@Controller and @ RequestMapping annotations

Posted by coldfiretech on Sun, 06 Mar 2022 12:23:30 +0100

Spring 2.5 adds the Spring MVC annotation function to replace the traditional XML based Spring MVC configuration.

The traditional style controller not only needs to deploy the mapping in the configuration file, but also can only write one processing method, which is not flexible enough.

Using annotation based controllers has two advantages:

  1. In the annotation based controller class, multiple processing methods can be written, and then multiple requests (actions) can be processed, 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.
  2. The annotation based controller does not need to deploy mapping in the configuration file, but only needs to use @ RequestMapping annotation to process the request.


The following describes the two most important annotation types in Spring MVC: @ Controller and @ RequestMapping.

1, Controller annotation

@The Controller annotation is used to declare that an instance of a class is a Controller. For example, in net biancheng. Create the Controller class IndexController in the Controller package. The example code is as follows.

package net.biancheng.controller;


import org.springframework.stereotype.Controller;


@Controller
public class IndexController {
// Method of processing request
}

Spring MVC uses the scanning mechanism to find all annotation based controller classes in the application. Therefore, in order for the controller class to be scanned by the spring MVC framework, you need to declare the spring context in the configuration file and specify the basic package of the controller class using the < context: component scan / > element (please ensure that all controller classes are under the basic package and its sub packages).

For example, in the configuration file of the spring MVC demo application, spring MVC servlet Add the following code to the XML:

  1. <!-- Use the scanning mechanism to scan the controller classes, which are all in net biancheng. Controller package and its sub packages -- >
  2. <context:component-scan base-package="net.biancheng.controller" />

2, RequestMapping annotation

There are multiple methods to process requests in a controller, such as adding users, modifying user information, deleting specified users, obtaining user list according to conditions, etc. Each method is responsible for different request operations, and @ RequestMapping is responsible for mapping the request to the corresponding controller method.

In the annotation based controller class, the corresponding processing method can be written for each request. Use the @ RequestMapping annotation to correspond the request to the processing method one by one.

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

@The common attributes of the RequestMapping annotation are as follows.

1. value attribute

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

  • @RequestMapping(value="toUser")
  • @RequestMapping("toUser")

The value attribute supports wildcard matching, such as @ RequestMapping(value="toUser / *") http://localhost:8080/toUser/1 Or http://localhost:8080/toUser/hahaha Can be accessed normally.

2. path attribute

Both the path attribute and the value attribute are used as mappings. That is, both @ RequestMapping(value="toUser") and @ RequestMapping(path="toUser") can access the toUser() method.

The path attribute supports wildcard matching, as indicated by @ RequestMapping(path="toUser / *") http://localhost:8080/toUser/1 Or http://localhost:8080/toUser/hahaha Can be accessed normally.

3. name attribute

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

4. method attribute

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 = "toUser",method = RequestMethod.GET) means that this method only supports GET requests. You can also specify multiple HTTP requests, such as @ RequestMapping(value = "toUser",method = {RequestMethod.GET,RequestMethod.POST}), indicating that this method supports both GET and POST requests.

5. params attribute

params attribute is used to specify the parameters specified in the request. The code is as follows.

@RequestMapping(value = "toUser",params = "type")
public String toUser() {


return "showUser";
}

The above code indicates that the request can be executed only when the type parameter must be included in the request. Namely http://localhost:8080/toUser?type=xxx The touser () method can be accessed normally, and http://localhost:8080/toUser The toUser() method cannot be accessed normally.

@RequestMapping(value = "toUser",params = "type=1")
public String toUser() {


return "showUser";
}

The above code indicates that the request must contain the type parameter, and the request can be executed only when the type parameter is 1. Namely http://localhost:8080/toUser?type=1 The touser () method can be accessed normally, and http://localhost:8080/toUser?type=2 The toUser() method cannot be accessed normally.

6. header attribute

The header attribute indicates that the request must contain some specified header values.

@RequestMapping(value = "toUser",headers = "Referer=http://www.xxx.com ") indicates that the request header must contain the specified" referer "request header and the value is“ http://www.xxx.com ”The request can only be executed when.

7. consumers attribute

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

8. Produ attribute

The produces property is used to specify the returned content type. The returned content type must be the type contained in the request header (Accept). 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.

Use @ RequestMapping to complete the mapping, including four information items: request URL, request parameter, request method and request header.

Mapping by request URL

1) Method level annotation

The example code of method level annotation is as follows.

package net.biancheng.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class IndexController {
@RequestMapping(value = "/index/login")
public String login() {
return "login";
}


@RequestMapping(value = "/index/register")
public String register() {
return "register";
}
}

In the above example, there are two RequestMapping annotation statements, both of which act on the processing method. In the whole Web project, the request information mapped by @ RequestMapping must be globally unique.

Users can use the following URL to access the login method (request processing method). Before accessing the login method, you need to create login in the / WEB-INF/jsp / directory jsp.

