Annotate Controller and RequestMapping

In the previous example, we configured the mapping between the hyperlink request and the controller in SpringMVC-servlet.xml using annotations (remember to turn on scanning).

Using annotation-based controllers has two advantages:

  • Multiple processing methods can be written in a controller class to process multiple requests, reducing the number of controller classes and facilitating later maintenance. Unlike deploying mappings in configuration files, each controller class can only correspond to one request.
  • There is no need to deploy the mapping in the configuration file, just annotate a method using the RequestMapping annotation type for request processing.

RequestMapping annotations come in two types: method-level annotations and class-level annotations

1.1 Method Level

@RequestMapping(value = "/index/login")
Copy the code

The value attribute maps the request URI to the method and is the default attribute of the RequestMapping annotation. If there is only one value attribute, you can omit “value=”.

Building on the last project

  1. Enable annotation scanning in SpringMVC-Servlet

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

	<context:component-scan base-package="com.controller" />
	
	<! Add prefix suffix to controller return value automatically
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		id="internalResourceViewResolver">
		<! -- prefix -- -- >
		<property name="prefix" value="/WEB-INF/jsp/" />
		<! - the suffix - >
		<property name="suffix" value=".jsp" />
	</bean>
</beans>
Copy the code
  1. Modifying a Controller Class
@Controller
public class IndexController {
    @RequestMapping(value = "/index/login")
    public String login(a) {
        / * * return login on behalf of the name of the logical view, need according to the configuration of Spring MVC * file internalResourceViewResolver prefixes and suffixes to find the corresponding physical view * /
        return "login";
    }
    @RequestMapping(value = "/index/register")
    public String register(a) {
        return "register"; }}Copy the code

1.2 class level

@Controller
@RequestMapping("/index")
public class IndexController {
    @RequestMapping("/login")
    public String login(a) {
        return "login";
    }
    @RequestMapping("/register")
    public String register(a) {
        return "register"; }}Copy the code

The common way a Controller receives request parameters

2.1 Receive request parameters through entity beans

  1. Create javabeans for the parameters
package pojo;
public class UserForm {
    private String uname;// The same as the request parameter name
    private String upass;
    private String reupass; 
    / / getter and setter
}
Copy the code
  1. Modify JSP page

login.jsp

<%@ 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. <form action="${pageContext.request.contextPath }/main" method="post">< table> <tr> < TD >< td><input type="text" name="uname" class="textSize"></td> </tr> <tr> < TD ><input type="password" name="upass" class="textSize"></td>
				</tr>
				
				<tr>
					<td colspan="2"><button onclick="gogo()"/> <button onclick="cancel()"/></td>
				</tr>
				
			</table>
			${messageError}
		</form>
		
	</body>
</html>
Copy the code

Main.jsp, as the login success page

<%@ 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"${sessionScope.u.name} is welcome to this system. </body> </html>Copy the code
  1. Modifying a Controller Class
@RequestMapping("/main")
public String main(UserForm user, HttpSession session, Model model) {
        if("herlo".equals(user.getUname())&&"123456".equals(user.getUpass())) {
                session.setAttribute("u", user);
                return "main";
        }
        else {
                model.addAttribute("messageError"."Wrong username or password");
                return "login"; }}Copy the code

2.2 Receive request parameters through parameters of the processing method

The request parameters are received through the parameters of the processing method, that is, the form parameters are written directly into the parameters of the controller class method, that is, the parameter names are exactly the same as the request parameter names. The receive parameter mode is applicable to GET and POST submission requests.

Use the UserForm object (entity JavaBean) to receive the request parameters submitted by the registration page */
@RequestMapping("/register")
public String register(String uname,String upass, Model model) {
    if ( "zhangsan".equals(uname)&&"123456".equals(upass) ) {
    //awa}}Copy the code

2.3 Receive request parameters via HttpServletRequest

Request parameters are received via HttpServletRequest, applicable to GET and POST submission requests.

<a href="${pageContext.request.contextPath}/register? param=test"> register < / a >Copy the code
@Controller
public class RegisterController{
	@RequestMapping("/register")
	public String register(HttpServletRequest request, Model model) {
		System.out.println(request.getParameter("param"));
		return "register"; }}Copy the code

2.4 Receive request parameters in the URL through @pathVariable

  • @pathVariable cannot accept objects, but can accept multiple values.
  • @pathVariable (” XXX “) @pathvariable binds the placeholder parameter {XXX} in the URL to the method parameter of the processor class
<h1>pathVariable</h1>
<a href="${pageContext.request.contextPath}/hello/pathVariable/bigsea" > name is bigsea </a>
<br/>
<a href="${pageContext.request.contextPath}/hello/pathVariable/sea" > name is sea</a>
<br/>
Copy the code
/ * * * localhost: 8080 / for springmvc/hello/pathVariable bigsea * localhost: 8080 / for springmvc/hello/pathVariable/sea * these urls will be Execute this method and pass  bigSEA , sea as arguments to the name field */
@RequestMapping("/pathVariable/{name}")
public String pathVariable(@PathVariable("name")String name){
        System.out.println("hello "+name);
        return "helloworld";
}
Copy the code

2.5 Receive request parameters through @requestParam

  • Request parameters are received via @requestParam for GET and POST requests.
  • RequestParam will not report a 404 error if the request parameter is not the same as the received parameter. 2.2 RequestParam will not report a 404 error if the request parameter is not the received parameter.
/** * handle registration@RequestParamReceive request parameters */
@RequestMapping("/register")
public String register(@RequestParam String uname, @RequestParam String upass, Model model) {
    if ("zhangsan".equals(uname)&&"123456".equals(upass)) {
    //awa}}Copy the code

2.6 Receiving request Parameters using @modelAttribute

  • The @modelAttribute annotation, when placed on the parameter of the processing method, is used to encapsulate multiple request parameters into an entity object that is automatically exposed as model data for use in view page presentation. In 2.1, multiple request parameters are encapsulated in a single entity object and cannot be exposed as model data (you need to use the Model.addattribute statement to expose model data, data binding and model data presentation, see Chapter 12).
  • Request parameters are received through the @modelAttribute annotation, which is applicable to GET and POST submission requests.

Model.addattribute (XXX, XXX)

@RequestMapping("/register")
public String register(@ModelAttribute("user") UserForm user) {
    if ("zhangsan".equals(uname) && "123456".equals(upass)) {
        logger.info("Success");
        return "login"; // Successful registration, go to login.jsp
    } else {
        logger.info("Failure");
        // Using @modelattribute ("user") has the same functionality as model.addattribute ("user",user)
        // The uname value of ModelAttribute can be retrieved from the register.jsp page using the EL expression ${user.uname}
        return "register"; / / return the register. The JSP}}Copy the code

Redirection and forwarding

Redirection redirects the user from the current processing request to another view (such as a JSP) or processing request, invalidating all information stored in the previous request and entering a new request scope.

Forwarding is to forward the user’s currently processed request to another view or processing request, without invalidating the information stored in the previous request. Forwarding is a server action and redirection is a client action.