天天看点

JavaEE SpringMVC

1. SpringMVC和Struts2都属于表现层的框架

JavaEE SpringMVC

图1.png

2. SpringMVC处理流程

JavaEE SpringMVC

图2.png

架构流程

1). 用户发送请求至前端控制器DispatcherServlet。

2). DispatcherServlet收到请求调用HandlerMapping处理器映射器。

3). 处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。

4). DispatcherServlet通过HandlerAdapter处理器适配器调用处理器。

5). 执行处理器(Controller,也叫后端控制器)。

6). Controller执行完成返回ModelAndView。

7). HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet。

8). DispatcherServlet将ModelAndView传给ViewReslover视图解析器。

9). ViewReslover解析后返回具体View。

10). DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。

11). DispatcherServlet响应用户。

3. 组件说明

  • DispatcherServlet:前端控制器

    用户请求到达前端控制器,它就相当于mvc模式中的c,DispatcherServlet是整个流程控制的中心,由它调用其它组件处理用户的请求,DispatcherServlet的存在降低了组件之间的耦合性。

  • HandlerMapping:处理器映射器

    HandlerMapping负责根据用户请求找到Handler即处理器,springmvc提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。

  • Handler:处理器

    Handler是继DispatcherServlet前端控制器的后端控制器,在DispatcherServlet的控制下Handler对具体的用户请求进行处理。由于Handler涉及到具体的用户业务请求,所以一般情况需要程序员根据业务需求开发Handler。

  • HandlAdapter:处理器适配器

    通过HandlerAdapter对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。

  • ViewResolver:视图解析器

    ViewResolver负责将处理结果生成View视图,ViewResolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果通过页面展示给用户。

  • View:视图

    SpringMVC框架提供了很多的View视图类型的支持,包括:jstlView、freemarkerView、pdfView等。我们最常用的视图就是jsp。一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。

4. 开发步骤

I. 创建Java Web工程,并导入jar包

spring-webmvc-5.0.5.RELEASE.jar、

jstl.jar
JavaEE SpringMVC

图3.png

II. 创建Item类

public class Item {
    private int id;
    private String name;
    private double price;
    private Date createTime;
    private String detail;
    
    public Item(int id, String name, double price, Date createTime, String detail) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
        this.createTime = createTime;
        this.detail = detail;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getDetail() {
        return detail;
    }
    public void setDetail(String detail) {
        this.detail = detail;
    }
    
}
           

III. 创建jsp页面--itemList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>查询商品列表</title>
    </head>
    <body>
        <form action="${pageContext.request.contextPath }/item/queryitem.action" method="post">
            查询条件:
            <table width="100%" border="1">
                <tr>
                    <td><input type="submit" value="查询"/></td>
                </tr>
            </table>
            商品列表:
            <table width="100%" border="1">
                <tr>
                    <td>商品名称</td>
                    <td>商品价格</td>
                    <td>生产日期</td>
                    <td>商品描述</td>
                    <td>操作</td>
                </tr>
                <c:forEach items="${itemList }" var="item">
                    <tr>
                        <td>${item.name }</td>
                        <td>${item.price }</td>
                        <td><fmt:formatDate value="${item.createTime }" pattern="yyyy-MM-dd HH:mm:ss"/></td>
                        <td>${item.detail }</td>
                        <td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
                    </tr>
                </c:forEach>
            </table>
        </form>
    </body>
</html>
           

IV. 创建Controller。

创建ItemController,ItemController是一个普通的java类,有点类似于Struts2中的Action,且不需要实现任何接口,只需要在类上添加@Controller注解即可。@RequestMapping注解指定请求的url,其中“.action”可以加也可以不加。在ModelAndView对象中,将视图设置为“/jsp/itemList.jsp”。

@Controller
public class ItemController {
    @RequestMapping("/itemList.action")
    public ModelAndView itemList() {
        // 查询商品列表,使用静态数据填充
        List<Item> itemList = new ArrayList<>();
        itemList.add(new Item(1, "联想", 3500, new Date(), "G480"));
        itemList.add(new Item(2, "联想1", 3501, new Date(), "G480-1"));
        itemList.add(new Item(3, "联想2", 3502, new Date(), "G480-2"));
        itemList.add(new Item(4, "联想3", 3503, new Date(), "G480-3"));
        itemList.add(new Item(5, "联想4", 3504, new Date(), "G480-4"));
        // 把商品列表传递给jsp
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList", itemList);
        // 设置展示数据的视图,即jsp
        modelAndView.setViewName("/jsp/itemList.jsp");
        return modelAndView;
    }
    
}
           