http://localhost:8080/springmvcDemo/index/login

2) Class level annotation

The example code of class level annotation is as follows:

package net.biancheng.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/index")
public class IndexController {
@RequestMapping("/login")
public String login() {
return "login";
}


@RequestMapping("/register")
public String register() {
return "register";
}
}

In the case of class level annotation, all methods in the controller class will be mapped to class level requests. Users can use the following URL to access the login method.

http://localhost:8080/springmvcDemo/index/login

In order to facilitate the maintenance of the program, it is recommended that developers use class level annotation to put the relevant processing in the same controller class. For example, the processing methods of adding, deleting, modifying and querying users can be placed in the UserController control class.

Mapping through request parameters and request methods

@In addition to using the request URL to map requests, RequestMapping can also use request parameters and request methods to map requests. Multiple conditions can make the request mapping more accurate.

package net.biancheng.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class IndexController {
@RequestMapping(value = "/index/success" method=RequestMethod.GET, Params="username")
public String success(@RequestParam String username) {


return "index";
}

In the above code, @ RequestMapping value represents the requested URL; Method refers to the request method. It is set as GET request here. If it is a POST request, it cannot enter the success processing method. params refers to the request parameter, where the parameter name is username.

3, Write request processing method

In the control class, each request processing method can have multiple different types of parameters and one or more types of return results.

1) Parameter types that often appear in request processing methods

If you need to use Servlet API types in the request processing method, you can use these types as the parameter types of the request processing method. The sample code of Servlet API parameter type is as follows:

package net.biancheng.controller;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/index")
public class IndexController {
@RequestMapping("/login")
public String login(HttpSession session,HttpServletRequest request) {
session.setAttribute("skey", "session Range value");
session.setAttribute("rkey", "request Range value");
return "login";
}
}

In addition to the Servlet API parameter types, there are input and output streams, form entity classes, annotation types, Spring framework related types, etc. these types will be described in detail when used in subsequent chapters.

A particularly important type is org springframework. ui. Model type, which is a spring MVC type containing Map. Spring MVC will create org. Org every time the request processing method is called springframework. ui. Model object. The example code of the model parameter type is as follows:

 

package net.biancheng.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/index")
public class IndexController {
@RequestMapping("/register")
public String register(Model model) {
/*In the view, you can use the EL expression ${success} to get the value in the model*/
model.addAttribute("success", "login was successful");
return "register";
}
}

2) Common processing methods for request return types

The request processing method can return the following types of objects:

  • ModelAndView
  • Model
  • Map containing model properties
  • View
  • String representing logical view name
  • void
  • Any other Java type


The most common return type is the String type representing the name of the logical view, such as the request processing method in the previous sections.

4, Examples

Create a Web application springmvcDemo2 and import the corresponding JAR package (refer to< The first Spring MVC program >Section (imported JAR package).

The springmvcDemo2 application directory structure is as follows.

springmvcDemo2 directory structure


web. The XML code is as follows.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>springMVC</display-name>


<!-- deploy DispatcherServlet -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
<!-- Indicates that the container loads immediately when it restarts servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- Handle all URL -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

springmvc-servlet. The XML configuration file code is as follows.

  1. <?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    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
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan
    base-package="net.biancheng.controller" />
    
    
    <bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!--prefix -->
    <property name="prefix" value="/WEB-INF/jsp/" />
    <!--suffix -->
    <property name="suffix" value=".jsp" />
    </bean>
    </beans>

Create a User entity class with the following code. As mentioned earlier, one advantage of using the Controller annotation is that a control class can contain multiple request processing methods. Create UserController with the following code.

  1. package net.biancheng.controller;
    
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    
    import net.biancheng.po.User;
    
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
    
    @RequestMapping("/login")
    public String getLogin(Model model) {
    User us = new User();
    us.setName("Programming help");
    model.addAttribute("user", us);
    return "login";
    }
    
    
    @RequestMapping("/register")
    public String getRegister() {
    
    
    return "register";
    }
    }

index.jsp file page code is as follows.

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Unregistered users, please
<a href="${pageContext.request.contextPath }/user/register"> register</a>!
<br /> Registered users, go to
<a href="${pageContext.request.contextPath }/user/login"> Sign in</a>!
</body>
</html>

login. The JSP code is as follows.

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Login page! welcome ${user.name} Sign in
</body>
</html>

register. The JSP code is as follows.

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Registration page!
</body>
</html>

The operation results are as follows.

index.jsp page


register.jsp page


login.jsp page


In the page shown in the figure above, when the user clicks the "register" hyperlink, the controller will forward the request to the getLogin method of UserController for processing, and then jump to register under / WEB-INF/jsp JSP view. Similarly, when you click the "login" hyperlink, the controller will go to login. Under / WEB-INF/jsp after processing JSP view.

Topics: Spring MVC