spring mvc示例_servlet获取spring Bean

示例代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
 
  <!--  创建springmvc 需要一个xml文件和applicationContext.xml 这里要理解initparam的含义
        mvc*.* 就是去寻找为mvc开头的文件,所有所创建的spring mvc的xml文件必须要有mvc开头
        命名为:mvc-context.xml 并且按照context-param中的配置,将applicationContext文件
        命名为:root-context.xml -->
  
  <!-- 监听spring 上下文容器 -->
  <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 加载spring 的xml配置文件到 spring的上下文容器中-->
  <context-param>
     <param-name>contextConfigLocation</param-name>
     <!-- 这里指定的classpath 为项目编译后的classes目录 -->
     <param-value>classpath:root-context.xml</param-value>
  </context-param>
  
  <!-- 首先在web.xml中配置一个DispatcherServlet -->
  <!-- 核心类,spring mvc DispatcherServlet -->
  <servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/classes/mvc*.*</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>UserAuthorizationFilter</servlet-name>
    <servlet-class>com.qingyuan.controller.UserAuthorizationFilter</servlet-class>
  </servlet>

  <servlet-mapping>
     <servlet-name>mvc</servlet-name>
     <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UserAuthorizationFilter</servlet-name>
    <url-pattern>/servlet/auth</url-pattern>
  </servlet-mapping>
  
  <filter>   
    <filter-name>CharacterEncodingFilter</filter-name>   
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>   
    <init-param>   
        <param-name>encoding</param-name>   
        <param-value>utf-8</param-value>   
    </init-param>   
  </filter>   
  <filter-mapping>   
    <filter-name>CharacterEncodingFilter</filter-name>   
    <url-pattern>/*</url-pattern>   
  </filter-mapping>  
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>  
<beans:beans xmlns="http://www.springframework.org/schema/mvc"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"  
    xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
                http://www.springframework.org/schema/mvc/spring-mvc.xsd  
                http://www.springframework.org/schema/aop  
                http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
                http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd  
                http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context.xsd">
      
   <!-- 首先通过import标签 导入root-context.xml,然后通过component-scan标签扫描指定包名,
        让该包下的所有java类的spring注解生效然后配置SpringMVC的视图渲染解析器,
        让其前缀为/page/ 后缀为.jsp 这样能够SpringMVC 所需要渲染的路径能够在/page/返回值.jsp中寻找 --> 
        
   <!-- 加载spring 的全局配置文件 -->
   <beans:import resource="root-context.xml"/>     
     
   <!-- 通过component-scan 让spring扫描com.qingyuan.controller下的所有类
        让spring 的代码注解生效 -->
   <context:component-scan base-package="com.qingyuan.controller" />   
   
    <!-- 配置SpringMVC的视图渲染器, 让其前缀为:/ 后缀为.jsp  将视图渲染到/page/<method返回值>.jsp中 -->  
    <beans:bean  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
        p:prefix="/page/" p:suffix=".jsp">  
   
   </beans:bean>
</beans:beans>

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
                    http://www.springframework.org/schema/context  
                     http://www.springframework.org/schema/context/spring-context-3.2.xsd  
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> 
  
  	<bean id="userController"
		class="com.qingyuan.controller.UserController">
	</bean>               
</beans>     

package com.qingyuan.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 *  使用注解@Controller 将HomeController 类定义为一个Controller,并且在方法中通过
 *  @RequestMapping("value") 来指定所需要访问的路径或者方法名称,springmvc 可以
 *  通过一个@controller注解将一个POJO转化为处理请求的控制器,通过@RequestMapping
 *  为控制器指定哪些需要的请求
 */

@Controller
public class HomeController {

	/**
	 * 返回到 /page/home.jsp
	 * 方法中定义了ModelAndView对象,
	 * 通过该对象指定所需要渲染的视图为home最后返回ModelAndView 
	 * 将页面渲染到home.jsp中
	 * @return
	 */
	@RequestMapping("index")
	public ModelAndView index()
	{
		// 创建模型跟视图,用于渲染页面,并且指定要返回的页面为home页面
		ModelAndView mav = new ModelAndView("home");
		return mav;
	}
}

package com.qingyuan.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *  servlet 容器中获取spring 容器中的Bean
 */
public class UserAuthorizationFilter extends HttpServlet {

	private WebApplicationContext wac;

	private static final long serialVersionUID = 2330673658987873853L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

            this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=gbk");
		
		// PrintWriter out = response.getWriter();
		// com.qingyuan.controller.UserController@163de4e
		UserController userController = (UserController)wac.getBean("userController");

	}

	@Override
	public void init() throws ServletException {
	
	       wac =WebApplicationContextUtils.getRequiredWebApplicationContext(
	       this.getServletContext());

	       // wac = WebApplicationContextUtils.getWebApplicationContext(
	       // this.getServletContext());

	       // wac的类型:org.springframework.web.context.support.XmlWebApplicationContext
               // super.init();
	}

}

package com.qingyuan.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

// http://jinnianshilongnian.iteye.com/blog/1594806
@Controller
public class UserController {

	@RequestMapping("login")
	public ModelAndView login(String username, String password)
	{
		if (this.checkParams(new String[]{username, password}))
		{
			ModelAndView mav = new ModelAndView("succ");
			mav.addObject("username", username);
			mav.addObject("password", password);
			return mav;
		}
		
		return new ModelAndView("home");
	}

	@RequestMapping(value="login2222",method=RequestMethod.POST)  
	public ModelAndView login(String username,String password,HttpServletRequest request)
	{  
	    request.setAttribute("username", username);  
	    request.setAttribute("password", password);  
	    
	    return new ModelAndView("succ");  
	}  
	
	private boolean checkParams(String[] params) {
		
		   for (String param:params)
		   {  
	            if (param == "" || param==null || param.isEmpty())
	            {  
	                return false;  
	            }  
	        }  
	        return true;  
	}
}

http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html
http://docs.spring.io/spring/docs/4.0.9.RELEASE/spring-framework-reference/htmlsingle/
http://projects.spring.io/spring-framework/

SpringMVC框架是围绕DispatcherServlet这个核心展开,DispatcherServlet这个Servlet负责拦截请求,并将其分派给相应的处
理类来处理

SpringMVC是基于Model2实现的技术框架,Model2是经典的MVC模型在Web应用中的变体,这个改变主要源于HTTP协议的无状态
性。Model2的目的和MVC一样,也是利用处理器分离模型(Model)、视图(View)和控制(Control),达到不同技术层级间松散层
耦合的效果,让系统更有灵活、复用性和可维护性.


分析:

1、 由最先的HTPP发送请求,由所配置的XML中的DispatcherServlet处理。
2、 DispatcherServlet接受到这个请求后,根据请求的信息及HandlerMapping的配置找到处理请求的处理器Handler。
3、 得到HandlerMapping对应的Handler后,通过HandlerAdapter对Handler进行封装,再以统一的适配器接口调用Handler。
4、 处理器完成业务逻辑的处理后返回一个ModelAndView给DispatcherServlet。
5、 ModelAndView包含逻辑视图名,而非真正的视图对象,DispatcherServlet借由ViewResolver完成逻辑视图名到真实视
    图对象的解析工作。
6、 当得到真实View对象后,DispatcherServlet就对这个View对象进行渲染
7、 最终返回到客户的HTTP响应

参考博文" http://blog.csdn.net/swingpyzf/article/details/8885459

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值