V. 在/WebContent/WEB-INF/目录下创建springmvc.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="com.mazaiting.controller"/>
</beans>
           

VI. 在/WebContent/WEB-INF/目录下创建创建web.xml,如果已有,则添加内容即可。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>springmvctest</display-name>
  <filter>
    <filter-name>charsetEncoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>charsetEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- 配置前端控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!-- 指定springmvc配置文件的路径。如果不指定,默认为:/WEB-INF/${servlet-name}-servlet.xml -->
      <param-name>contextConfigLocation</param-name>
      <!-- <param-value>classpath:springmvc.xml</param-value> -->
      <param-value>/WEB-INF/springmvc.xml</param-value>
    </init-param>
    <!-- 设置首页启动 -->
    <!-- <load-on-startup>1</load-on-startup> -->
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.action</url-pattern>
    <!-- 设置匹配方式 -->
    <!-- <url-pattern>/</url-pattern> -->
  </servlet-mapping>
  <welcome-file-list>  
    <welcome-file>/jsp/itemList.jsp</welcome-file>  
</welcome-file-list> 
</web-app>
           

VII. 运行项目

http://localhost:8080/Springmvc-first/itemList.action

JavaEE SpringMVC

图4.png

5. 注解映射器和适配器

  • 配置组件扫描器

    组件扫描器可省去在Spring容器中配置每个Controller类的繁琐。使用<context:component-scan>自动扫描标记@controller注解的控制器类,配置如下:

<context:component-scan base-package="com.mazaiting.controller"/>
           

注:如果要扫描多个包,多个包中间使用半角逗号分隔

  • 配置RequestMappingHandlerMapping

    注解式处理器映射器,对类中标记@ResquestMapping注解的方法进行映射,根据@ResquestMapping注解定义的url匹配@ResquestMapping注解标记的方法,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装了url对应的方法Method。

<!-- 配置注解式处理器映射器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
           
  • 配置RequestMappingHandlerAdapter

    注解式处理器适配器,对标记@ResquestMapping注解的方法进行适配。

<!-- 配置注解式处理器映射器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
           

6.配置视图解析器

1). 在springmvc.xml文件中配置

<!-- 配置视图解析器(对jsp默认解析器的视图解析器) -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- prefix:前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- suffix:后缀 -->
        <property name="suffix" value="jsp"></property>
    </bean>
           
  • InternalResourceViewResolver:支持JSP视图解析。
  • viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar 包。此属性可以不设置,默认为JstlView。
  • prefix和suffix:查找视图页面的前缀和后缀,最终视图的址为:前缀+逻辑视图名+后缀,逻辑视图名需要在Controller返回的ModelAndView中指定,比如逻辑视图名为hello,则最终返回的jsp物理视图地址就为 “WEB-INF/jsp/hello.jsp”。

    2). 修改ItemController中的itemList方法为

@Controller
public class ItemController {
    // 路径
    @RequestMapping("/itemList.action")
    public ModelAndView itemList() {
        // 查询商品列表,使用静态数据填充
        List<Item> itemList = new ArrayList<>();
        itemList.add(new Item(1, "联想", 3500, new Date(), "G480"));
        itemList.add(new Item(2, "联想1", 3501, new Date(), "G480-1"));
        itemList.add(new Item(3, "联想2", 3502, new Date(), "G480-2"));
        itemList.add(new Item(4, "联想3", 3503, new Date(), "G480-3"));
        itemList.add(new Item(5, "联想4", 3504, new Date(), "G480-4"));
        // 把商品列表传递给jsp
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList", itemList);
        // 设置展示数据的视图,即jsp
//      modelAndView.setViewName("/jsp/itemList.jsp");
        // 配置视图解析器解析器之后不能返回全路径名
        modelAndView.setViewName("itemList");
        return modelAndView;
    }
}
           

代码下载