配置处理器映射器
在classpath:springmvc.xml中配置处理器映射器、处理器适配器、视图解析器。
三者顺序无所谓。注意dispatcherServlet.xml的约束。
<1>配置处理器适配器和处理器映射器
下面内容引自https://my.oschina.net/HeliosFly/blog/205343
<!-- 开启注解 -->
<!-- springmvc使用<mvc:annotation-driven> -->
<!-- 自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter, -->
<!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 -->
<mvc:annotation-driven/>
mvc:annotation-driven注解解读
通常如果我们希望通过注解的方式来进行Spring MVC开发,我们都会在*-servlet.xml中加入标签来告诉Spring我们的目的。但是我们为什么这么做呢?这个标签是什么意思呢?它做了什么呢?
同样为了弄清楚这些问题, 我们先找到它的解析类。所有的自定义命名空间(像mvc,context等)下的标签解析都是由BeanDefinitionParser接口的子类来完成的。
我们看到有多个AnnotationDrivenBeanDefinitionParser,他们是用来处理不同命名空间下的标签的,我们今天研究的是标签,所以我们找到对应的实现类是org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser。
通过阅读类注释文档,我们发现这个类主要是用来向工厂中注册了
//两个处理器映射器,HandlerMapping接口的实现类,用来处理请求映射的
//第一个是处理@RequestMapping注解的
RequestMappingHandlerMapping
//第二个会将controller类的名字映射为请求url
BeanNameUrlHandlerMapping
//三个处理器适配器,都实现HandlerAdapter接口,确定调用哪个controller的哪个方法来处理当前请求
//第一个处理@Controller注解的处理器,支持自定义方法参数和返回值(很酷)
RequestMappingHandlerAdapter
//第二个是处理继承HttpRequestHandler的处理器
HttpRequestHandlerAdapter
//第三个处理继承自Controller接口的处理器
SimpleControllerHandlerAdapter
//后面三个是用来处理异常的解析器
ExceptionHandlerExceptionResolver
ResponseStatusExceptionResolver
DefaultHandlerExceptionResolver
上面几个Bean实例。这几个类都是用来做什么的呢?
前两个是HandlerMapping接口的实现类,用来处理请求映射的。其中第一个是处理@RequestMapping注解的。第二个会将controller类的名字映射为请求url。
中间三个是用来处理请求的,即三个处理器适配器。具体点说就是确定调用哪个controller的哪个方法来处理当前请求。
第一个处理@Controller注解的处理器,支持自定义方法参数和返回值(很酷)。
第二个是处理继承HttpRequestHandler的处理器。
第三个处理继承自Controller接口的处理器。
后面三个是用来处理异常的解析器。
<2>配置handler
开发handler时要按照HandlerAdapter的要求开发
@Controller
@RequestMapping(value = "/student", method = {RequestMethod.GET, RequestMethod.POST})
public class StudentController {
@RequestMapping(value = "/student", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView student(){
return new ModelAndView("student", "insertDTO", new Student());
}
@RequestMapping(value = "/addStudent", method = {RequestMethod.GET, RequestMethod.POST})
public String addStudent(@ModelAttribute("insertDTO")Student student, ModelMap model){
//相当于request.setAttribute(...),在jsp页面通过name取值
model.addAttribute("name", student.getName());
model.addAttribute("id", student.getId());
model.addAttribute("age", student.getAge());
return "result";
}
}
<3>配置视图解析器
需要配置解析jsp的视图解析器
<!--ViewResolver 视图解析器-->
<!--用于支持Servlet、JSP视图解析-->
<!-- 配置视图解析器 --> <!-- InternalResourceViewResolver:支持JSP视图解析 -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar包; -->
<!-- prefix 和suffix:查找视图页面的前缀和后缀,最终视图地址为:前缀+逻辑视图名+后缀,
逻辑视图名需要在controller中返回ModelAndView指定,
比如逻辑视图名为hello,则最终返回的jsp视图地址 "WEB-INF/jsp/hello.jsp" -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>