paulwong

开始Spring MVC

建立一个web project,并导入spring 3.x的jar包配置web.xml根据上面的spring mvc流程图,我们知道DispatcherServlet是spring mvc 的一个前端控制器,所以我们当然要去配置它,以便于将请求转给DispatcherServlet处理

  <servlet>
    
<servlet-name>dispatcher</servlet-name>
    
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    
<init-param>
        
<param-name>contextConfigLocation</param-name>
<!-- 如果配置文件位于classpath下,可以这么写: classpath:dispatcher.xml -->
        
<param-value>/WEB-INF/dispatcher.xml</param-value>
    
</init-param>
    
<load-on-startup>1</load-on-startup>
  
</servlet>

  
<servlet-mapping>
    
<servlet-name>dispatcher</servlet-name>
    
<url-pattern>/</url-pattern>
  
</servlet-mapping>

注:由于DispatcherServlet在初始化的过程中需要一个配置文件来生产文件中的各种bean,并生成WebApplicationContext对象,保存到ServletContext中(如果DispatcherServlet有多个,那么每一个DispatcherServlet都对应一个WebApplicationContext),我们可以在Servlet的init-param中配置配置文件的路径,当然如果我们没有配置Init-Param,它会默认到WEB-INF的文件夹中找[servletname]-servlet.xml文件,例如上面如果我们没有配置,则会去寻找dispatcher-servlet.xml这个配置文件。(在init-param中我们可以指定多个配置文件,用逗号分隔也可以使用通配符*)
配置上文中我们指定的所需的dispatcher.xml文件

<?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:p="http://www.springframework.org/schema/p"
xmlns:context
="http://www.springframework.org/schema/context"
xmlns:mvc
="http://www.springframework.org/schema/mvc"
xsi:schemaLocation
="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
>

    
<context:component-scan base-package="com.controls" />
    
<mvc:annotation-driven />
    
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       
<property name="prefix" value="/WEB-INF/views/"></property>
       
<property name="suffix" value=".jsp"></property>
       
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
    
</bean>
</beans>



配置文件说明:
<context:component-scan base-package="com.controls" />
由于我们使用了基于注解的Controller,所以这里指定了需要被扫描的包路径,如果有多个可以使用逗号分隔
<mvc:annotation-driven />

上面的spring mvc流程图中我们知道DispatcherServlet接管请求后,会由HandlerMapping来执行映射,所以我们需要注册HanlderMapping,比如上面的标签会自动注册比如DefaultAnnotationHandlerMapping(执行请求到Controller的映射)和AnnotationMethodHandlerAdapter(调用controller中的方法)这样的bean,当然这个标签还提供了其他的一些支持(更多介绍请参照spring官方文档第455页)。

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

       
<property name="prefix" value="/WEB-INF/views/"></property>

       
<property name="suffix" value=".jsp"></property>

       
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>

</bean>

上面spring mvc流程图的最后controller处理完毕后会交给一个ViewResolver进行处理,大体上是解析视图逻辑名并经过一定的处理获取一个视图,这里的意思是设置视图用jsp来处理(比如我们设置viewClass为JstlView)来进行处理,就是以forward的形式转发给jsp,这个地址是:/WEB-INF/views/[controller返回值].jsp ,当然视图解析器可以定义多个,(视图解析器不会处理ModelAndView中已经设置了View的请求,因为已经有View来处理了,那当然就不需要它来解析到真正的视图View啦)
编写Controller控制器这里我们使用例子的形式来说明

实现一个控制器类@Controller
@Controller
@RequestMapping(
"/user")
public class UserControl {

}

只要给类加上Controller的注解,并放在被扫描的包中,那么这个类就是一个控制器了,RequestMapping表明匹配的路径,可以写在类或者类的方法上,如果类上面有RequestMapping注解,那么其下面的方法就是相对于类上面注解地址的一个相对路径


定义一个接管请求的方法方法名:无任何要求
--------------------------------------------------------------
参数:(顺序以及个数无任何要求)
HttpServletRequest
HttpServletResponse
PrintWriter 相当于HttpResponse.getWriter()获得的对象
Map 其实是获得了ModelAndView中的Model
BindingResult 绑定数据的处理结果
HttpSession 如果使用此参数,需要注意如果是第一次访问还没有session的话会报错
@PathVariable 用于接收路径变量
@RequestParam 相当于调用request.getParameter(“name”)方法
@CookieValue 获取cookie的值
@RequestHeader 获取header中的值
实体对象 会根据请求的参数名,注入到这个对象对于得属性中,必须提供set方法
等等等等等
--------------------------------------------------------------
返回值:
void
返回值是void,如果接收了PrintWriter 或者 HttpServletResponse 参数,那么返回的ModelAndView就是null,也就是直接将输出流输出到客户端,如果方法没有接收输出参数,后面会默认生成一个视图名

String 视图逻辑名

ModelAndView 是一个视图逻辑名+Map的封装类
其他任意类型 存入ModelAndView中的Model
--------------------------------------------------------------

不管我们的返回类型是什么,返回值会通过处理,最终返回一个ModelAndView或者null
例1:给方法定义一个请求映射并使用路径变量 @RequestMapping("/id/{userid}/name/{username}")

@RequestMapping("/id/{userid}/name/{username}")
public String queryUser(@PathVariable("userid"long userID, @PathVariable("username") String userName, Map<String, User> model) {
       User user 
= new User();
       user.setUserID(userID);
       user.setUserName(userName);
       model.put(
"userInfo", user);
       
return "Home";
    }


@RequestMapping定义路由映射,其中{userid} {username} 是PathVariable(路径变量)
这样我们只需访问 http://localhost:8080/SpringMVC/user/id/10001/name/liudehua 就能进入上面的方法
RequestMapping还可以使用通配符,如: /test/*/name/{name}

例2:接受请求参数@RequestMapping("/save")
@RequestMapping("/save")
public String save(@RequestParam("userName") String userName,@RequestParam("Age"int age) {
       System.out.println(userName);
       System.out.println(age);
       
return "Home";
}


例3:请求参数直接注入到Model@RequestMapping("/save")
@RequestMapping("/save")
public String save(User user) {
       System.out.println(user.getUserID());
       System.out.println(user.getUserName());
       
return "Home";
}

例4:转发与重定向转发: (相当于 request.getRequestDispatcher(“”).forward(request, response))
return “forward:/user/test”;

重定向: (相当于response.redirect(“”))
return “redirect:/user/test”
return “redirect:http://www.google.com.hk”;

例5:根据HttpMethod来过滤请求
@RequestMapping(params="hello=world", method={RequestMethod.GET, RequestMethod.POST}
public String helloworld() {
}
 


例6:根据参数来进行过滤
@RequestMapping(params="hello=world", method={RequestMethod.GET, RequestMethod.POST})  
public String helloworld() {
}
  

必须有个hello的参数并且名称为world,而且只能是get或post请求才会进入此方法

http://www.cnblogs.com/zhaoyang/archive/2012/01/07/2315425.html

posted on 2012-03-29 19:06 paulwong 阅读(1148) 评论(0)  编辑  收藏 所属分类: SPRING MVC


只有注册用户登录后才能发表评论。


网站导航: