Recommend learning java -- the first lesson of spring MVC

Spring MVC overview

Spring MVC is a module in the spring framework and one of the cores of spring. It is often used for web development. Its bottom layer is Servlet, so it is also called Spring web mvc. Because the internal architecture pattern is mvc architecture, it is called Spring MVC

Spring MVC is a container that manages the controller objects in the interface layer and uses ioC technology.

DispatcherServlet, the core Servlet of spring MVC, is responsible for processing requests and response processing results, which is the core content of our study.

The first spring MVC example

Realized functions (i.e. requirements)

The user initiates the request, processes the request and gives the response result.

Implementation step analysis

  1. Create a web project
  2. Add dependency (spring webmvc, servlet)
  3. Declare the spring MVC core object DispatcherServlet
  4. Create jsp and initiate request
  5. Create a common class to be used as a Controller (instead of the previous servlet). Here, use the annotations @ Controller and @ RequestMapping
  6. Create a jsp page that displays the results
  7. Create Spring MVC configuration file (similar to Spring configuration file)

Among the above steps, the first step does not need to be said more; The dependencies used in the second step are as follows:

<!--    springMVC rely on    -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.15</version>
</dependency>

<!--    servlet rely on    -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>
Declare the spring MVC core object DispatcherServlet

First, create spring MVC servlet under the resources folder XML, which is the configuration file of spring MVC, but now we just create the file, and the configuration will be added later; Then on the web Add the following code to the XML file:

<!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>
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--    custom SpringMVC Configuration file location for    -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--    Represents the server tomcat The order in which objects are created. The smaller the value, the earlier the time to create objects, an integer greater than or equal to 0    -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--
            <url-pattern> Send some requests to the designated Servlet handle.
            Then you can use wildcards to specify. Common extension forms are as follows:.do,.action,.mvc etc.
        -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

The configuration here is Spring and the web As we wrote in, a slight adjustment is made here, because the dispatcher servlet is used this time. Similarly, the above code is basically fixed. Write it down and use it directly later.

Create the jsp that initiates the request

The page is very simple. Make a hyperlink and click to initiate a request. The specific code is as follows:

<%--
  Created by studyingJava
  Date: 2022/2/9
  Time: 11:57
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>springmvc-first</title>
</head>
<body>
    <a href="hello.do">launch hello.do request</a>
</body>
</html>
Create controller class

Create a new package named controller. Of course, the name can be defined by you. The complete code is as follows:

/**
 * desc: Customize the back-end Controller and add the annotation @ Controller to indicate the creation of the java object
 * author: Recommend learning java
 * <p>
 * weChat: studyingJava
 */
@Controller
public class MyController {

    /**
     * @return ModelAndView: Encapsulation (data and view) representing the result of the request
     * @RequestMapping: For request mapping, the parameter value is an array of string type, the uri address starts with "/", and the method parameter specifies the request method
     * It can be used on methods and classes. The former represents the complete address and the latter represents the public prefix. At this time, the corresponding method only needs to write the part after the prefix
     */
    @RequestMapping(value = "/doHello")
    public ModelAndView doHello() {
        // The actual business of the simulation result here should be calling the service layer

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", "handle doHello request");
        modelAndView.addObject("code", 200);

        // Send the request result to the jsp page to be displayed
        modelAndView.setViewName("/result.jsp");

        return modelAndView;
    }

}
Create a jsp page that displays the results

We can take out the encapsulated value in the controller class and display it on this page. The code is as follows:

<%--
  Created by studyingJava
  Date: 2022/2/9
  Time: 16:43
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Response request result</title>
</head>
<body>
    /result.jsp Display the processing results of user requests<br>

    <h3>msg Data: ${msg}</h3>
    <h3>code Data: ${code}</h3>
</body>
</html>
Add annotation scanner to configuration file

Because we generate Java objects through annotations and the corresponding request response method is also specified through annotations, the program should scan the business logic given by us through the configuration file. The code is as follows:

<?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"
       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">

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

Here we need to use the knowledge of the previous section. Publish and deploy our project to the local tomcat server, and then visit it through the browser to see the results. The specific operations will not be repeated here. Friends who do not know can read a blog.

If you encounter result The value in the JSP page is not displayed. Solution: modify the web The start tag of web app in XML can be as follows:

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
            http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

The final effect is as follows:

Expand knowledge

In the above content, the page where we show the results is full path, which is troublesome. Then the system provides us with a configuration called view parser. After adding, we only need to give the page name. See the specific configuration below.

Add the following code to the configuration file:

<!--  view resolver 
            You only need to configure the prefix and suffix, and only need the file name when using
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/"/>
    <property name="suffix" value=".jsp"/>
</bean>

The usage code in MyController is as follows:

