재인쇄할 소스를 표시해 주세요:
앞서 언급한 대로: Spring+SpringMVC+MyBatis 심층 학습 및 구성(12) - SpringMVC 진입 프로그램(1)
앞서 구성한 org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping은 주석이 없는 프로세서 매퍼입니다. 실제로 이런 종류의 매퍼의 문제점은 빈에 URL을 구성해야 한다는 것입니다.
이제 URL과 핸들러를 중앙에서 구성하는 주석이 아닌 또 다른 매퍼
org.springframework.web.servlet.handler.SimpleUrlHandlerMapping을 구성합니다.
<!-- 配置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이 매핑할 수 있는 매퍼를 결정하고 올바른 매퍼가 이를 처리하도록 합니다.
앞서 구성한 org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter는 주석이 없는 어댑터입니다. 작성하는 핸들러는 컨트롤러 인터페이스를 구현해야 합니다.
주석이 없는 또 다른 어댑터인
org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter에 대해 이야기해 보겠습니다. 작성된 핸들러가 HttpRequestHandler 인터페이스를 구현해야 합니다.
public class ItemsController2 implements HttpRequestHandler{ @Overridepublic 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에 구성됨:
프론트 엔드 컨트롤러는 위 파일에서 처리 매퍼, 어댑터, 뷰 리졸버 및 기타 구성 요소를 로드합니다. springmvc.xml에 구성되지 않은 경우 기본 로드된 항목이 사용됩니다.
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 주석 어댑터를 사용하세요.
<!--注解映射器 --><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> -->
주석이 있는 매퍼 및 어댑터를 사용하세요. (주석이 있는 매퍼와 주석이 달린 어댑터는 쌍으로 사용해야 합니다. 주석이 없는 매퍼는 매핑에 사용할 수 없다는 점을 이해합니다.)
/** * 开发注解Handler * 使用@Controller标明它是一个控制器 * @author Joanna.Yan * */@Controllerpublic 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);//返回ModelAndViewModelAndView modelAndView=new ModelAndView(); modelAndView.addObject("itemsList", itemsList);//指定视图modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");return modelAndView; }//定义其它方法//商品添加//商品修改}
<!-- 对于注解的Handler可以单个配置 实际开发中建议使用组件扫描 --><!-- <bean class="joanna.yan.ssm.controller.ItemsController3" /> --><!-- 可以扫描controller、service、... 这里让扫描controller,指定controller的包 --><context:component-scan base-package="joanna.yan.ssm.controller"></context:component-scan>
컴포넌트 스캐너를 사용하여 저장 스프링 컨테이너에 로딩이 필요합니다. 각 컨트롤러 클래스를 구성하는 것은 번거롭습니다. @Controller로 표시된 컨트롤 클래스를 자동으로 검색하려면
방문: http://localhost:8080/SpringMVC/jyqueryItems.action
참고: 테스트 프로세스 중에 단일 구성 주석 처리기가 실행되는 데 문제가 없습니다. 구성 구성 요소 스캐너가 실행 중이면 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)
原因是:我的Tomcat的jdk是1.8,项目的jdk版本是1.7,两者不一样造成的。记得要统一版本!
通过前端控制器源码分析springmvc的执行过程。
第一步:前端控制器接收请求
调用doDispatch
第二步:前端控制器调用处理器映射器查找Handler
第三步:调用处理器适配器执行Handler,得到执行结果ModeAndView
第四步:视图渲染,将model数据填充到request域。
视图解析,得到view:
调用view的渲染方法,将model数据填充到request域。
渲染方法:
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");
위 내용은 Spring+SpringMVC+MyBatis 심층학습 및 구축 - SpringMVC 진입 프로그램(2)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!