springMVC3 注解的使用

SpringMVC注解使用
web.xml 配置:
1. <servlet> 
2.     <servlet-name>dispatcher</servlet-name> 
3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
4.     <init-param> 
5.         <description>加载/WEB-INF/spring-mvc/目录下的所有XML作为Spring MVC的配置文件</description> 
6.         <param-name>contextConfigLocation</param-name> 
7.         <param-value>/WEB-INF/spring-mvc/*.xml</param-value> 
8.     </init-param> 
9.     <load-on-startup>1</load-on-startup> 
10. </servlet> 
11. <servlet-mapping> 
12.     <servlet-name>dispatcher</servlet-name> 
13.     <url-pattern>*.htm</url-pattern> 
14. </servlet-mapping> 

这样,所有的.htm的请求,都会被DispatcherServlet处理;
初始化 DispatcherServlet 时,该框架在 web 应用程序WEB-INF 目录中寻找一个名为[servlet-名称]-servlet.xml的文件,并在那里定义相关的Beans,重写在全局中定义的任何Beans,像上面的web.xml中的代码,对应的是dispatcher-servlet.xml;当然也可以使用<init-param>元素,手动指定配置文件的路径;
dispatcher-servlet.xml 配置:
1. <?xml version="1.0" encoding="UTF-8"?> 
2. <beans xmlns="http://www.springframework.org/schema/beans" 
3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
4.        xmlns:mvc="http://www.springframework.org/schema/mvc" 
5.        xmlns:p="http://www.springframework.org/schema/p" 
6.        xmlns:context="http://www.springframework.org/schema/context" 
7.        xmlns:aop="http://www.springframework.org/schema/aop" 
8.        xmlns:tx="http://www.springframework.org/schema/tx" 
9.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
10.             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
11.             http://www.springframework.org/schema/context   
12.             http://www.springframework.org/schema/context/spring-context-3.0.xsd  
13.             http://www.springframework.org/schema/aop   
14.             http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
15.             http://www.springframework.org/schema/tx   
16.             http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
17.             http://www.springframework.org/schema/mvc   
18.             http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
19.             http://www.springframework.org/schema/context   
20.             http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
21.     <!-- 
22.         使Spring支持自动检测组件,如注解的Controller 
23.     --> 
24.     <context:component-scan base-package="com.minx.crm.web.controller"/> 
25.      
26.     <bean id="viewResolver" 
27.           class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
28.           p:prefix="/WEB-INF/jsp/" 
29.           p:suffix=".jsp" /> 
30. </beans> 

第一个Controller:
1. package com.minx.crm.web.controller;  
2.  
3. import org.springframework.stereotype.Controller;  
4. import org.springframework.web.bind.annotation.RequestMapping;  
5. @Controller 
6. public class IndexController {  
7.     @RequestMapping("/index")  
8.     public String index() {  
9.         return "index";  
10.     }  
11. } 
@Controller注解标识一个控制器,@RequestMapping注解标记一个访问的路径(/index.htm),return "index"标记返回视图(index.jsp);
注:如果@RequestMapping注解在类级别上,则表示一相对路径,在方法级别上,则标记访问的路径;
从@RequestMapping注解标记的访问路径中获取参数:
Spring MVC 支持RESTful风格的URL参数,如:
1. @Controller 
2. public class IndexController {  
3.  
4.     @RequestMapping("/index/{username}")  
5.     public String index(@PathVariable("username") String username) {  
6.         System.out.print(username);  
7.         return "index";  
8.     }  
9. } 
在@RequestMapping中定义访问页面的URL模版,使用{}传入页面参数,使用@PathVariable 获取传入参数,即可通过地址:http://localhost:8080/crm/index/tanqimin.htm 访问;
根据不同的Web请求方法,映射到不同的处理方法:
使用登陆页面作示例,定义两个方法分辨对使用GET请求和使用POST请求访问login.htm时的响应。可以使用处理GET请求的方法显示视图,使用POST请求的方法处理业务逻辑;
1. @Controller 
2. public class LoginController {  
3.     @RequestMapping(value = "/login", method = RequestMethod.GET)  
4.     public String login() {  
5.         return "login";  
6.     }  
7.     @RequestMapping(value = "/login", method = RequestMethod.POST)  
8.     public String login2(HttpServletRequest request) {  
9.             String username = request.getParameter("username").trim();  
10.             System.out.println(username);  
11.         return "login2";  
12.     }  
13. } 
在视图页面,通过地址栏访问login.htm,是通过GET请求访问页面,因此,返回登陆表单视图login.jsp;当在登陆表单中使用POST请求提交数据时,则访问login2方法,处理登陆业务逻辑;
防止重复提交数据,可以使用重定向视图:
1. return "redirect:/login2" 
可以传入方法的参数类型:
1. @RequestMapping(value = "login", method = RequestMethod.POST)  
2. public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {  
3.     String username = request.getParameter("username");  
4.     System.out.println(username);  
5.     return null;  
6. } 


可以传入HttpServletRequest、HttpServletResponse、HttpSession,值得注意的是,如果第一次访问页面,HttpSession没被创建,可能会出错;
其中,String username = request.getParameter("username");可以转换为传入的参数:

1. @RequestMapping(value = "login", method = RequestMethod.POST)  
2. public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,@RequestParam("username") String username) {  
3.     String username = request.getParameter("username");  
4.     System.out.println(username);  
5.     return null;  
6. } 

使用@RequestParam 注解获取GET请求或POST请求提交的参数;
获取Cookie的值:使用@CookieValue :
获取PrintWriter:
可以直接在Controller的方法中传入PrintWriter对象,就可以在方法中使用:
1. @RequestMapping(value = "login", method = RequestMethod.POST)  
2. public String testParam(PrintWriter out, @RequestParam("username") String username) {  
3.     out.println(username);  
4.     return null;  
5. } 


获取表单中提交的值,并封装到POJO中,传入Controller的方法里:
POJO如下(User.java):
1. public class User{  
2.     private long id;  
3.     private String username;  
4.     private String password;  
5.  
6.     …此处省略getter,setter...  
7. } 


通过表单提交,直接可以把表单值封装到User对象中:
1. @RequestMapping(value = "login", method = RequestMethod.POST)  
2. public String testParam(PrintWriter out, User user) {  
3.     out.println(user.getUsername());  
4.     return null;  
5. } 


可以把对象,put 入获取的Map对象中,传到对应的视图:
1. @RequestMapping(value = "login", method = RequestMethod.POST)  
2. public String testParam(User user, Map model) {  
3.     model.put("user",user);  
4.     return "view";  
5. } 

在返回的view.jsp中,就可以根据key来获取user的值(通过EL表达式,${user }即可);
Controller中方法的返回值:
void:多数用于使用PrintWriter输出响应数据;
String 类型:返回该String对应的View Name;
任意类型对象:
返回ModelAndView:
自定义视图(JstlView,ExcelView):
拦截器(Inteceptors):
1. public class MyInteceptor implements HandlerInterceptor {  
2.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)   
3.         throws Exception {  
4.         return false;  
5.     }  
6.     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav)   
7.         throws Exception {  
8.     }  
9.     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn)   
10.         throws Exception {  
11.     }  
12. } 

拦截器需要实现HandleInterceptor接口,并实现其三个方法:
preHandle:拦截器的前端,执行控制器之前所要处理的方法,通常用于权限控制、日志,其中,Object o表示下一个拦截器;
postHandle:控制器的方法已经执行完毕,转换成视图之前的处理;
afterCompletion:视图已处理完后执行的方法,通常用于释放资源;
在MVC的配置文件中,配置拦截器与需要拦截的URL:
1. <mvc:interceptors> 
2.     <mvc:interceptor> 
3.         <mvc:mapping path="/index.htm" /> 
4.         <bean class="com.minx.crm.web.interceptor.MyInterceptor" /> 
5.     </mvc:interceptor> 
6. </mvc:interceptors> 

国际化:
在MVC配置文件中,配置国际化属性文件:
1. <bean id="messageSource" 
2.     class="org.springframework.context.support.ResourceBundleMessageSource" 
3.     p:basename="message"> 
4. </bean> 

猜你喜欢

转载自kfyfly.iteye.com/blog/1038811
今日推荐