Premium SpringMVC

Request limit

In some cases we may need to request restrictions, such as allowing only POST, GET, etc. ...

RequestMapping annotation is provided a plurality of parameters for the request to add restrictions

  • value request address
  • path request address
  • method request method
  • headers must be included in the request header field specified
  • params must contain a request parameter
  • consumes media type received data (before processing request match contentType)
  • produce return media type (only accept processing request match)

Case:

@RequestMapping(value = "/editCourse",method = RequestMethod.POST,headers = {"id"},params = {"name"},consumes = {"text/plain"},produces = {"text/html"})//含义:url为/editCourse 请求方法为POST hander必须包含id字段  参数必须包含name 只接受text/plain类型数据 返回数据类型为text/html

To simplify the writing, the MVC also provides a set of annotations and method for limiting the path, the method comprising a common request:

PostMappingGetMappingDeleteMappingPutMapping例:@PostMapping("/editCourse")

handler return value

handler method may be three types of return values ​​for different scenes

ModelAndView

Packaging view and return value data type for the name and returns the logical view of data views to be presented

It is equivalent to adding properties in the Request, then forwards the request

Example:

@RequestMapping("/test")public ModelAndView test() {    ModelAndView modelAndView = new ModelAndView();    modelAndView.setViewName("index.jsp");    modelAndView.addObject("msg", "hello ssm!");    return modelAndView;}

void

It represents handler does not return any data, when it is necessary for the scene directly operated in response completion response

Example:

@RequestMapping("/test2")public void test2(String name,HttpServletResponse response) throws IOException {    response.getWriter().println(name.toUpperCase());}

String

Returns a value of type string, the content may be returned view name request address may be other

Behind uses a request forwarded by the way

Example:

@RequestMapping("/test3")public String test3(Model model) {    model.addAttribute("msg","hello XXX");    return "index.jsp";}@RequestMapping("/test4")public String test4() {    return "/test";}

Forwarding and Redirection:

The request may specify the target address is redirected or by forwarding the request;

Example:

@RequestMapping("/test5")public String test5() {    return "forward:/index.jsp";}@RequestMapping("/test6")public String test6() {    return "redirect:/index.jsp";}

Of course, the default is to forward it can be omitted;

json interaction

Moment, most companies will have a mobile end App, when our back-office services when needed to provide an interface for the App, you have to use the data to json, of course, the front and rear end of the front-end and back-separation project also uses json to exchange data;

Before starting, we need to import jackson dependent, and for achieving the sequence of the deserialization json;

<dependency>  <groupId>com.fasterxml.jackson.core</groupId>  <artifactId>jackson-databind</artifactId>  <version>2.9.9</version></dependency>

Return json data

@ResponseBody annotation handler for labeling a method returns json data, and returns as the return value to the method of the reception data;

Example:

@RequestMapping("/getCourseList")@ResponseBodypublic List<Course> getCourseList() {  //获取所有课程    return courseService.selectCourses();}@RequestMapping("/getCourse")@ResponseBodypublic Course getCourse(Integer id) {// 根据id获取一个课程    return courseService.selectByID(id);}

ContentType ResponseBody will respond to application / json, then calls the toJsonString jackson json return value into a string, and finally returned to the client;

@RestController

If you need to add ResponseBody for each method, then it is very troublesome, SpringMVC provides @RestController notes, that this is all a handler return values ​​are all the json Controller, Controller and ResponseBody equivalent to two notes combined;

Example:

@RestControllerpublic class CourseController {.....}

Accepting json data

SpringMVC can help us deserialization json parameter to specify the type of entity, List or Map;

It is emphasized that: the client must specify ContenType as application / json

@RequestMapping("/addCourse")@ResponseBodypublic Course addCourse(@RequestBody Course course) {//接收json参数映射到实体    course.setName("接收json成功");//修改name再把数据发回去 以便查看效果    return course;}@RequestMapping("/addCourses")@ResponseBodypublic List<Course> addCourse(@RequestBody List<Course> courses) {//接收json数组参数映射到list    return courses;}@RequestMapping("/addData")@ResponseBodypublic Map<String,String> addData(@RequestBody Map<String,String> data) {//接收json数据映射到map    return data;}@RequestMapping("/addInfo")@ResponseBodypublic String addInfo(@RequestBody String data) {//接收json数据不做任何转换    return data;}

When passed by the client json complex may not be converted directly to an entity type, which we can receive through the Map, or direct access to the raw json string handling yourself; just the same as above addData and addInfo

Handler Interceptors

As the name suggests interceptor Handler Handler intercepts method can control whether to execute the method Handler, the filter is very similar to the Servlet

But be careful:

Servlet execution timing of the filter is before SpringMVC, filtering the target object is a request;

The Handler interceptor to intercept the target object is a method Handler

Handler interceptors can easily achieve, verify the login state, the operation rights verification operation;

Use Cases:

1. Preparation of interceptor

public class MyInterceptor implements HandlerInterceptor {    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        //在执行handler前调用   返回值将决定是否继续执行请求        System.out.println("preHandle");        return true;    }    @Override    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {        //handler被真正执行了,已经拿到了handler的返回结果  但是DispatcherServlet还没有发送给前台        System.out.println("postHandle");    }    @Override    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {        //DispatcherServlet将视图发送给前台后的回调 (无论handler是否执行 一定有响应发给前台)        System.out.println("afterCompletion");              //Handler中出现的任何异常也会传给该方法,可以在这里进行处理          if (ex != null){            System.out.println("handler中出现异常了....");        }    }}

2. Configure interceptor

<mvc:interceptors>    <mvc:interceptor>        <mvc:mapping path="/**"/>        <bean class="com.kkb.interceptor.MyInterceptor"/>    </mvc:interceptor></mvc:interceptors><!--* path用于指定拦截器拦截的url只有handler的url与之匹配才会被拦截  /** 表示拦截所有请求* interceptors中可配置多个interceptor -->

3. execution order

Blocker execution order determined by the order of arrangement, and a filter as interceptors also be in the form of a chain

"SpringMVC Advanced Edition"

 

When the request processing is completed, it notifies the interceptor in reverse order (i.e., execution afterComplation), provided that the normal release request interceptor (preHandler are returned to true), they will not be notified;

Exception Handling

A complete system must consider handle exceptional conditions, SpringMVC provides a very convenient method of treatment, only we need to implement HandlerExceptionResolver interface and to register Bean container can be

1. Preparation exception handler

@Componentpublic class MyExceptionHandler implements HandlerExceptionResolver {    @Override    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {        ModelAndView modelAndView = new ModelAndView();        modelAndView.setViewName("error.jsp");        modelAndView.addObject("exobj",ex);        return modelAndView;    }}

The return value can be seen in ModelAndView approach, we need to add the name and the error message error page;

2. Register to the container

Component annotations can be added directly or, registered in the configuration file

<bean class="com.kkb.exceptionhandler.MyExceptionHandler"/>

Stressed: Whether or exception handler interceptors are not all requests for a handler, for example if the request itself is wrong as 404, is an exception can not be handled exception handler Handler, still need to be carried out web.xml configuration

Guess you like

Origin www.cnblogs.com/CQqfjy/p/12330513.html