SpringMVC framework (detailed explanation)

1. Introduction

1.1. What is MVC?

Spring MVC is a Java-based request-driven lightweight web framework that implements the MVC design pattern. By separating (M) Model, (V) View, and (C) Controller, the web layer is decoupled from responsibilities and Complex web applications are divided into parts with clear logic, simplifying development, reducing errors, and facilitating cooperation among developers within the team.

1.2, Advantages and Disadvantages of SpringMVC

Advantages of MVC:
Multiple views share a model, greatly improving code reusability. The
three modules of MVC are independent of each other and have a loosely coupled architecture.
The controller improves the flexibility and configurability of applications and
is conducive to software engineering management.

Perfect system architecture = loose coupling + high reusability + high scalability

MVC Disadvantages:
Complex principles
, increased complexity of system structure and implementation,
inefficient access of model data by views

1.3, MVC pattern
  1. View-corresponding component: JSP or HTML file
  2. Controller-corresponding component: Servlet
  3. Model-corresponding component: JavaBean
    Insert image description here
    JSP Model1
    Insert image description here
    JSP Model2
  4. Servlet: accept front-end requests and call JavaBeans
  5. JavaBean: handle business and operate database
  6. JSP: Respond to the processing results to the browser and present them to the user
    Insert image description here
    MVC processing
    Insert image description here
    Spring MVC
  7. Replace Servlet in JSP Model2 model with Controller
  8. After the Controller receives the request, it completes the business processing and uses the Model model object to store the processing results.
  9. The Controller calls the corresponding view parser View to view the processing results, and finally the client gets the response information.

Second, use SpringMvc

21. Create the maven-web project and modify the web.xml file in the WEB-INF directory under the webapp directory.

Insert image description here

2.2, the content of web.xml file is as follows
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <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>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>
2.3, introduce springMVC dependencies
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.xinxi2</groupId>
  <artifactId>SpringMvc1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SpringMvc1 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring.version>5.2.5.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>


  <!-- log4j 日志jar-->

  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
  </dependency>

  <!-- 连接mysql5 的驱动 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.10</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.2</version>
  </dependency>

  <!-- mybatis依赖 -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.2</version>
  </dependency>
  <!-- 参考版本对应 http://www.mybatis.org/spring/ -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
  </dependency>

  <!-- 数据源管理  使用了dbcp2数据 -->
  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-dbcp2</artifactId>
    <version>2.1.1</version>
  </dependency>
  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.4.2</version>
  </dependency>

  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <!-- commons 文件上传jar -->
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.4</version>
  </dependency>
  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>

  <!-- jstl -->
  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>

  <!-- 加入JSON转换工具 -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
  </dependency>

  </dependencies>

  <build>
    <finalName>SpringMvc1</finalName>
  </build>
</project>

2.4, create springmvc.xml file
<?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/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd

	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd">

<!--  扫描  -->
    <context:component-scan base-package="com.controller"></context:component-scan>
</beans>
2.5, create a controller class
import java.util.List;
import java.util.Map;


//标记该类为处理层类
@Controller
@RequestMapping("/hello")

public class HelloController {
    
    
   	
    //把请求路径映射到该方法上
    @RequestMapping("/hello01")
    public String hello01(){
    
    
        System.out.println("hello01");
        
        //请求转发到hello01.jsp界面
        return "hello01.jsp";
    }
}
2.6, springMVC running process
  1. The client requests http://localhost:8080/springMVC17/hello
  2. Come to the tomcat server.
  3. Springmvc's front-end controller DipatcherServlet accepts all requests.
  4. Check which @RequestMaping your request address matches.
  5. Execute the corresponding method. The method returns a string. Springmvc parses the string into the web page to be forwarded.
  6. Concatenate the string through the view parser.
  7. Get the spliced ​​address and find the corresponding web page.
  8. Render the web page to the client
2.7, use Model to upload data
    @RequestMapping("/hello03")
    public String hello03(Student student,Model model){
    
    
        System.out.println("hello03"+student.getUsername()+"  "+student.getPwd()+" "+student.getBirthday()+" "+student.getAge());
        model.addAttribute("linyuhao","hh");
        return "hello01.jsp";
    }

Insert image description here

Upload data using HttpServletRequest

    @RequestMapping("/hello04")
    public String hello04(HttpServletRequest request){
    
    
        System.out.println("hello04");
        request.setAttribute("guangtou","gg");
        return "hello01.jsp";
    }

Insert image description here

