轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/7010201.html 前面講到:Spring+SpringMVC+MyBatis深入學習及搭建(十二)——SpringMVC入門程式(一) 1.非註解的處理器映射器和適配器 1.1非註解的處理器映射器 前面我 ...
轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/7010201.html
前面講到:Spring+SpringMVC+MyBatis深入學習及搭建(十二)——SpringMVC入門程式(一)
1.非註解的處理器映射器和適配器
1.1非註解的處理器映射器
前面我們配置的org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping是非註解的處理器映射器。這種映射器其實有一個問題就是要一個bean裡面配置一個url。
現在我們再配置另一個非註解映射器
org.springframework.web.servlet.handler.SimpleUrlHandlerMapping,它會將url和handler集中進行配置。
<!-- 配置Handler --> <bean id="ItemsController1" name="/queryItems.action" class="joanna.yan.ssm.controller.ItemsController1"/> <!-- 配置處理器映射器 將bean的name作為url進行查找,需要在配置Handler時指定beanname(就是url) --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <!-- 簡單url映射 simpleUrlHandlerMapping是BeanNameUrlHandlerMapping的增強版, 它可以將url和處理器bean的id進行統一映射配置。 --> <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <!-- 對ItemsController1進行url映射,url是/queryItems1.action --> <prop key="/queryItems1.action">ItemsController1</prop> <prop key="/queryItems2.action">ItemsController1</prop> </props> </property> </bean>
疑問:可以同時配置這兩個映射器嗎?
解答:多個映射器可以並存,前端控制器判斷url能讓哪些映射器映射,就讓正確的映射器處理。
1.2非註解的處理器適配器
前面我們配置的org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter是一個非註解的適配器。它要求你編寫的Handler要實現Controller介面。
再說另一個非註解的適配器:
org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter。它要求編寫的Handler實現HttpRequestHandler介面。
public class ItemsController2 implements HttpRequestHandler{ @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //調用service查找資料庫,查詢商品列表,這裡使用靜態數據模擬 List<Items> itemsList=new ArrayList<Items>(); Items items_1=new Items(); items_1.setName("聯想筆記本"); items_1.setPrice(6000f); items_1.setDetail("ThinkPad T430 聯想筆記本電腦!"); Items items_2 = new Items(); items_2.setName("蘋果手機"); items_2.setPrice(5000f); items_2.setDetail("iphone6蘋果手機!"); itemsList.add(items_1); itemsList.add(items_2); //設置模型數據 request.setAttribute("itemsList", itemsList); //設置轉發的視圖 request.getRequestDispatcher("/WEB-INF/jsp/items/itemsList.jsp").forward(request, response); // 從上邊可以看出此適配器器的handleRequest方法沒有返回ModelAndView,可通過response修改定義響應內容,比如返回json數據: // response.setCharacterEncoding("utf-8"); // response.setContentType("application/json;charset=utf-8"); // response.getWriter().write("json串"); } }
在springmvc.xml中配置:
2.DispatcherServlet.properties
前端控制器從上邊的文件中載入處理映射器、適配器、視圖解析器等組件,如果不在springmvc.xml中配置,則使用預設載入的。
3.註解的處理器映射器和適配器
在spring3.1之前使用org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping註解映射器。
在spring3.1之後使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping註解映射器。
在spring3.1之前使用org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter註解適配器。
在spring3.1之後使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter註解適配器。
3.1配置註解映射器和適配器
<!--註解映射器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <!--註解適配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> <!--使用mvc:annotation-driven代替上邊註解映射器和註解適配器 配置 mvc:annotation-driven預設載入很多的參數綁定方法, 比如json轉換解析器就預設載入了,如果使用mvc:annotation-driven就不用配置上面的RequestMappingHandlerMapping和RequestMappingHandlerAdapter 實際開發時使用mvc:annotation-driven --> <!-- <mvc:annotation-driven></mvc:annotation-driven> -->
3.2開發註解Handler
使用註解的映射器和註解的適配器。(註解的映射器和註解的適配器必須配對使用,理解為不能使用非註解映射器進行映射)
/** * 開發註解Handler * 使用@Controller標明它是一個控制器 * @author Joanna.Yan * */ @Controller public class ItemsController3{ //商品查詢列表 //@RequestMapping實現對queryItems方法和url進行映射,一個方法對應一個url //一般建議將url和方法名寫成一樣,方便維護 @RequestMapping("/queryItems") public ModelAndView queryItems() throws Exception{ //調用service查找資料庫,查詢商品列表,這裡使用靜態數據模擬 List<Items> itemsList=new ArrayList<Items>(); Items items_1=new Items(); items_1.setName("聯想筆記本"); items_1.setPrice(6000f); items_1.setDetail("ThinkPad T430 聯想筆記本電腦!"); Items items_2 = new Items(); items_2.setName("蘋果手機"); items_2.setPrice(5000f); items_2.setDetail("iphone6蘋果手機!"); itemsList.add(items_1); itemsList.add(items_2); //返回ModelAndView ModelAndView modelAndView=new ModelAndView(); modelAndView.addObject("itemsList", itemsList); //指定視圖 modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp"); return modelAndView; } //定義其它方法 //商品添加 //商品修改 }
3.3在spring容器中載入Handler
<!-- 對於註解的Handler可以單個配置 實際開發中建議使用組件掃描 --> <!-- <bean class="joanna.yan.ssm.controller.ItemsController3" /> --> <!-- 可以掃描controller、service、... 這裡讓掃描controller,指定controller的包 --> <context:component-scan base-package="joanna.yan.ssm.controller"></context:component-scan>
使用組件掃描器省去在spring容器配置每個controller類的繁瑣。使用<context:component-scan/>自動掃描標記@Controller的控制類。
3.4 部署調試
訪問:http://localhost:8080/SpringMVC/jyqueryItems.action
註意:在測試過程中單個配置註解的Handler運行沒有問題,在配置組件掃描器運行時,啟動Tomcat報錯:
嚴重: Context initialization failed java.lang.IllegalArgumentException at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80) at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230) at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153) at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5266) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5554) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1258) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1918) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 六月 14, 2017 4:43:03 下午 org.apache.catalina.core.ApplicationContext log 嚴重: StandardWrapper.Throwable java.lang.IllegalArgumentException at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80) at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230) at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153) at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5266) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5554) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1258) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1918) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 六月 14, 2017 4:43:03 下午 org.apache.catalina.core.StandardContext loadOnStartup 嚴重: Servlet [springmvc] in web application [/SpringMVC] threw load() exception java.lang.IllegalArgumentException at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80) at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230) at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153) at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5266) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5554) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1258) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1918) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)View Code
原因是:我的Tomcat的jdk是1.8,項目的jdk版本是1.7,兩者不一樣造成的。記得要統一版本!
4.前端控制器源碼分析
通過前端控制器源碼分析springmvc的執行過程。
第一步:前端控制器接收請求
調用doDispatch
第二步:前端控制器調用處理器映射器查找Handler
第三步:調用處理器適配器執行Handler,得到執行結果ModeAndView
第四步:視圖渲染,將model數據填充到request域。
視圖解析,得到view:
調用view的渲染方法,將model數據填充到request域。
渲染方法:
5.視圖解析器配置首碼和尾碼
springmvc.xml中:
<!-- 配置視圖解析器 解析jsp視圖,預設使用jstl標簽,所有classpath下得有jstl的包 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--配置jsp路徑的首碼 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!--配置jsp路徑的尾碼 --> <property name="suffix" value=".jsp"/> </bean>
程式中不用指定首碼和尾碼:
//指定視圖 // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp"); //下邊的路徑,如果在視圖解析器中配置jsp路徑的首碼和jsp路徑的尾碼,修改為 modelAndView.setViewName("items/itemsList");
如果此文對您有幫助,微信打賞我一下吧~