Spring MVC 2

Source: Internet
Author: User

Spring processes ajax requests
Spring uses the jackson class library to help us convert java objects to json and xml data. It can directly convert the objects returned by the Controller Into json data for the client to use. The client can also transmit json data to the server for direct conversion. The procedure is as follows:
 
1. The following two jar packages must be introduced in the project:
Jackson-core-asl-1.7.2jar
Jackson-mapper-asl-1.7.2jar
2. Modify in the spring configuration file:

<! -- Ing requests and annotation POJO with ajax configuration --> <bean class = "org. springframework. web. servlet. mvc. annotation. annotationMethodHandlerAdapter "> <property name =" cacheSeconds "value =" 0 "/> <property name =" messageConverters "> <list> <bean class =" org. springframework. http. converter. json. mappingJacksonHttpMessageConverter "> </bean> </list> </property> </bean>

This header req. setRequestHeader ("accept", "application/json") must be added to the request to be sent. spring knows that the ajax request is sent.

The client code is as follows:

<Script> function createAjaxObj () {var req; if (window. XMLHttpRequest) {req = new XMLHttpRequest ();} else {req = new ActiveXObject ("Msxml2.XMLHTTP"); // ie} return req;} function sendAjaxReq () {var req = createAjaxObj (); req. open ("get", "ajax. do? Method = test1 & uname = James "); req. setRequestHeader ("accept", "application/json"); // This header must be added before spring knows that the ajax request req is sent. onreadystatechange = function () {eval ("var result =" + req. responseText); // eval function document. getElementById ("div1 "). innerHTML = result [0]. uname;} req. send (null) ;}</script>

The server code is as follows:

@ Controller @ RequestMapping ("ajax. do ") public class AjaxController {@ RequestMapping (params =" method = test1 ", method = RequestMethod. GET) public @ ResponseBody List <User> test1 (String uname) throws Exception // @ ResponseBody This annotation is used to handle ajax request return values can be any value, spring will automatically convert to the json object {String uname2 = new String (uname. getBytes ("iso8859-1"), "UTF-8"); System. out. println (uname2); System. out. println ("AjaxController. test1 () "); List <User> list = new ArrayList <User> (); list. add (new User ("everyone", "123"); list. add (new User ("Skoda", "456"); return list; // note that the returned value can no longer be a normal String }}

Interceptor in Spring
Define two basic methods for spring interceptor
1. Implementation interface: org. springframework. web. servlet. HandlerInterceptor.
The interface has the following methods that need to be rewritten:
Note: The Object handler in the parameter is the next interceptor.
A) public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
This method is executed before the action is executed to implement data preprocessing, such as encoding and security control.
If the return value is true, the action is executed.
B) public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception
This method is executed after the action is executed and before the view is generated. Here, we have the opportunity to modify the view layer data.
C) public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
Throws Exception
The final execution is usually used to release resources and handle exceptions. We can handle related exceptions based on whether ex is null. When we handle exceptions at ordinary times, we throw an exception from the underlying layer and finally reach the spring framework to this method.
2. Inheritance adapter: org. springframework. web. servlet. handler. HandlerInterceptorAdapter
This adapter implements the HandlerInterceptor interface. Provides empty implementations of all methods in this interface.

Public class Interceptor1 implements HandlerInterceptor {@ Overridepublic void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System. out. println ("Last executed !!! It is generally used to release resources !! ") ;}@ Overridepublic void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System. out. println ("after the Action is executed, it is executed before the view is generated !! ") ;}@ Overridepublic boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System. out. println (" executed before action !!! "); Return true; // continue to execute action }}

/* How to configure in XML. Sample Code: <mvc: interceptors> <bean class = "com. sxt. interceptor. MyInterceptor"> </bean> <! -- Intercept all springmvc URLs! --> <Mvc: interceptor> <mvc: mapping path = "/user. do"/> <! -- <Mvc: mapping path = "/test/*"/> --> <bean class = "com. sxt. interceptor. myInterceptor2 "> </bean> </mvc: interceptor> </mvc: interceptors> */public class Interceptor2 extends HandlerInterceptorAdapter {@ Overridepublic boolean preHandle (HttpServletRequest request, HttpServletResponse response, object handler) throws Exception {System. out. println ("MyInterceptor2.preHandle ()"); return true; // continue to execute action} // depending on your needs // @ Override // public void afterCompletion (HttpServletRequest request, httpServletResponse response, Object handler, Exception ex) throws Exception {// super. afterCompletion (request, response, handler, ex); //} // @ Override // public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {// super. postHandle (request, response, handler, modelAndView );//}}

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.