// Send the request result to the jsp page to be displayed
//modelAndView.setViewName("/WEB-INF/view/result.jsp");
// How to use after configuring the view parser
modelAndView.setViewName("result");

That's ok!

Carry parameters

The above request does not carry any parameters, but many cases in actual development need to carry parameters. The following is a demonstration by case.

Carry multiple parameters

As an example, a form is added to the request page. The user enters two data, which are received through the Controller and displayed in result JSP page.

index.jsp add the following code:

<body>
    <a href="hello.do">launch hello.do request</a><br>

    <%--Demo request with parameters--%>
    <form action="test/param.do" method="post">
        Language:<input type="text" name="language"><br>
        Experience:<input type="text" name="work_time"><br>
        <input type="submit" value="Submit">
    </form>
</body>

In MyController, we add a new method to handle this submission request:

/**
 * Transmit parameter - receive parameter - display parameter
 * <p>
 * It is recommended to use the packing class of basic data type for formal parameter type to avoid 400 exceptions caused by not filling in
 *
 * @return
 */
@RequestMapping(value = "/test/param.do")
public ModelAndView doParam(String language, Integer work_time) {

    ModelAndView mv = new ModelAndView();
    mv.addObject("language", language);
    mv.addObject("work_time", work_time);

    mv.setViewName("result");

    return mv;
}

As a result, you can verify by yourself that the front runs through. There should be no problem with this. If you don't understand, please leave a message~

Solve the problem of garbled Chinese parameters

tips: if we use Chinese to transmit parameters, we will find that the display is garbled. Then we need to solve this problem through the filter. The code is as follows:

On the web Add the following code to XML:

<!--  Use the filter to solve the problem of garbled code (request process, setting process, display process)  -->
<filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <!--      Project use code      -->
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
    <init-param>
        <!--     Force request use encoding Coding mode       -->
        <param-name>forceRequestEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <!--     Forced response use encoding Coding mode       -->
        <param-name>forceResponseEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <!--     Force all requests to go through the filter       -->
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Adding a filter can ensure that all our requests (requests and responses) pass through the filter defined by us, and the coding is unified. This code is also fixed and can be used directly in the future.

The parameter name and method parameter name in the request are inconsistent

tips: the parameter name in our request is consistent with the formal parameter name of the method in the Controller. If it is inconsistent, how can we ensure that the parameter value in the request can be received?

The usage of @ param annotation is also very simple:

@RequestMapping(value = "/test/param.do")
public ModelAndView doParam1(@RequestParam(value = "language") String lan,
                             @RequestParam(value = "work_time") Integer workTime) {

    ModelAndView mv = new ModelAndView();
    mv.addObject("language", lan);
    mv.addObject("work_time", workTime);

    mv.setViewName("result");

    return mv;
}

The value value of the annotation is the parameter name in the request, and the formal parameters of the method can be customized. The annotation will automatically assign the parameter value in the request to the formal parameters of the method.

Controller method parameters are java objects

This method of receiving parameters has preconditions:

  • The parameter name in the request must be consistent with the attribute name in the java object
  • java objects need to provide parameterless construction methods

Let's create a new Java object programmer java

/**
 * desc:
 * author: Recommend learning java
 * <p>
 * weChat: studyingJava
 */
public class Programmer {

    private String languageType;
    private Integer workTime;

    public Programmer() {
    }

    public String getLanguageType() {
        return languageType;
    }

    public void setLanguageType(String languageType) {
        this.languageType = languageType;
    }

    public Integer getWorkTime() {
        return workTime;
    }

    public void setWorkTime(Integer workTime) {
        this.workTime = workTime;
    }

}

index. Add a new form in jsp:

<%--For demonstration java Object receives a request with parameters
       Requirement: parameter name and in the request java The property names in the object are consistent
       --%>
<form action="test/param_object.do" method="post">
    Language classification:<input type="text" name="languageType"><br>
    hands-on background:<input type="text" name="workTime"><br>
    <input type="submit" value="java Object receive request parameters">
</form>

MyController. The following methods are added to Java:

/**
 * Demonstrates using java objects to receive requests with parameters
 * Requirements: the parameter name in the request is consistent with the attribute name in the java object, and the parameter free construction method is provided in the java object
 *
 * @return
 */
@RequestMapping(value = "/test/param_object.do")
public ModelAndView doParamObject(Programmer programmer) {

    ModelAndView mv = new ModelAndView();
    mv.addObject("language", programmer.getLanguageType());
    mv.addObject("work_time", programmer.getWorkTime());

    mv.setViewName("result");

    return mv;
}

As a result, readers can verify by themselves that this method of receiving parameters does not support the inconsistency between the parameter name in the request and the attribute name in the java object.

Return value of controller method

