Spring MVC的API:
DispatcherServlet: 整个Spring MVC的前端控制器,由它来接管来自客户端的请求
HandlerMapping: DispatcherServlet会通过它来处理客户端请求到各个(Controller)处理器的映射
HandlerAdapter: HandlerMapping会根据它来调用Controller里需要被执行的方法
HandlerExceptionResolver: spring mvc处理流程中,如果有异常抛出,会交给它来进行异常处理
ViewResolver: HandlerAdapter会把Controller中调用返回值最终包装成ModelAndView,ViewResolver会检查其中的view,如果view是一个字符串,它就负责处理这个字符串并返回一个真正的View,如果view是一个真正的View则不会交给它处理,为什么view即可以是字符串又会是View呢下面会进行解释
View: 对应MVC 中的V, 此接口只有一个方法 render,用于视图展现
ModelAndView 对于解决上面介绍ViewResoler或者下面图片的疑惑,这个类中的view这个属性是 Object 类型的,它可以是一个视图名也可以是一个实际的View,这点我们观察其源码可以很清楚的看出来
Spring MVC流程:
1.通过DispatcherServlet拦截用户请求
2.DispatcherServlet从HandlerMapping映射中获取用户请求是到哪个Controller,并把结果返回到DispatcherServlet中
3.请求到达Controller后,执行相关业务,返回ModelAndView到DispatcherServlet中
4.根据ModelAndView从ViewResolver中找到需要显示的View,并返回到DispatcherServlet中
5.DispatcherServlet把View响应到用户端
Spring MVC的简单实现:
web.xml的相关配置
- <servlet>
- <servlet-name>springServlet</servlet-name>
- <!-- Spring MVC的核心控制器(前端控制器)拦截用户的请求 -->
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <!-- 开启服务时初始化,创建相应的Bean -->
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext.xml</param-value>
- </init-param>
- </servlet>
- <servlet-mapping>
- <servlet-name>springServlet</servlet-name>
- <url-pattern>*.do</url-pattern>
- </servlet-mapping>
创建自己的Controller(后端控制器),继承AbstractController并实现handleRequestInternal方法
- public class LoginAction extends AbstractController {
- @Override
- protected ModelAndView handleRequestInternal(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- // TODO Auto-generated method stub
- return null;
- }
- }
applicationContext.xml的相关配置
- <?xml version="1.0" encoding="UTF-8"?>
- <beans
- xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <!-- 配置controller的业务Bean -->
- <bean id="loginAction" class="com.web.action.LoginAction">
- </bean>
- <!-- 配置url与controller的映射关系 -->
- <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
- <property name="mappings">
- <props>
- <prop key="/login.do">loginAction</prop>
- </props>
- </property>
- </bean>
- <!-- 配置视图View(已jsp作为视图) -->
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/"/>
- <property name="suffix" value=".jsp"/>
- </bean>
- </beans>
现在如果用户发送/login.do的请求,请求就会到达LoginAction中进行处理,以及响应客户端
用以上的相关配置有一点不好的地方就是,用户的每个请求都需要用一个Controller来处理,要怎么样才能实现一个Controller中写多个处理方法接受用户不同的请求呢?有以下两种方式:
方式一:继承
Controller不再继承AbstractController类,现在继承MultiActionController类来实现多方法,处理方式如下
web.xml的相关配置不变,需要重写LoginAction这个Controller类
- package com.web.action;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.web.servlet.ModelAndView;
- import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
- /**
- * 继承AbstractController只能实现一个动作对应一个方法
- * 继承MultiActionController实现一个controller中写多个方法
- * @author Administrator
- *
- */
- public class LoginAction extends MultiActionController {
- private String fromView;
- private String toView;
- /**
- *
- * 处理方法的访问修饰符只能为public
- * @param request
- * @param response
- * @return
- * @throws Exception
- */
- public ModelAndView getList(HttpServletRequest request, HttpServletResponse response) throws Exception {
- request.setAttribute("list", "执行getList方法成功");
- return new ModelAndView(toView);
- }
- public ModelAndView doLogin(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- //获取表单数据
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- //调用业务逻辑方法
- String result = login(username, password);
- if("success".equals(result)){
- request.setAttribute("result", "成功");
- return new ModelAndView(toView);
- }else{
- request.setAttribute("result", "失敗");
- return new ModelAndView(fromView);
- }
- }
- private String login(String username, String password){
- if("123".equals(username) && "admin".equals(password)){
- return "success";
- }
- return "fail";
- }
- public String getFromView() {
- return fromView;
- }
- public void setFromView(String fromView) {
- this.fromView = fromView;
- }
- public String getToView() {
- return toView;
- }
- public void setToView(String toView) {
- this.toView = toView;
- }
- }
applicationContext.xml的相关配置
- <?xml version="1.0" encoding="UTF-8"?>
- <beans
- xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <!-- 配置methodNameResolver -->
- <bean id="ParameterMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
- <property name="paramName" value="action"/>
- </bean>
- <!-- 配置controller的业务Bean -->
- <bean id="loginAction" class="com.web.action.LoginAction">
- <!-- controller继承MultiActionController并添加这个配置,使controller能写多个方法 -->
- <property name="methodNameResolver" ref="ParameterMethodNameResolver"/>
- <!-- 初始化属性 -->
- <property name="fromView" value="login"/>
- <property name="toView" value="index"/>
- </bean>
- <!-- 配置url与controller的映射关系 -->
- <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
- <property name="mappings">
- <props>
- <prop key="/login.do">loginAction</prop>
- </props>
- </property>
- </bean>
- <!-- 配置视图View(已jsp作为视图) -->
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <!-- 前缀 -->
- <property name="prefix" value="/"/>
- <!-- 后缀 -->
- <property name="suffix" value=".jsp"/>
- </bean>
- </beans>
用户发送请求/login.do?action=doLogin或者/login.do?action=getList就会执行相应的处理方法了,这样就可以访问了
方式二:注解
web.xml的相关配置不变,需要重写LoginAction这个Controller类
业务类UserService:添加注解@Service
- package com.service;
- import org.springframework.stereotype.Service;
- /**
- * 业务类(M)
- * @author Administrator
- *
- */
- @Service
- public class UserService {
- public String login(String username, String password){
- if("123".equals(username) && "admin".equals(password)){
- return "登录成功";
- }
- return "登录失败";
- }
- }
Controller类LoginAction:添加注解@Controller
- package com.web.action;
- import java.util.HashMap;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.servlet.ModelAndView;
- import com.service.UserService;
- @Controller
- @RequestMapping("/login")
- public class LoginAction {
- @Autowired
- private UserService userService;
- public void setUserService(UserService userService) {
- this.userService = userService;
- }
- /**
- * @param username
- * @param password
- * @return
- * 返回ModelAndView,并使用map传递数据到页面
- */
- @RequestMapping("/doLogin.do")
- public ModelAndView doLogin(String username, String password) {
- String result = userService.login(username, password);
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("result", result);
- if("登录成功".equals(result)){
- return new ModelAndView("index",map);
- }
- return new ModelAndView("login",map);
- }
- /**
- * @param request
- * @return
- * 返回String,使用request传递数据到页面
- */
- @RequestMapping("/getList.do")
- public String getList(HttpServletRequest request){
- request.setAttribute("result", "执行GetList方法成功");
- return "/index";
- }
- }
applicationContext.xml的相关配置:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans
- xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- ">
- <!-- 自动扫描路径下的所有文件,并根据注解完成注入的工作 -->
- <context:component-scan base-package="com.service,com.web.action"/>
- <!-- 默认的注解映射的支持 -->
- <mvc:annotation-driven/>
- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
- <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
- <!-- 使spring支持注解 -->
- <context:annotation-config/>
- <!-- 配置视图View(已jsp作为视图) -->
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/" />
- <property name="suffix" value=".jsp" />
- </bean>
- </beans>
用户请求:
<a href="login/getList.do">点击获取List</a>
<form action="login/doLogin.do" method="post"></form>,访问成功。
但是存在以下疑点:
在applicationContext.xml配置中,我删除以下配置仍可正常运行...
- <mvc:annotation-driven/>
- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
- <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
- <!-- 使spring支持注解 -->
- <context:annotation-config/>