SpringMVC: entry case

SpringMVC

Both SpringMVC and Struts2 belong to the framework of the presentation layer. It is part of the Spring framework. We can see from the overall structure of Spring:

Application of MVC design pattern in b / s system

1. The user initiates a request to the controller

Control the data received by the user and delegate to the model for processing

2. The controller processes the data through the model and obtains the processing result

Model usually refers to business logic

3. The model processing results are returned to the controller

4. The controller displays the model data in the view

The model in the web cannot display the data directly on the view, and needs to be completed by the controller. If the model is in the C / S application, the data can be displayed in the view.

5. The controller responds the view response to the user

Display the data or processing results to the user through the view.

SpringMVC architecture diagram

step

The first step: initiate a request to the front controller (DispatcherServlet)

The second step: DispatcherServlet requests the processor mapper (HandlerMapping) to find the processor (Handler)

You can search according to xml configuration and annotations

Step 3: HandlerMapping returns Handler to DispatcherServlet

Step 4: DispatcherServlet calls the processor adapter (Handleradapter) to execute the Handler

Step 5: Handleradapter to execute Handler

The sixth step: Handler execution is completed and the Handleradapter returns to ModelAndView

Step 7: Handleradapter returns ModelAndView to DispatcherServlet

ModelAndView is a low-level object of springmvc framework, including Model and View

Step 8: DispatcherServlet requests a view resolver (View resolver) to perform view resolution

Resolve into a real view (jsp) based on the logical view name

Step 9: View resolver returns view to DispatcherServlet (View)

Step 10: DispatcherServlet for View rendering

View rendering fills the model data (in the ModelAndView object) into the request field

Step 11: DispatcherServlet responds to users with results

Component description

1. Front-end controller DispatcherServlet (no programmer development required)

Function: Receive request, response result, equivalent to repeater, central processor. With DispatcherServlet reduces the coupling between other components.

2. HandlerMapping (does not require programmer development)

Function: Find Handler according to the requested url

3. Handleradapter

Role: to execute Handler according to specific rules (rules required by Handleradapter)

4. Processor Handler (requires programmer development)

Note: When writing Handler, follow the requirements of Handleradapter, so that the adapter can execute Handler correctly

5. View resolver (no programmer development required)

Function: Perform view resolution, and resolve to a real view according to the logical view name

6. View (requires programmer to develop jsp)

View is an interface, the implementation class supports different View types (jsp, freemarker, pdf ...)

Entry case

Import jar

xml configuration component

1, edit pojo: Items.java

public class Items {
    private Integer id;
    private String name;
    private Float price;
    private String pic;
    private Date createtime;
    private String detail;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Float getPrice() {
        return price;
    }
    public void setPrice(Float price) {
        this.price = price;
    }

    public String getPic() {
        return pic;
    }
    public void setPic(String pic) {
        this.pic = pic == null ? null : pic.trim();
    }

    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 == null ? null : detail.trim();
    }
}

2. Write view: itemsList.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="${itemsList }" 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 }/item/editItem.action?id=${item.id}">修改</a></td>
            </tr>
         </c:forEach>

      </table>
   </form>
</body>
</html>

3 、 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">
    <display-name>springmvc</display-name>

    <!-- springmvc前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
            contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等)
            如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml)
         -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--
            第一种:*.action,访问以.action结尾,由DispatcherServlet进行解析
            第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析,使用此种方式可以实现 RESTful风格的url
            第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时,仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。
         -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>


    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

load-on-startup: indicates that the servlet starts with the service.

url-pattern: For * .action, please send it to DispatcherServlet.

contextConfigLocation: Specify the loading location of springmvc configuration. If not specified, WEB-INF / [Servlet name of DispatcherServlet] -servlet.xml is loaded by default.

4、springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
      http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd
      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
      http://www.springframework.org/schema/tx 
      http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <!-- 配置Handler -->
    <bean id="itemsController1" class="org.haiwen.controller.ItemsController1" name="/queryItems_test.action"/>
    <!-- 配置另外一个Handler -->
    <bean id="itemsController2" class="org.haiwen.controller.ItemsController2"/>
        
    <!-- 非注解映射器一:将bean的name作为url进行查找,需要在配置Handler时指定beanname(就是url),所有的映射器都实现 HandlerMapping接口。-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>    
    <!-- 非注解映射器二:简单url映射 -->
    <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">itemsController2</prop>
            </props>
        </property>
    </bean>
    
    <!-- 所有处理器适配器都实现 HandlerAdapter接口 -->
    <!-- 非注解适配器一:要求编写的Handler实现 Controller接口 -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    <!-- 非注解适配器二:要求编写的Handler实现 HttpRequestHandler接口 -->
    <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>

    <!-- 视图解析器:解析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>