These include:

  • Andview: data and modelview. We have studied this.
  • String: only the view. The view path can be a full path or a logical name of the view.
  • void:
  • Object:
The view parser returns String type:
/**
 * The return type of the view controller is String
 *
 * @return
 */
@RequestMapping(value = "/test/controller_return_string.do")
public String doReturnString(String languageType, Integer workTime) {

    // How to use the logical name of the view parser
    return "result";
    // If you want to use full path, you can't use view parser
    //return "/WEB-INF/view/result.jsp";
}

If you only return the view and want to attach data, you can add formal parameters to the method as follows:

@RequestMapping(value = "/test/controller_return_string.do")
public String doReturnString(HttpServletRequest request, String languageType, Integer workTime) {
    // Return only the data attached to the view
    request.setAttribute("language", languageType);
    request.setAttribute("work_time", workTime);

    // How to use the logical name of the view parser
    return "result";
}
The view parser returns void type:

Complete the AJAX request.

The first step is to create a folder js under webapp

And put the file jquery-3.4.1 JS in this folder.

Step 2: add dependency

Since it is a request, the format processing of the data of the request result is usually json format. What we add is json dependency:

<!--    jackson rely on    -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.10</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.10</version>
</dependency>

All dependencies are in POM XML file.

Step 3, in index Request initiated in JSP page

First, under the head tag, introduce the jQuery JS library we added. The code is as follows:

<script charset="UTF-8" type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-3.4.1.js"></script>

It should be noted that such errors may be encountered:

Failed to load resource: the server responded with a status of 404

The browser can see by pressing F12 that the local js file is not loaded successfully, so most of the problems are path problems, so the path here needs to be added <% = request Getcontextpath()% >, if you started with js / jquery-3.4.1 js, there will be no syntax error, but there will be the error I wrote. That's why you need to add the request context path.

Then add a button in the body to initiate an ajax request when clicking:

<%--The return type of the presentation view controller is void--%>
<button id="btnAjax" type="button">launch Ajax request</button>

Then, in the head tag, write a javaScript script under the imported js code we just wrote:

<%--  launch ajax request  --%>
<script type="text/javascript">
    $(function () {
        $("#btnAjax").on("click",function () {
            alert("click success")
        })
    })
</script>

Let's test whether it will take effect after clicking. As a result, you can verify that there is no problem. Next, we will write specific response data, that is, wrap json format.

After there are no problems above, we will demonstrate the real request response results of Ajax. We modify the script as follows:

<%--  launch ajax request  --%>
<script type="text/javascript">
    $(function () {
        $("#btnAjax").on("click",function () {
            $.ajax({
                dataType: 'json',
                url: 'return-void-ajax.do',
                data:{
                    languageType:"ajax request",
                    workTime:20220303
                },
                // response is a custom parameter
                success: function (response) {
                    alert("ajax Request response result:"+response.languageType+response.workTime);
                }
            });
        })
    })
</script>

The response data format we specify here is json, which is why we need to add corresponding dependencies at the beginning. This step is done. Our controller, that is, the server has not been written yet. As before, add a new method in MyController as follows:

/**
 * The return type of the controller is void. Use ajax to request the demonstration result
 *
 * @param response
 * @param languageType
 * @param workTime
 * @throws Exception
 */
@RequestMapping(value = "/return-void-ajax.do")
public void doAjax(HttpServletResponse response, String languageType, Integer workTime) throws Exception {
    Programmer programmer = new Programmer();
    programmer.setLanguageType(languageType);
    programmer.setWorkTime(workTime);

    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(programmer);

    response.setContentType("application/json;charset=utf-8");
    PrintWriter pw = response.getWriter();
    pw.print(json);
    pw.flush();
    pw.close();
}

The test results in the browser can show that the data specified in ajax is correct. This part is mainly to be familiar with the process and master the sequence and logic of program execution.

Perform process analysis

The user initiates the request, first to the server (Tomcat), and then to the central scheduler (dispatcher servlet) for distribution to different controllers. Then the Controller executes the corresponding business logic and returns the data view to the result page.

There can be multiple controllers. We only wrote one in the above example, and there can be multiple methods in a controller to process different requests, and the same method can also process multiple requests.

summary

  • Spring MVC can actually be understood as a encapsulated framework to simplify our workflow and improve development efficiency
  • The Spring system is huge. We have learned the previous Spring Framework. Now we feel very relaxed to learn Spring MVC, and we will feel that the pressure in the follow-up is not so heavy

Learn programming, recommend the first choice of Java language, Xiaobian created a dedicated Java official account recommendation Java, you can search for javaFirst in WeChat, and start the Java journey together!

Keywords: Java Spring Ajax Spring MVC

Added by Rother2005 on Fri, 04 Mar 2022 13:06:25 +0200