SpringMVC Common Annotations (c)

A, @ Controller, @ RestController and @ControllerAdvice

1. @Controller

@Controller for marking on a class, which is a class mark SpringMVC Controller object. The processor will distribute a scanning method using the annotation class, and the method detects whether the @RequestMapping annotations.
Use @Controller annotations in the corresponding method, the parser may parse the view of the return jsp, html pages, and jump to the corresponding page;
if the page to return json etc., the need to add annotations @ResponseBody.

2. @RestController

@RestController annotation corresponds @ResponseBody + @Controller together effect.

@ResponseBody return json data does not add annotations in the previous method, but using @RestController this annotation, you can not return to jsp, html pages, view resolver can not resolve jsp, html page, what is returned is the return the contents.

If you use @RestController, want to return to the page, you need to use ModelAndView:

public ModelAndView login(){
        ModelAndView mv = new ModelAndView("index");
        return mv;
   }

3. @ControllerAdvice

@ControllerAdvice, the new notes after Spring3.2 offer, from the name of the controller can be seen in the general meaning is enhanced.

It is split open ControllerAdvice Controller Advice, on the Advice, which is a section for enclosing all the attributes, including point and facets of the logic required weaving. Here ContrllerAdvice also can be understood, it should be the level of abstraction of the Controller for a "slice" surround, and specific business woven into the way it is achieved through a combination of other annotations (@ControllerAdvice not the way to use AOP woven into the business logic, but Spring was built built-in support for its individual logical way of weaving). @ControllerAdvice annotation is declared in the class, which uses three main points:

(1) global exception handler, type annotation bonding method @ExceptionHandler, for capturing the specified type of exception thrown Controller, so as to achieve the difference between different types of exception processing

@ControllerAdvice(basePackages = "mvc")
public class SpringControllerAdvice {
  @ExceptionHandler(RuntimeException.class)
  public ModelAndView runtimeException(RuntimeException e) {
    e.printStackTrace();
    return new ModelAndView("error");
  }
}

Thrown in the interface of the RuntimeException, so in theory, this exception trap will catch the exception, then return the default error view. The following are UserController code:

@RequestMapping(value = "/detail", method = RequestMethod.GET)
public ModelAndView detail(@RequestParam("id") long id) {
    ModelAndView view = new ModelAndView("user");
    User user = userService.detail(id);
    view.addObject("user", user);
    throw new RuntimeException("mock user detail exception.");
}

Thrown in UserController exception can be captured SpringControllerAdvice.

It should be noted that the unified treatment of abnormal controller needs to be put under general controller and the same level package, or in ComponentScan package. In the handling of an exception can be used System.out manner, logger.info may be used, or may be into the database.

(2) binding global data, annotation @InitBinder type bonding method, the request for registering the custom parameter analytical methods, so as to achieve the specified custom format parameter;

For @InitBinder, the main role of the annotation is to bind some of the parameters to customize. Normally we use the parameters can be bound by @ RequestParam, @ RequestBody or @ModelAttribute and other notes, but for some special types of parameters, such as Date, which is bindings Spring does not provide direct support, we only energy converter for a declaration, the type of the request parameter string converted by the converter type Date of parameters, to supply @RequestMapping labeling method used.

@ControllerAdvice(basePackages = "mvc")
public class SpringControllerAdvice {
  @InitBinder
  public void globalInitBinder(WebDataBinder binder) {
    binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
  }
}

The method of labeling @InitBinder registered Formatter request will be called each time the request parameter conversion, the parameters for determining whether the specified parameters can be converted. The following are UserController code:

@RequestMapping(value = "/detail", method = RequestMethod.GET)
public ModelAndView detail(@RequestParam("id") long id, Date date) {
    System.out.println(date);
    ModelAndView view = new ModelAndView("user");
    User user = userService.detail(id);
    view.addObject("user", user);
    return view;
}

(3) pre-global data, annotation @ModelAttribute type bonding method, which represents a method of labeling will be executed before the execution target Controller method.

@ModelAttribute use, if the statement on the method, and binds @ControllerAdvice, this method will all interface methods within @ControllerAdvice specified range before execution, and the return value @ModelAttribute labeling methods may also be supplied subsequent calls interface methods.

@ControllerAdvice(basePackages = "mvc")
public class SpringControllerAdvice {
  @ModelAttribute(value = "message")
  public String globalModelAttribute() {
    System.out.println("global model attribute.");
    return "this is from model attribute";
  }
}

It should be noted that the method provides a return value of type String, and @ModelAttribute the specified attribute name Message, so that you can receive the parameter in the Controller layer, as is the UserController (Common @Controller):

@RequestMapping(value = "/detail", method = RequestMethod.GET)
public ModelAndView detail(@RequestParam("id") long id, 
       @ModelAttribute("message") String message) {
    System.out.println(message);
    ModelAndView view = new ModelAndView("user");
    User user = userService.detail(id);
    view.addObject("user", user);
    return view;
}

@ModelAttribute execution method is marked () method will be executed after the execution preHandle all interceptors.

4. @ControllerAdvice and the difference @RestControllerAdvice

// @ControllerAdvice @RestControllerAdvice can point and a subset of the controller
 // point of all controllers annotated @RestController 
@ControllerAdvice (Annotations = RestController. Class )
 public  class AnnotationAdvice {}
// point for controlling all the specified package 
@ControllerAdvice ( "org.example.controllers" )
 public  class BasePackageAdvice {}
// point to all controllers with the specified signature 
@ControllerAdvice (assignableTypes = {ControllerInterface. Class , of AbstractController. Class })
 public  class AssignableTypesAdvice {}

Difference @ControllerAdvice and @RestControllerAdvice similar to the difference @RestController and @Controller.

Two, @ RequestBody and @ResponseBody

1. @RequestBody

@RequestBody is acting on the parameter list, for transmitting data over the front fixed format [xml format or the like json encapsulated as JavaBean] corresponding to the object, when used to package an object is the default configuration HttpMessageConverter parses then packaged into a parameter.

public Object login(@RequestBody User loginUuser, HttpSession session)

2. 

 

Guess you like

Origin www.cnblogs.com/myitnews/p/11567719.html