SPRING Boot cross-domain access processing

Source: Internet
Author: User
Tags getmessage

Respect for the original: http://blog.csdn.net/ruiguang21/article/details/77878933

  1. Problem scenario: Because the project is used to cross-domain access, today also get expert guidance, so write to share to everyone may be considering the front and back end of the separation, the Frontend backend server is not on a machine, this cross-domain access situation occurs. Normal local access is not a problem, but encountered this non-identical server situation, will be error access-control-allow-origin. The specific error content does not remember.
  2. Problem Solution One: Add a interceptor to the request by adding cross-domain access to the header, allowing cross-domain access.
  3. Bag Com.meicloud.interceptor;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.log4j.logger;import Org.springframework.web.servlet.modelandview;import Org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class Commoninterceptor Extended Handlerinterceptoradapter {Private final static recorder recorder = Logger.getlogger (commoninterceptor.        Class); @ Overwrite Common Boolean prehandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws exception {Logger.info ("Add cross-domain access header configuration, access-contr        ol-allow-origin:* ");        Cross-domain access to cors response.addheader ("Access-control-allow-origin", "*");        Response.AddHeader ("Access-control-allow-methods", "Post,get,options,put,delete,head");        Response.AddHeader ("Access-control-allow-headers", "S_id,content-type");        Response.AddHeader ("Access-control-max-age", "3600000");                Response.AddHeader ("Access-control-allow-credentials", "true"); Let the request, not be cached, Response.setheader ("Cache-conTrol "," No-cache ");          Response.setheader ("Cache-control", "No-store");          Response.setheader ("Pragma", "No-cache");        Response.setdateheader ("Expires", 0);        Logger.debug ("================================== prehandle");    Returns true; } @ Overwrite public invalid Posthandle (HttpServletRequest request, HttpServletResponse response, Object handler, Modelandview MoD    Elandview) throws Exception {Logger.debug ("================================== posthandle"); @ Overwrite public void aftercompletion (HttpServletRequest request, HttpServletResponse response, object handler, EXCEP    tion ex) throws exception {Logger.debug ("================================== aftercompletion"); }}

      

  4. Above is the interceptor content, the following is the configuration of the Interceptor.
Bag Com.meicloud.config;import Org.springframework.context.annotation.componentscan;import Org.springframework.context.annotation.configuration;import Org.springframework.web.servlet.config.annotation.interceptorregistry;import Org.springframework.web.servlet.config.annotation.resourcehandlerregistry;import Org.springframework.web.servlet.config.annotation.viewcontrollerregistry;import Org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;import Com.meicloud.interceptor.CommonInterceptor, @ComponentScan @ Configuring public class Webmvcconfig extension Webmvcconfigureradapter {        @ overwrite    public  void Addinterceptors (Interceptorregistry registry) {         //TODO auto-generated method stub         Registry.addinterceptor (New Commoninterceptor ()). Addpathpatterns ("/Getdoc");    }  }

And then you can use him in the controller, and here's my controller.

We can implement this method by invoking this method, and this method can be used to implement this method in a simple way. Basereturn Basereturn = new Basereturn (); String name = Mailentity.getname (); String company = Mailentity.getcompany (); String department = mailentity.getdepartments (); String job = Mailentity.getjob (); String email = mailentity.getemail (); String phone = Mailentity.getphone (); String doc = Mailentity.getdoc (); try {if (name = = NULL | | name.equals (")) {throw new Commenexception (" Name cannot be empty! } if (email = = NULL | | Email.equals ("")) {throw new commenexception ("Email cannot be empty! ”); } if (phone = = NULL | | Phone.equals ("")) {throw new Commenexception ("The phone number cannot be empty! ”); } if (doc = = NULL | | Doc.equals ("")) {throw new Commenexception ("The document cannot be empty! ”); } } catch (Exception E1) {Basereturn.setcode (returntype.fail); Basereturn.setmsg (E1.getmessage ()); Log.error (E1.getmessage ()); Return to base to return; } try {//Imailclent.sendmail (mailentity); Imailclent.sendhtmlmail (mailentity); Basereturn.setcode (returntype.success); catch (Exception e) {e.printstacktrace (); Basereturn.setcode (Returntype.fail); Basereturn.setmsg ("Failed to send mail!" ”); Log.error (E.getmessage ()); } return Basereturn; }

Next is the front-end call, with the Ajax POST request

var params ={name: Name, Company: Company, Department: Department, Work: work, email: email, phone: phone, Doc:'/Doc/api.doc '};var Type= ' POST '; var url= Config.host +url;$ ({url:url, data: json.stringify (params), type: ' type ', ContentType: "Application/json ", Async:false, Success: function (data) {//Todo Success}, Error: function (data) {//Todo failed}});

Problem Solution Two: use JSONP to achieve cross-domain access, directly on the code, the front-end code is:

url = '/http/localhost:9999/getdoc ' + '? Name = ' + params.name              + ' &company = ' + params.company             + ' &departments = ' + params.departments + ' &job = ' + params.job< c8/>+ ' &email = ' + Params.email + ' &phone = ' + Params.phone + ' &doc = '            + params.doc;$ on ({        url:url,        type: ' Get ', C12/>async:false,        dataType: "Jsonp",        jsonpcallback: "Callback",        success: function (data) {            //TODO Success        },        Error: Function (data) {            //Todo failed        }    });

The

Restricted call method is get and the data type is JSONP. The back end must also respond to the Jsonpobject object.

@ResponseBody @RequestMapping (value = "/Getdoc", method = requestmethod.get) public jsonpobject Getdoc (HttpServletRequest please                String callback) {Basereturn Basereturn = new Basereturn ();        String name = Request.getparameter ("name");        String company = Request.getparameter ("Company");        String departments = Request.getparameter ("departments");        String job = request.getparameter ("job");        String email = request.getparameter ("email");        String phone = request.getparameter ("Phone");                String doc = Request.getparameter ("Doc"); try {if (name = = NULL | | name.equals (")) {throw new Commenexception (" Name cannot be empty!            ” ); } if (email = = NULL | | Email.equals ("")) {throw new commenexception ("Email cannot be empty!            ” ); } if (phone = = NULL | | Phone.equals ("")) {throw new Commenexception ("The phone number cannot be empty!            ” ); } if (doc = = NULL | | Doc.equALS ("")) {throw new Commenexception ("The document cannot be empty!            ” );            }} capture (Exception E1) {Basereturn.setcode (returntype.fail);            Basereturn.setmsg (E1.getmessage ());            Log.error (E1.getmessage ());        Return to the new Jsonpobject (Callback,basereturn);        } mailentity mailentity = new mailentity ();        Mailentity.setcompany (company);        Mailentity.setdepartments (department);        Mailentity.setdoc (DOC);        Mailentity.setemail (e-mail);        Mailentity.setjob (work);        Mailentity.setname (name);                        Mailentity.setphone (telephone);            try {imailclent.sendhtmlmail (mailentity);        Basereturn.setcode (returntype.success);            } capture (Exception five) {e.printstacktrace ();            Basereturn.setcode (Returntype.fail); Basereturn.setmsg ("Failed to send mail!            ” );        Log.error (E.getmessage ());    } returns the new Jsonpobject (Callback,basereturn);     }

Today get expert guidance, originally there is a more convenient way, can be achieved. But the principle is certainly the same, it is no doubt that by adding a message header to the request to set up cross-domain access. The new solution is to add @crossorigin annotations to the controller or method, for details please refer to: http://spring.io/blog/2015/06/08/cors-support-in-spring-framework

@ResponseBody    @RequestMapping (value = "/Getdoc", method = requestmethod.post) public Basereturn Getdoc (@RequestBody Mailentity mailentity,httpservletrequest Request, httpservletresponse response, HttpSession HttpSession) {     @CrossOrigin// Add cross-domain access message header            log.info ("Execution controller Homecontroller.getdoc") using annotations

  

SPRING Boot cross-domain access processing

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.