First knowledge of spring MVC framework

Types in MVC

MVC: model (dao,service), view (jsp) and controller (Servlet) are specifications for software design,
dao: operation database
servlet

MVC is not a design pattern, MVC is an architecture pattern

Projects encountered in actual development

Front end data transmission entity class
Entity class: user name, password, birthday, hobby... 20
Front end: user name, password
pojo:

vo: a class of subdivision
jsp: essentially a Servlet
Hypothesis: interview question: is the architecture of your project designed or evolved

Process of running project in Servlet

  1. User request
  2. The Servlet accepts the requested data and calls the corresponding business logic method
  3. After the business is processed, the updated data is returned to the Servlet
  4. Servlets turn to sharing with JSPS, which render the page
  5. Respond to the front-end updated page

Controller: controller

  1. Get form data
  2. Call business logic
  3. Go to the specified page

Model: Model

  1. Business logic
  2. Status of saved data

view: view

  1. Display page

What MVC needs to do

  1. Mapping URL s to JAVA classes or methods of JAVA classes
  2. Encapsulate user submitted data
  3. Processing request - call related business processing - powder loading response data
  4. Render the response data. Project of presentation layer in jsp/html

Another framework: MVVM: M V M

Advantages of spring MVC

  1. Lightweight, easy to learn
  2. Efficient
  3. Good compatibility with Spring
  4. Contract due to configuration
  5. Powerful
  6. Concise and flexible

Architecture in initial spring MVC

1. Create project

Note that every time you create a project, you need to re import the jar package into the project
Otherwise, 404 error will be reported in the project (reason: the view parser contains the string function of automatic assembly, resulting in string splicing at the beginning)

2. Import the dependencies required by spring MVC (it must be Maven project when creating the project)

<?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>org.example</groupId>
    <artifactId>SpringMVC</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.0.2.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

</project>

3. Configure the required spring MVC servlet core XML file (all constraints are listed in this sequence, and the package items are automatically scanned)

<?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
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

</beans>
Auto scan package
<!-- Automatically scan the package to make the annotations under the specified package effective,from IOC Unified container management -->
    <context:component-scan base-package="com.kuang.controller"/>
Intercept qualified statements
   <!-- Give Way Spring MVC Do not process static resources -->
    <mvc:default-servlet-handler />
    <!--
    support mvc Annotation driven
        stay spring Generally used in@RequestMapping Annotation to complete the mapping relationship
        To make@RequestMapping Note effective
        You must register with the context DefaultAnnotationHandlerMapping
        And one AnnotationMethodHandlerAdapter example
        These two instances are handled at the class level and method level, respectively.
        and annotation-driven Configuration helps us automatically complete the injection of the above two instances.
     -->
    <mvc:annotation-driven />
view resolver
<!-- view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- prefix -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- suffix -->
        <property name="suffix" value=".jsp" />
    </bean>

4. Configure the required web XML file (implementation of spring MVC core framework DispatcherServlet,)

<?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">
    <!--to configure DispatchServlet:This is it SpringMVC Core of: request distributor, front-end controller-->
    <!--1.register servlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--Specified by initialization parameters SpringMVC The location of the configuration file is associated-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!-- Start sequence: the smaller the number, the earlier the start -->
        <load-on-startup>1</load-on-startup>
    </servlet>

</web-app>

5. On the web Write out the total spring MVC interception in XML, and

  <!--All requests will be rejected springmvc intercept -->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ac4oghxr-1640671808786) (C: \ users \ L \ appdata \ roaming \ typora \ typora user images \ image-20211020171251487. PNG)]

Write entity classes in the Controller under the package (including)

package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {
    @RequestMapping("/h1")
    public String sayHello(Model model){
        model.addAttribute("msg","HelloSpringMVC");
        return "hello";
    }
}

Summary

General steps for writing Servlet projects

  1. Import the jar package in the Web project and configure the Web xml
<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:Spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapper>
       <servlet-name>springmvc</servlet-name>
       <url-parttern>/</url-parttern>
