1.@RequestMapping

(I) Function: establish the corresponding relationship between request URL and processing method

(2) scope of action: can be applied on the class name or method

  • On a class: the first level of access to the directory
  • Function in method: second level access directory
  • Details: The path can start without writing/representing the root directory of the application

(3) Attributes

  • Path Specifies the URL of the request path
@Controller
@RequestMapping(path = "/test")
@ResponseBody
public class HelloController {
    @RequestMapping(path="/hello")
    public String sayHello(a){
        System.out.println("hello springMVC");
        return "success"; }}Copy the code
  • The value and path attributes are the same and can be omitted if there is only one parameter
@Controller
@RequestMapping(value = "/test")
@ResponseBody
public class HelloController {
    @RequestMapping(value="/hello")
    public String sayHello(a){
        System.out.println("hello springMVC");
        return "success"; }}Copy the code
  • Mthod specifies how the method is requested
@Controller
@RequestMapping(path = "/test",method = RequestMethod.GET)
@ResponseBody
public class HelloController {
    @RequestMapping(path="/hello")
    public String sayHello(a){
        System.out.println("hello springMVC");
        return "success"; }}Copy the code
  • Params: Used to specify request parameters

The key and value of the requested parameters must be exactly as configured

// The request parameter must have the parameter username
@RequestMapping(path = "/testRequestMapping",params={"username"})
    public String testRequestMapping(a){
        System.out.println("Test RequeMapping annotations");
        return "success";
    }

// The request parameter must have the parameter username, and the parameter name is heihei
@RequestMapping(path = "/testRequestMapping",params={"username=heihei"})
    public String testRequestMapping(a){
        System.out.println("Test RequeMapping annotations");
        return "success";
    }
Copy the code
  • The request header sent by HEADERS must contain the specified content
// The request parameter must have the parameter username, and the request header must contain Accpet
@RequestMapping(path = "/testRequestMapping",params={"username"},headers={"Accept"})
	public String testRequestMapping(a){
        System.out.println("Test RequeMapping annotations");
        return "success";
    }
Copy the code

(4) Binding of request parameters

  • 1.String data type

When the parameters passed to the web page are the same as the controller method parameters, the parameters are automatically bound

<a href="param/testParam? username=hehe"> Request parameters </a>// The request parameters must be the same as the method parameters

@RequestMapping(path="/testParam")
    public String testParam(String username){
        System.out.println(username);
        return "success";
    }
Copy the code
  • 2.javaBean

Entity type (JavaBean). The parameter name of the front end must be the same as the attribute name in the JavaBean

// A simple javaBean that contains only properties of the basic typeName: < input type ="text" name="username"/><br/> Password :<input type="text" name="password"/><br/> <input type="text" name="money" /><br/>

@RequestMapping(path ="/saveAccount")
public String testsaveAccount(Account account){
    System.out.println("Test saveAccount");
    System.out.println(account.getUsername());
    return "success";
}

// A complex javaBean containing reference data typesName: < input type ="text" name="username"/><br/> Password :<input type="text" name="password"/><br/> <input type="text" name="money"/><br/> Username :<input type="text" name="user.name"/><br/> User password :<input type="text" name="user.password" /><br/>

@RequestMapping(path ="/saveAccount")
public String testsaveAccount(Account account){
    System.out.println("Test saveAccount");
    System.out.println(account.getUsername());
    return "success";
}

Copy the code

2. Customize the type converter

Sometimes you need to convert a String argument passed in to a Date data type. This can be done through a custom Converter that must implement the Converter interface

Usage:

  • Step 1: Define a conversion class to implement the Converter interface
public class Stringtodate implements Converter<String.Date> {
    @Override
    public Date convert(String source) {
        Date parse=null;
        if(source==null) {
            throw new RuntimeException("Please pass in parameters.");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            parse = simpleDateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        returnparse; }}Copy the code
  • Step 2: Add the converter to the Spring container
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.qunar.controller.Stringtodate"/>
            </set>
        </property>
 </bean>

 <! -- Enable SpringMVC framework annotation support to add converter location -->
<mvc:annotation-driven conversion-service="conversionService"/>
Copy the code

3. Use servlet objects

Spring supports native ServletAPI objects as parameters to controller methods

HttpServletRequest
HttpServletResponse
HttpSession
Copy the code
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request,HttpServletResponse response,HttpSession session) {
	System.out.println(request);
	System.out.println(response);
	System.out.println(session);
	return "success";
}
Copy the code

4.@RequestParam

(1) Function

Copies the parameter named in the request to the parameter in the controller

(2) Attributes

Value: specifies the name of the request parameter.

Required: Whether this parameter must be provided in the request parameter. Default value :true. Indicates that this parameter must be provided. If this parameter is not provided, an error will be reported.

@RequestMapping(path = "/testDate")
    public String testDate(@RequestParam(value = "date")Date date){
        System.out.println("Test type converter");
        System.out.println(date);
        return "success";
}
Copy the code

5.@RequestBody

(1) Function

Used to get the request body content. Key =value&key=value… Structured data. The GET request mode is not applicable. The get request returns null

(2) Attributes

Required: Whether the request body is required. The default value is true. When the value is true, an error is reported in the GET request mode. If the value is false, the GET request returns null.