</beans>

5. Develop Handler to implement Controller interface

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.haiwen.pojo.Items;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class ItemsController1 implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {

        //调用service查找数据库,查询商品列表,这里使用静态数据模拟
        List<Items> itemsList = new ArrayList<>();
        
        //向list中填充静态数据
        Items items_1 = new Items();
        items_1.setName("联想笔记本");
        items_1.setPrice(6000f);
        items_1.setCreatetime(new Date());
        items_1.setDetail("ThinkPad T430 联想笔记本电脑!");

        Items items_2 = new Items();
        items_2.setName("苹果手机");
        items_2.setPrice(5000f);
        items_2.setCreatetime(new Date());
        items_2.setDetail("iphone6苹果手机!");

        itemsList.add(items_1);
        itemsList.add(items_2);

        //返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        //相当 于request的setAttribut,在jsp页面中通过itemsList取数据
        modelAndView.addObject("itemsList", itemsList);
        //指定视图
        modelAndView.setViewName("items/itemsList");

        return modelAndView;
    }
}

6. Develop another Handler to implement HttpRequestHandler interface

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.haiwen.pojo.Items;
import org.springframework.web.HttpRequestHandler;

public class ItemsController2 implements HttpRequestHandler {

    @Override
    public void handleRequest(HttpServletRequest request,
                              HttpServletResponse response) throws ServletException, IOException {

        //调用service查找 数据库,查询商品列表,这里使用静态数据模拟
        List<Items> itemsList = new ArrayList<>();
        
        //向list中填充静态数据
        Items items_1 = new Items();
        items_1.setName("联想笔记本");
        items_1.setPrice(6000f);
        items_1.setCreatetime(new Date());
        items_1.setDetail("ThinkPad T430 联想笔记本电脑!");

        Items items_2 = new Items();
        items_2.setName("苹果手机");
        items_2.setPrice(5000f);
        items_2.setCreatetime(new Date());
        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);

        //使用此方法可以通过修改response,设置响应的数据格式,比如响应json数据
        //response.setCharacterEncoding("utf-8");
        //response.setContentType("application/json;charset=utf-8");
        //response.getWriter().write("json串");
    }
}

Annotation component mode

1、springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
      http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd 
      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
      http://www.springframework.org/schema/tx 
      http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <!-- 对于注解的Handler可以单个配置,实际开发中建议使用组件扫描-->
    <!-- <bean class="org.haiwen.controller.ItemsController1" /> -->
    <!--
        可以扫描controller、service、...
        这里让扫描controller,指定controller的包
     -->
    <context:component-scan base-package="org.haiwen.controller"></context:component-scan>

    <!--注解映射器 -->
    <!-- <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>

    <!-- 视图解析器:解析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>
</beans>

Annotation processor mapper

Before spring 3.1, the org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping annotation mapper was used.

After spring3.1 use org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping annotation mapper.

 

Annotation processor adapter

Before spring 3.1, the annotated adapter was annotated with org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.

After spring3.1, use org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter to annotate the adapter.

2. Develop Handler

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.haiwen.pojo.Items;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

//使用Controller标识,它是一个控制器
@Controller
public class ItemsController3 {

    //商品查询列表
    //@RequestMapping实现 对queryItems方法和url进行映射,一个方法对应一个url
    //一般建议将url和方法写成一样
    @RequestMapping("/queryItems")
    public ModelAndView queryItems() throws Exception {

        //调用service查找 数据库,查询商品列表,这里使用静态数据模拟
        List<Items> itemsList = new ArrayList<>();

        //向list中填充静态数据
        Items items_1 = new Items();
        items_1.setName("联想笔记本");
        items_1.setPrice(6000f);
        items_1.setCreatetime(new Date());
        items_1.setDetail("ThinkPad T430 联想笔记本电脑!");

        Items items_2 = new Items();
        items_2.setName("苹果手机");
        items_2.setPrice(5000f);
        items_2.setCreatetime(new Date());
        items_2.setDetail("iphone6苹果手机!");

        itemsList.add(items_1);
        itemsList.add(items_2);

        //返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        //相当 于request的setAttribut,在jsp页面中通过itemsList取数据
        modelAndView.addObject("itemsList", itemsList);
        //指定视图
        modelAndView.setViewName("items/itemsList");

        return modelAndView;
    }
}
Published 202 original articles · praised 37 · 30,000+ views

Guess you like

Origin blog.csdn.net/lovecuidong/article/details/103315114