</spring-mappper>
  1. Configure spring MVC servlet under resource 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/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <!-- Automatically scan the package to make the annotations under the specified package effective,from IOC Unified container management -->
    <context:component-scan base-package="com.kuang.controller"/>
    <!-- Give Way Spring MVC Do not process static resources -->
    <mvc:default-servlet-handler />
        <!--Processor and mapper are omitted-->
    <mvc:annotation-driven />


    <!-- view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- prefix -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- suffix -->
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

3. Create a new scenario to jump to the configuration view parser

package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {
    @RequestMapping("/h1")
    public String sayHello(Model model){
        model.addAttribute("msg","HelloSpringMVC");
        return "hello";
    }
}

The second method inherits the Controller class to implement the Controller principle

Spring MVC XML files are deleted except the view parser

<bean name="/t1" class="com.kuang.controller.Controller01">

Create a new class

To create a class, you must first think of registering messages in spring MVC

!(C:\Users\l\AppData\Roaming\Typora\typora-user-images\image-20211020184032510.png)

Specify the path of the class first, and then the method path

Restful style
concept
A way of transmitting information to the background

//customary: http://localhost:8080/all?a=1&b=2
//Restful:http://localhost:8080/add/1/3

Use annotation @ PostMapping

@PostMapping("add/{a}/{b})
public String test1(@PathVariable int a,@PathVariable){
    	String res=a+b;
    	model.addAttribute("msg","Result 2 is:"+res);
    	return "test";
}

Summary:

In the annotation above, @ PostMapping,@P=GetMapping can be changed by changing the name of the annotation

The parameters passed are obtained by using EL expressions

Jump mode of results in spring MVC

Set the ModelAndView object, viewName + view parser suffix to forward or redirect the jump URL

View parser, for example:

<!-- view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- prefix -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- suffix -->
        <property name="suffix" value=".jsp" />
    </bean>

Inherit the Controller class to return the view or directly redirect the page and forward

Jump to view in spring MVC (without view parser)

I Fully qualified name forwarding

@Controller
public class Test01{
    @ResquestMapping("/m1/t2")
    public String reword(Modle modle){
        modle.addAttribute("msg","ModelTeset");
        return "WEB-INF/jsp/test.jsp";
    }
}

II Direct forwarding (no adapter used)

@ResquestMapping("/rsm/r1")
public String test3(){
    //forward
    return "forward:/index.jsp";
}

III Redirection (no adapter used)

@ResquestMapping("/rsm/r1")
public String test4(){
    return "redirect:/index.jsp";
}

Use of redirection

Pass in parameters in spring MVC

@Controller
@ResquestMapping("/user")
public class UserController{
    @GetMapping("/t1")
    public String test1(RequestParam("username") String name,Model model){
        //1. Accept front-end parameters
        System.out.prinln("The parameters accepted by the front end are"+name);
        //2. Return the returned result to the front end
        model.addAttriute("msg",name);
        //3. View jump 
        return "test";
    }
}

Properties in the object passing in parameters in spring MVC

As long as it is consistent with the object attribute of the passed in parameter, the object is directly and automatically encapsulated. This situation is only applicable to the case where the attribute name is the same

Garbled code encountered by Spring

Add filter

package com.kuang.fiter;

import javax.servlet.*;
import java.io.IOException;

public class Encoding implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("I have only passed the filter!!!");
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

Load the filter into the web XML file

<!--
        to configure SpringMVC Random code filtering
    -->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

File conversion in json

<head>
    <meta charset="utf-8">
    <title>Title</title>
    <script type="text/javascript">
        //Write a java object
        var user={
            name="high",
            age=3,
            sex="male"
        }
        //Convert js object to json object
        var json=JSON.stringfly(user);
        console.log(json);
        console.log("===================");
        //Convert json objects to js objects
        var obj=JSON.parse("json");
        json object
        console.log("obj");
        //Format conversion of json object
    </script>
</head>

~~ html

Title ~~~

Keywords: Java Front-end mvc

Added by scristaldi on Fri, 31 Dec 2021 21:30:43 +0200