Spring MVC principle and configuration

Spring MVC principle and configuration

1. Spring MVC Overview

Spring is Spring MVC provides a powerful and flexible web framework. By means of annotations, Spring MVC provides almost POJO development model, making the development and testing of the controller easier. These controllers generally do not directly process the request, but it will be delegated to other bean Spring context, using the Spring dependency injection, the bean is injected into the controller.

Spring MVC mainly mapped by the DispatcherServlet, a processor (controller) viewresolver view composition.

2. SpringMVC operating principle

3.SpringMVC Interface explained

3.1 DispatcherServlet Interface

Spring provides a front controller, all requests to have it come through unified distribution. Before a request to the DispatcherServlet Spring Controller, by means of a Spring provides required target specific HandlerMapping Controller.

3.2 HandlerMapping Interface

Able to complete the mapping of client requests to the Controller.

3.3 Controller Interface

When the user needs to concurrent processing said request, thus achieving Controller interface, and must ensure thread safety reusable.
The Controller handles user requests, which Struts Action and the role is the same. Once the user request has been processed Controller, ModelAndView DispatcherServlet object is returned to the front controller, ModelAndView contains model (Model) and the view (View).
From a broad perspective, the controller is the DispatcherServlet entire Web application; from microscopic consideration, the Controller Http request a single process controller, and model ModelAndView Http request procedure is returned (Model) and the view (View).

3.4 ViewResolver Interface

Spring provides view resolvers (ViewResolver) Find View objects in Web applications, thus rendering the corresponding result to the customer.

4. DispatcherServlet

It is the core of Spring MVC. It is responsible for receiving HTTP requests to organize and coordinate the various components of Spring MVC. The main work are the following three:

  1. URL request interception in line with a specific format.
  2. DispatcherServlet WebApplicationContext initialization context corresponding to, and the business layer, persistence layer WebApplicationContext associated.
  3. Spring MVC respective constituent components of the initialization, and fitted into the DispatcherServlet.

5. Examples

5.1 configuration file web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <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>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--中文过滤器-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

5.2 configuration file 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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 
       xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <!--扫描所有的包-->
    <context:component-scan base-package="mrzhangxd.xyz"/>
    <!-- 视图解析器 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--<task:annotation-driven></task:annotation-driven>-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀prefix -->
        <property name="prefix" value="/WEB-INF/view/"></property>
        <!-- 后缀suffix -->
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

As two major profile configuration is successful, write the following code

5.3 The main coding

  1. reg.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>用户注册</title>
    </head>
    <body>
    <form action="save" method="post">
        <fieldset>
            <legend>创建用户</legend>
            <p>
                <label>姓名:</label> <input type="text" id="name" name="name" tabindex="1">
            </p>
            <p>
                <label>年龄:</label> <input type="text" id="age" name="age" tabindex="2">
            </p>
            <p>
                <label>密码:</label> <input type="text" id="pwd" name="pwd" tabindex="3">
            </p>
            <p id="buttons">
                <input id="reset" type="reset" tabindex="4" value="取消">
                <input id="submit" type="submit" tabindex="5" value="注册">
            </p>
        </fieldset>
    </form>
    </body>
    </html>
  2. success.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <div id="gloobal">
        <h4>注册成功</h4>
        <p>
        <h5>用户信息如下:</h5>
        姓名:${user.name}<br /> 年龄:${user.age}<br /> 密码:${user.pwd}<br />
        </p>
    </div>
    </body>
    </html>
  3. UserController.java

    package mrzhangxd.xyz.controller;
    
    import mrzhangxd.xyz.pojo.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class UserController {
        @RequestMapping("")
        public String Create(Model model) {
            return "reg/reg";
        }
        @RequestMapping("/save")
        public String Save(@ModelAttribute("form") User user, Model model) {
            model.addAttribute("user", user);
            return "reg/success";
        }
    }
  4. User.java

    package mrzhangxd.xyz.pojo;
    
    import java.io.Serializable;
    import java.util.Date;
    
    public class User implements Serializable {
    
        private static final long serialVersionUID = 1L;
        private Integer id; //用户ID
        private String name; // 用户名
        private String pwd; // 密码
        private Integer age; // 年龄
        private Date creatTime; // 创建时间
    
        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;
        }
    
        public String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public Date getCreatTime() {
            return creatTime;
        }
    
        public void setCreatTime(Date creatTime) {
            this.creatTime = creatTime;
        }
    }
    

5.4 operating results

  1. registration page

  2. Success page

--- END ---

Guess you like

Origin www.cnblogs.com/MrZhangxd/p/11595142.html