web.xml配置
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
bean配置:
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> <bean id="simpleUrlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/hello">helloController</prop> </props> </property> </bean> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> <bean id="helloController" class="com.soo.sailing.ui.item.HelloTestController"></bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"></property> <property name="suffix" value=".jsp"></property> </bean>
Controller
public class HelloTestController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ModelAndView mav = new ModelAndView("index"); mav.addObject("UserName","Spring MVC"); return mav; } }
请求/hello时出错。
06:24:54.968 [http-nio-8282-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/hello", parameters={} 06:24:54.968 [http-nio-8282-exec-6] DEBUG org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped to com.soo.sailing.ui.item.HelloTestController@355669ff 06:24:54.968 [http-nio-8282-exec-6] DEBUG org.springframework.web.servlet.view.InternalResourceView - View name 'index', model {UserName=Spring MVC} 06:24:54.969 [http-nio-8282-exec-6] DEBUG org.springframework.web.servlet.view.InternalResourceView - Forwarding to [/WEB-INF/index.jsp] 06:24:54.969 [http-nio-8282-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - "FORWARD" dispatch for GET "/WEB-INF/index.jsp", parameters={} 06:24:54.969 [http-nio-8282-exec-6] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /WEB-INF/index.jsp 06:24:54.969 [http-nio-8282-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - Exiting from "FORWARD" dispatch, status 404 06:24:54.969 [http-nio-8282-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND
本意是请求/hello,DispatcherServlet请请求map到HelloTestController, HelloTestController返回index View,index view对应WEB-INF目录下的index.jsp。 不过springmvc并不是直接display index.jsp而是做了一个forward请求到 /WEB-INF/index.jsp. 这个forward请求被DispatcherServlet捕获(因为它捕获/*的url-pattern)并交由HandlerMapping处理。由于没有定义对应的mapping,所以就抛出PageNotFound - No maping for GET /WEB-INF/index.jsp的错和404状态。
1)当修改url-pattern从/*改为/时,在forward/WEB-INF/index.jsp请求时就能直接display index.jsp
2)如果不修改url-pattern, 而是在serlvet配置bean文件中添加<mvc:default-servlet-handler/>就会交由web容器来处理,也可以成功。