`
snoopy7713
  • 浏览: 1125388 次
  • 性别: Icon_minigender_2
  • 来自: 火星郊区
博客专栏
Group-logo
OSGi
浏览量:0
社区版块
存档分类
最新评论

深入理解Spring MVC 3(三)

阅读更多

十二、如何把全局异常记录到日志中?

在 前的配置中,其中有一个属性warnLogCategory,值是“SimpleMappingExceptionResolver类的全限定名”。我是 在SimpleMappingExceptionResolver类父类AbstractHandlerExceptionResolver类中找到这个 属性的。查看源码后得知:如果warnLogCategory不为空,spring就会使用apache的 org.apache.commons.logging.Log日志工具,记录这个异常,级别是warn。

值:“org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”,是“SimpleMappingExceptionResolver类的全限定名”。这个值不是随便写的。  因 为我在log4j的配置文件中还要加入 log4j.logger.org.springframework.web.servlet.handler.SimpleMappingExceptionResolver=WARN, 保证这个级别是warn的日志一定会被记录,即使log4j的根日志级别是ERROR。

 

 

 

 

 十三、如何给spring3 MVC中的Action做JUnit单元测试?

 使用了spring3 MVC后,给action做单元测试也很方便,我以前从来不给action写单元测试的,再在不同了,方便了,所以一定要写。

 

 JUnitActionBase类是所有JUnit的测试类的父类

 

Java代码  收藏代码
  1. package test;    
  2. import javax.servlet.http.HttpServletRequest;    
  3. import javax.servlet.http.HttpServletResponse;    
  4. import org.junit.BeforeClass;    
  5. import org.springframework.mock.web.MockServletContext;    
  6. import org.springframework.web.context.WebApplicationContext;    
  7. import org.springframework.web.context.support.XmlWebApplicationContext;    
  8. import org.springframework.web.servlet.HandlerAdapter;    
  9. import org.springframework.web.servlet.HandlerExecutionChain;    
  10. import org.springframework.web.servlet.HandlerMapping;    
  11. import org.springframework.web.servlet.ModelAndView;    
  12. import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;    
  13. import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;    
  14. /**   
  15. * 说明: JUnit测试action时使用的基类  
  16. *   
  17. * @author  赵磊  
  18. * @version 创建时间:2011-2-2 下午10:27:03    
  19. */     
  20. public class JUnitActionBase {    
  21.     private static HandlerMapping handlerMapping;    
  22.     private static HandlerAdapter handlerAdapter;    
  23.     /**  
  24.      * 读取spring3 MVC配置文件  
  25.      */    
  26.     @BeforeClass    
  27.  public static void setUp() {    
  28.         if (handlerMapping == null) {    
  29.             String[] configs = { "file:src/springConfig/springMVC.xml" };    
  30.             XmlWebApplicationContext context = new XmlWebApplicationContext();    
  31.             context.setConfigLocations(configs);    
  32.             MockServletContext msc = new MockServletContext();    
  33.             context.setServletContext(msc);         context.refresh();    
  34.             msc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);    
  35.             handlerMapping = (HandlerMapping) context    
  36.                     .getBean(DefaultAnnotationHandlerMapping.class);    
  37.             handlerAdapter = (HandlerAdapter) context.getBean(context.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);       
  38.         }    
  39.     }    
  40.     
  41.     /**  
  42.      * 执行request对象请求的action  
  43.      *   
  44.      * @param request  
  45.      * @param response  
  46.      * @return  
  47.      * @throws Exception  
  48.      */    
  49.     public ModelAndView excuteAction(HttpServletRequest request, HttpServletResponse response)    
  50.  throws Exception {    
  51.         HandlerExecutionChain chain = handlerMapping.getHandler(request);    
  52.         final ModelAndView model = handlerAdapter.handle(request, response,    
  53.                 chain.getHandler());    
  54.         return model;    
  55.     }    
  56. }    

 

这是个JUnit测试类,我们可以new Request对象,来参与测试,太方便了。给request指定访问的URL,就可以请求目标Action了。

  1. package test.com.app.user;  
  2. import org.junit.Assert;  
  3. import org.junit.Test;  
  4. import org.springframework.mock.web.MockHttpServletRequest;  
  5. import org.springframework.mock.web.MockHttpServletResponse;  
  6. import org.springframework.web.servlet.ModelAndView;  
  7.   
  8. import test.JUnitActionBase;  
  9.   
  10. /**  
  11. * 说明: 测试OrderAction的例子 
  12.  
  13. * @author  赵磊  
  14. * @version 创建时间:2011-2-2 下午10:26:55   
  15. */   
  16.   
  17. public class TestOrderAction extends JUnitActionBase {  
  18.     @Test  
  19.     public void testAdd() throws Exception {  
  20.     MockHttpServletRequest request = new MockHttpServletRequest();  
  21.         MockHttpServletResponse response = new MockHttpServletResponse();  
  22.         request.setRequestURI("/order/add");  
  23.         request.addParameter("id""1002");  
  24.         request.addParameter("date""2010-12-30");  
  25.         request.setMethod("POST");  
  26.         // 执行URI对应的action  
  27.         final ModelAndView mav = this.excuteAction(request, response);  
  28.         // Assert logic  
  29.         Assert.assertEquals("order/add", mav.getViewName());  
  30.         String msg=(String)request.getAttribute("msg");  
  31.         System.out.println(msg);  
  32.     }  
  33. }  

 

需要说明一下 :由于当前最想版本的 Spring(Test) 3.0.5还不支持@ContextConfiguration的注解式context file注入,所以还需要写个setUp处理下,否则类似于Tiles的加载过程会有错误,因为没有ServletContext。3.1的版本应该有更 好的解决方案,参见: https://jira.springsource.org/browse/SPR-5243 

参考 :http://www.iteye.com/topic/828513

 

十四、转发与重定向

可以通过redirect/forward:url方式转到另一个Action进行连续的处理。

可以通过redirect:url 防止表单重复提交 

写法如下:

return "forward:/order/add";

return "redirect:/index.jsp";

 

 

 

 

 十五、处理ajax请求

 

1、引入下面两个jar包,我用的是1.7.2,好像1.4.2版本以上都可以,下载地址: http://wiki.fasterxml.com/JacksonDownload

jackson-core-asl-1.7.2.jar 

jackson-mapper-asl-1.7.2.jar

 

2、spring的配置文件中要有这一行,才能使用到spring内置支持的json转换。如果你手工把POJO转成json就可以不须要使用spring内置支持的json转换。

<mvc:annotation-driven />

 

3、使用@ResponseBody注解

Java代码  收藏代码
  1. /**  
  2.  * ajax测试  
  3. * http://127.0.0.1/mvc/order/ajax  
  4.  */    
  5.     
  6. @RequestMapping("/ajax")    
  7. @ResponseBody    
  8. public Object ajax(HttpServletRequest request){    
  9.     List<String> list=new ArrayList<String>();    
  10.     list.add("电视");    
  11. nbsp;       list.add("洗衣机");    
  12.     list.add("冰箱");    
  13.     list.add("电脑");    
  14.     list.add("汽车");    
  15.     list.add("空调");    
  16.     list.add("自行车");    
  17.     list.add("饮水机");    
  18.     list.add("热水器");    
  19.     return list;    
  20. }    

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics