SPRINGMVC Learning record seven--sjon data interactions and interceptors

Source: Internet
Author: User
Tags representational state transfer

JSON data Interaction 21.1 Why JSON data interaction

JSON data format in the interface calls, HTML pages are more commonly used, the JSON format is relatively simple, parsing is more convenient.

For example: WebService interface, transfer JSON data.

21.2 SPRINGMVC for JSON interaction

1, request JSON, output JSON, request is the JSON string, so in front-end pages need to convert the contents of the request to JSON, not very convenient.

2, request Key/value, output JSON. This method is more commonly used.

21.3 environment Ready 21.3.1 load JSON-turned jar package

The SPRINGMVC uses Jackson's package for JSON conversion (@requestBody and @responsebody using the package below for JSON), as follows:

21.3.2 Configuring the JSON Converter

Adding messageconverters to the annotation adapter

<!--Note Adapter--    <Beanclass= "Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">       < Propertyname= "Messageconverters">       <List>       <Beanclass= "Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></Bean>       </List>       </ Property>    </Bean>

Note: If you use <mvc:annotation-driven/> you do not need to define the contents above.

21.4 JSON interactive test 21.4.1 input JSON string, output is JSON string 21.4.1.1 jsp page

Use jquery's AJAX submission JSON string to parse the output JSON results.

21.4.1.2 Controller

21.4.1.3 test Results

21.4.2 input key/value, output is JSON string 21.4.2.1 jsp page

Use jquery's Ajax to commit the Key/value string and parse the output JSON results.

21.4.2.2 Controller

21.4.2.3 Test

RESTful support 22.1 What is restful

The restful architecture is one of the most popular Internet software architectures available. Its structure is clear, conforms to the standard, easy to understand, expands conveniently, therefore is getting more and more website adoption.

RESTful (that is, the abbreviation for representational state transfer) is actually a development concept and a good interpretation of HTTP.

1, the URL specification, write the RESTful format URL

Non-rest url:http://...../queryitems.action?id=001&type=t01

Rest URL Style: http://..../items/001

Features: URL concise, the parameters are uploaded to the server through the URL

2. HTTP Method specification

Either delete, add, update: Use URL is consistent, if delete, need to set HTTP method for delete, the same way add ...

Background controller method: Determine the HTTP method, if delete is performed to remove, if it is post execution Add.

3. ContentType specification for HTTP

When requested, specify ContentType, to JSON data, set to JSON-formatted type:

22.2 Rest Example 2.2.1 Requirements

Query the product information and return the JSON data.

2.2.2 Controller

Define methods for URL mapping using a restful URL, the ID of the query commodity information is passed to the controller.

The output JSON uses @responsebody to output the Java object json.

@RequestMapping (value= "/Itemsview/{id}"): {XXX} placeholder, the requested URL can be "/VIEWITEMS/1" or "/VIEWITEMS/2", Get the XXX variable in {XXX} by using @pathvariable in the method.

@PathVariable is used to map template variables in the request URL to the parameters of a functional processing method.

If requestmapping is represented as "/Itemsview/{id}", the ID and parameter names are the same,@PathVariable do not specify a name.

Front-end controller configuration for the 22.2.3 rest method

In the Web. XML configuration:

22.3 Analysis of static resources

The configuration of the front-end controller is specified in Url-parttern/, and there is a problem with static resource resolution:

Add a static resource resolution method in Springmvc.xml.

23 Interceptor 23.1 Intercept definition

Define the interceptor to implement the Handlerinterceptor interface. Three methods are available in an interface.

 Public classHandlerInterceptor1ImplementsHandlerinterceptor {//execute before entering the handler method//for identity authentication, identity authorization//such as identity authentication, if the authentication by means that the current user does not log in, need this method to intercept no longer execution down@Override Public BooleanPrehandle (httpservletrequest request, httpservletresponse response, Object handler)throwsException {//return False indicates interception, not down execution//return TRUE indicates release      return false; }   //after entering the handler method, return to Modelandview before executing//The scenario starts with Modelandview: Upload common model data (such as menu navigation) to the view here, or you can unify the specified view here@Override Public voidPosthandle (httpservletrequest request, httpservletresponse response, Object handler, Modelandview MoD Elandview)throwsException {}//execute handler complete execution of this method//Application Scenario: Unified exception handling, unified log processing@Override Public voidaftercompletion (httpservletrequest request, httpservletresponse response, Object handler, Exception ex) throwsException {}}

23.2 Interceptor Configuration 23.2.1 for handlermapping configuration

Springmvc Interceptors for handlermapping to intercept settings, if the interception is configured in a handlermapping, the handlermapping mapping succeeds handler eventually uses the interceptor.

<Beanclass= "Org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">    < Propertyname= "Interceptors">        <List>            <refBean= "HandlerInterceptor1"/>            <refBean= "HandlerInterceptor2"/>        </List>    </ Property></Bean>    <BeanID= "HandlerInterceptor1"class= "Springmvc.intercapter.HandlerInterceptor1"/>    <BeanID= "HandlerInterceptor2"class= "Springmvc.intercapter.HandlerInterceptor2"/>

It is generally not recommended.

23.2.2-like global interceptors

The SPRINGMVC configures a global-like interceptor, and the SPRINGMVC framework injects a similar global interceptor into each handlermapping.

23.3 intercept Test 23.3.1 test requirements

Test the timing of the execution of multiple interceptors by various parties.

23.3.2 Write two interception

23.3.32 Interceptors are released

Handlerinterceptor1...prehandle

Handlerinterceptor2...prehandle

Handlerinterceptor2...posthandle

Handlerinterceptor1...posthandle

Handlerinterceptor2...aftercompletion

Handlerinterceptor1...aftercompletion

Summarize:

The Prehandle method executes sequentially,

Posthandle and aftercompletion are executed in reverse order of interceptor configuration.

23.3.4 Interceptor 1 release, Interceptor 2 not released

Handlerinterceptor1...prehandle

Handlerinterceptor2...prehandle

Handlerinterceptor1...aftercompletion

Summarize:

Interceptor 1 release, Interceptor 2 Prehandle will be executed.

Interceptors 2 Prehandle not released, interceptors 2 Posthandle and aftercompletion will not be executed.

Posthandle will not execute as long as an interceptor is not released.

23.3.1 Interceptor 1 not released, Interceptor 2 not released

Handlerinterceptor1...prehandle

Interceptors 1 Prehandle not released, Posthandle and Aftercompletion will not be executed.

Interceptor 1 Prehandle not release, Interceptor 2 does not execute.

23.3.2 Summary

Based on the test results, the interceptor is applied.

For example: Unified log processing Interceptor, need the Interceptor Prehandle must be released, and put it in the Interceptor link in the first position.

For example: Login to the authentication interceptor, placed in the Interceptor link in the first position. The permission check blocker is placed after the login authentication interceptor. (check permissions only after login)

23.4 Interceptor Application (for login authentication) 23.4.1 requirements

1. User Request URL

2, Interceptor for intercept check

If the requested URL is a public address (a URL that can be accessed without landing), let the release

If the user session does not exist jump to landing page

If the user session has been released, continue the operation.

23.4.2 Login Controller method
@Controller Public classLogincontroller {//Login@RequestMapping ("/login")    PublicString Login (HttpSession session, string Username, string password)throwsException {//invoking service for user authentication// ...      //Save user identity information in sessionSession.setattribute ("Username", username); //REDIRECT to Product List page      return"Redirect:/items/queryitems.action"; }   //Exit@RequestMapping ("/logout")    PublicString Logout (HttpSession session)throwsException {//Clear Sessionsession.invalidate (); //REDIRECT to Product List page      return"Redirect:/items/queryitems.action"; }}

23.4.3 login Authentication intercept implement 23.4.3.1 code implementation
  Public classLogininterceptorImplementsHandlerinterceptor {//execute before entering the handler method//for identity authentication, identity authorization//such as identity authentication, if the authentication by means that the current user does not log in, need this method to intercept no longer execution down@Override Public BooleanPrehandle (httpservletrequest request, httpservletresponse response, Object handler)throwsException {//gets the requested URLString URL=Request.getrequesturi (); //determine if the URL is a public address (it will be exposed in the address configuration profile when it is actually used)//Here the address is the address of the landing submission      if(Url.indexof ("Login.action") >=0){         //If the login is submitted, the release         return true; }      //Judging SessionHttpSession Session=request.getsession (); //Remove user identity information from the sessionString username= (String) session.getattribute ("username"); if(Username! =NULL){         //identity exists, release         return true; }      //Execute here indicates user identity needs authentication, jump landing pageRequest.getrequestdispatcher ("/web-inf/jsp/login.jsp"). Forward (request, response); //return False indicates interception, not down execution//return TRUE indicates release      return false; }

23.4.3.2 Interceptor Configuration

SPRINGMVC Learning record seven--sjon data interactions and interceptors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.