@RequestMapping(path = "/testRequestMapping") public String testRequestMapping(@RequestBody(required = false)String Body){system.out.println (" Test RequeMapping annotations "); System.out.println(body); return "success"; }Copy the code

6@PathVariable

Used to assign a placeholder in a request to a handler parameter with the specified name

/ / request url: http://localhost:8080/test/testVariable/100/aaa? a=100

@RequestMapping(path = "/testVariable/{id}/{path}")
    public String testVariable(@PathVariable("id")Integer id, @PathVariable("path") String path){
        System.out.println(id);
        System.out.println(path);
        return "success";
}
Copy the code

7.@ModelAttribute

(1) Function

  • Appears on a method to indicate that the current method is executed before the controller’s method. It can modify methods that have no return value or methods that have a concrete return value.

  • Appears on a parameter and gets the specified data to assign to the parameter.

(II) Attributes:

Value: key used to obtain data. The key can be the attribute name of the POJO or the key of the map structure.

(3) Basic use

@ModelAttribute
    public void testModelAttribute(String name) {
        System.out.println(name);
    }

    @RequestMapping(path="/hello")
    public String sayHello(String name){
        System.out.println("hello springMVC");
        System.out.println("name:"+ name);
        return "success";
    }
Copy the code

(4) The ModelAttribute modification method returns a value

@ModelAttribute
    public User returnUser(String name){
        System.out.println(name);
        User user = new User();
        user.setName("zhangsan");
        user.setAge(13);
        System.out.println(user);

        return user;
    }

    @RequestMapping(path="/user")
    public String getUser(User user) {
        System.out.println(user);
        return "success";
    }
Copy the code

(5) The ModelAttribute modification method does not have a return value

@ModelAttribute
public void showModel(String username,Map<String,User> map) {
	// query the database
	User user = findUserByName(username);
	System.out.println("Executing the showModel method"+user);
	map.put("abc",user);
}


@RequestMapping("/updateUser")
public String testModelAttribute(@ModelAttribute("abc")User user) {
	System.out.println("The controller handles requests by modifying the user :"+user);
	return "success";
}

Copy the code

8.@ResponseBody

(1) Function

This annotation is used to convert the object returned by the Controller method into data in a specified format, such as JSON or XML, via the HttpMessageConverter interface. By default, only String data is returned

Usage: Add Jackson dependency

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.7</version>
    </dependency>
Copy the code
@RequestMapping(path="/user")
    public User getUser(User user) {
        System.out.println(user);
        return user;
    }
Copy the code

Exception handler

Exceptions in the system include two types: expected exceptions and runtimeexceptions. The former captures exceptions to obtain exception information, and the latter reduces the occurrence of run-time exceptions by means of standard code development and testing. The DAO, Service, and Controller of the system are thrown upward through throws Exception. Finally, the SpringMVC front-end controller submits the dao, Service, and Controller to the Exception processor for Exception processing

SpringMVC’s custom exception handler implements the HandlerExceptionResolver interface

public class CustomExceptionResolver implements HandlerExceptionResolver {
	@Override
	public ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) { 
    ex.printStackTrace();
    CustomException customException = null;
    // If a system - defined exception is thrown, it is directly converted
    if(ex instanceof CustomException){
    customException = (CustomException)ex;
    }else{
    // If it does not throw a system custom exception, reconstruct a system error exception.
    customException = new CustomException("System error, please contact system administrator!");
    }
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("message", customException.getMessage());
    modelAndView.setViewName("error");
    returnmodelAndView; }}Copy the code

Configure exception handlers into the Spring container

<! -- Configure custom exception handlers -->
<bean id="handlerExceptionResolver" class="com.itheima.exception.CustomExceptionResolver"/>
Copy the code

10. The interceptor

Spring MVC’s processor interceptor is similar to the Filter used in Servlet development for pre-processing and post-processing of the processor. Users can define their own interceptors to implement specific functions.

SpringMVC’s interceptor implements the HandleInterceptor interface

public class HandlerInterceptorDemo1 implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
	System.out.println("The preHandle interceptor intercepted it.");
	return true;
	}
    
    // Is called when all interceptors in the interceptor chain return successfully before the DispatcherServlet returns a response to the client
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,Object handler,ModelAndView modelAndView) throws Exception {
	System.out.println("PostHandle method executed.");
	}
    // is called after the DispatcherServlet has fully processed the request and you can do some resource cleaning in this method.
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
	System.out.println("AfterCompletion method executed."); }}Copy the code

Configure interceptors in the Spring container

<! -- Configure interceptor -->
<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/ * *"/>
		<bean id="handlerInterceptorDemo1"class="com.web.interceptor.HandlerInterceptorDemo1">	</bean>
	</mvc:interceptor>
</mvc:interceptors>
Copy the code

Configure multiple interceptors

<! < MVC :interceptors> < MVC :interceptor> < MVC :mapping path="/**" /><! MVC :exclude-mapping path=""/><! - is used to specify the url -- -- > of < bean id = "handlerInterceptorDemo1" class = "com. Web. The interceptor. HandlerInterceptorDemo1" > < / bean > </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**" /> <bean id="handlerInterceptorDemo2" class="com.web.interceptor.HandlerInterceptorDemo2"></bean> </mvc:interceptor> </mvc:interceptors>Copy the code