2.8, use Map to upload data
    @RequestMapping("/hello05")
    public String hello05(Map map){
    
    
        System.out.println("hello05");
        int count = 1/0;
        map.put("wangdao","qq");
        return "redirect:/login.jsp";
    }

Insert image description here

2.9, Static resource loading problem

Insert image description here
This requires us to load the static resources in the springMVC configuration file, plus

<!--  解决了静态资源的加载问题  -->
    <mvc:resources mapping="/static/**" location="/static/"></mvc:resources>

Insert image description here

3. How to implement page redirection

In the method of the controller layer, the return value is of String type, and an interface is returned using the request forwarding method. If you want to use redirection to jump to other pages, add redirect: in the return value, / when springmvc sees When the string you return contains redirect:, it will be considered that you want to redirect.

return “redirect:/login.jsp”;

    @RequestMapping("/hello05")
    public String hello05(Map map){
    
    
        System.out.println("hello05");
        int count = 1/0;
        map.put("wangdao","qq");
        return "redirect:/login.jsp";
    }

4. Interceptor

4.1. Create interceptor
package com.Interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class LoginInterceptor implements HandlerInterceptor {
    
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        System.out.println("preHandle");
//        拦截规则,自己根据业务需求实现
        String username = request.getParameter("username");
        if (null==username || "".equals(username)){
    
    
            response.sendRedirect("/index.jsp");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
    
        System.out.println("postHandle:handle执行完,渲染之前");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
    
        System.out.println("afterCompletion:handle执行完,渲染之后");
    }
}

The interceptor class we created needs to implement the HandlerInterceptor interface and override the preHandle method.
If we want to use the interceptor we defined, we need to register the interceptor in the springmvc.xml file.

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/hello/**"/>
            <mvc:exclude-mapping path="/hello/hello04"/>
            <bean class="com.Interceptor.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

5. File upload

5.1. Upload to local server

The first step is to import the dependencies for file upload.

  <!-- commons 文件上传jar -->
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.4</version>
  </dependency>
  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>

The second step is to create a page. What needs to be noted here is that the submission method must be post submission. The form type enctype needs to be set to the format of multipart/form-data. The name attribute of the input tag here cannot be omitted and needs to be received by the controller layer. The parameter names are the same.

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2023/6/25
  Time: 16:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上传文件</title>
</head>
<body>
    <form action="/hello/hello03" method="post" enctype="multipart/form-data">
        <input type="text" name="username"><br>
        <input type="file" name="photo"><br>
        <input type="text" name="age"><br>
        <input type="text" name="birthday">
        <input type="submit" value="提交">
    </form>
</body>
</html>

The third step is to configure the file upload parser in the springMVC configuration file.

<!--  配置multipartResolver,用于上传文件,使用spring的CommonsMultipartResolver  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxInMemorySize" value="5000000"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

The fourth step is to create a method that implements the file upload interface. @RequestMapping represents the requested interface.

    @RequestMapping("/uploadPage")
    public String uploadPage(){
    
    
        return "upload.jsp";
    }

    @RequestMapping("/upload")
    @ResponseBody // 此方法的返回值就是响应体的内容
    public String upload(String username, MultipartFile photo,HttpServletRequest request){
    
    

        String fileType = photo.getOriginalFilename();
        int index = fileType.lastIndexOf(".");
        fileType = fileType.substring(index);
        String path = request.getSession().getServletContext().getRealPath("static"+File.separator+"uploadfiles");
        long filename = System.currentTimeMillis();
        System.out.println(path);
        System.out.println(fileType);
        System.out.println(path+"\\"+filename+fileType);
        File file = new File(path+"\\"+filename+fileType);
        try {
    
    
            photo.transferTo(file);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return "上传成功!";
    }

6. Content supplement

@RestController is equivalent to @Controller+@ResponseBody.
All methods under this annotation return json data.
@RequestMapping: Function: Map the request path to the response method.

@RequestParam(value = “u”): Set the request parameter name you accept. query parameters

@Param(value="name"): set the parameters in the mapper mapping file in mybatis

@RequestMapping(value = “/addUser”, method = RequestMethod.POST)
method: Indicates the request method accepted by this interface. Any request method can be accepted if not set.
@GetMapping("addUser"): Indicates that only requests in the get submission method are accepted

@RequestBody: Convert the requested json data into a java object. From front-end to back-end
@ResponseBody: Convert java to json data from back-end to front-end

Guess you like

Origin blog.csdn.net/H20031011/article/details/131511482