Use of spring MVC annotations

Posted by somethingorothe on Sat, 20 Nov 2021 04:09:55 +0100

Background: the traditional style Controller is written by the class that implements the Controller interface. This Controller not only needs to deploy mapping in the configuration file, but also can only write one processing method, which is not flexible enough. Spring 2.5 adds the Spring MVC annotation function to replace the traditional XML based Spring MVC configuration.

Advantages of annotation:

  • In the annotation based controller class, multiple processing methods can be written to process multiple requests (actions), which allows related operations to be written in the same controller class, so as to reduce the number of controller classes and facilitate future maintenance.
  • The annotation based controller does not need to deploy mapping in the configuration file, but only needs to use the @ RequestMapping annotation method for request processing.

The two main annotations in the Controller are @ Controller and @ RequestMapping

Controller

@The Controller annotation is used to declare that an instance of a class is a Controller.

import org.springframework.stereotype.Controller;
@Controller
public class HelloController {
    // Write the method to process the request
}

Moreover, Spring MVC finds all annotation based controller classes in the package through the scanning mechanism. Therefore, we must declare spring context in the configuration file and use < context: component scan base package = "package name" / > to scan the controller classes by the Spring MVC framework.

RequestMapping

After annotation is used, there are multiple methods to process requests in a controller, such as adding users, modifying user information, deleting users, etc. Each method is responsible for different request operations, and @ RequestMapping is responsible for mapping the request to the corresponding controller method.

@The RequestMapping annotation can be used on a class or method. Used on a class to indicate that all methods in the class that respond to requests take this address as the parent path.

Detailed explanation of RequestMapping property

value

The value attribute is the default attribute of the @ RequestMapping annotation. Therefore, if there is only the value attribute, the attribute name can be omitted. If there are other attributes, the value attribute name must be written.

@RequestMapping(value="user")
@RequestMapping("user")

The value attribute supports wildcard matching. For example, @ RequestMapping(value = "touser / *") indicates access http://localhost:8080/toUser/xxx All resources under.

path

Both the path attribute and the value attribute are used as mappings. That is, both @ RequestMapping(value = "user") and @ RequestMapping(path = "user") can access the User() method, and the path also supports wildcard matching.

name

The name attribute is equivalent to the annotation of the method, making the method easier to understand. For example, @ RequestMapping(value = "getUser", name = "get user information").

method

The method property indicates which HTTP requests the method supports. If the method attribute is omitted, it indicates that the method supports all HTTP requests.

@RequestMapping(value = "user",method = RequestMethod.GET) means that this method only supports GET requests. You can also specify multiple HTTP requests, such as @ RequestMapping(value = "user",method = {RequestMethod.GET,RequestMethod.POST}), indicating that this method supports both GET and POST requests.

params

The params property is used to specify the parameters specified in the request

@RequestMapping(value = "showUser",params = "type")
public String showUser() {
    return "showUser";
}

The request must contain a type parameter to execute the request. Namely http://localhost:8080/showUser?type=xxx The showuser () method can be accessed normally, and http://localhost:8080/showUser The showUser() method cannot be accessed normally.

consumers property

The consumers attribute is used to specify the submitted content type for processing the request, such as application/json, text/html.
@RequestMapping(value = "toUser",consumes = "application/json")

produces property

The produces property is used to specify the returned content type. The returned content type must be the type contained in the request header. For example, @ RequestMapping(value = "toUser",produces = "application/json").

In addition, the produces property can specify the encoding of the return value. For example, @ RequestMapping(value = "toUser", produces = "application/json,charset=utf-8") indicates that the utf-8 code is returned.

The following code demonstrates the specific use of annotations in spring MVC

Code demonstration

Use Maven to create a Web project and import relevant jar packages. The relevant file directories of the Web project are as follows

web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--        Start level 1-->
        <load-on-startup>1</load-on-startup>
        <init-param>
<!-        appoint springmvc Profile path-->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Springmvc configuration file springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<!--    Automatically scan the package to make the comments under the specified package effective, and IOC Unified container management-->
    <context:component-scan base-package="controller"/>
<!--    Give Way SpringMVC Do not deal with static resources  .css .js .mp3 .mp4-->
    <mvc:default-servlet-handler/>
<!--    Enable annotation support-->
    <mvc:annotation-driven/>
<!--    view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--        prefix-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
<!--        suffix-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

Create UserController entity class

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
//With class level annotation, RequestMapping on this class is the parent path of all response requests in the class
@Controller
@RequestMapping("/user")
public class UserController {
//value represents the URL of the request, and method represents the method of the request. The get request is set here. If it is a post request, this method cannot receive the request
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    //The annotation RequestParam indicates that the parameters of the request must contain username and password
    public String Login(@RequestParam String username, @RequestParam String password, Model model){
        String str = null;
        if (username.equals("lsl")&&password.equals("251210")){
            str="Successful login page";
        }
        else{
            str="Account password error, please login again";
        }
        model.addAttribute("msg",str);
        return "login";
    }
    @RequestMapping("/register")
    public String Register(){
        return "register";
    }
}

jsp file is relatively simple and is only used for display

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>home page</title>
  </head>
  <body>
  <form method="get" action="${pageContext.request.contextPath}/user/login">
    enter one user name<input name="username" type="text"/><br/>
    Please input a password<input name="password" type="text"/><br>
    <input type="submit">
  </form>

<a href="${pageContext.request.contextPath}/user/register"  style="text-decoration: none">register</a>
  </body>
</html>

login.jsp is used to receive the data returned by the processor and display the key value pair msg

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login interface</title>
</head>
<body>
    ${msg}
</body>
</html>

register.jsp is only used for jump pages

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Registered account</title>
</head>
<body>
user name:<input ><br>
password:<input ><br>
Confirm password:<input>
</body>
</html>

Run the tomcat server and jump to the index.jsp page first

Then enter the correct username and password, click Submit and enter the login.jsp page

If the login is successful, you can also select the wrong account and password

Note: the login.jsp page is still entered here, but the msg information is different, and there is no complex jump

register.jsp page

Restful style

The url format we encounter is generally https://xxx/xxx/xxx . This is the Restful style url.

This is achieved by receiving the requested parameters through the PathVariable annotation

The login code above is written in Restful style as follows

@RequestMapping(value = "/login/{username}/{password}",method = RequestMethod.GET)
public String Login(@PathVariable String username, @PathVariable String password, Model model){
        String str = null;
        if (username.equals("lsl")&&password.equals("251210")){
            str="Successful login page";
        }
        else{
            str="Account password error, please login again";
        }
        model.addAttribute("msg",str);
        return "login";
    }

In visit“ http://localhost:8080/user/login/lsl/251210 ”The above code will automatically bind the template variables {username} and {password} in the URL to the parameters with the same name annotated by @ PathVariable, that is, username=lsl, pwd=251210.

Topics: Java Spring mvc