SPRINGMVC data exchange

Source: Internet
Author: User

Front JSP page:

<%@ page language= "Java"Import= "java.util.*" pageencoding= "iso-8859-1"%><script type= "Text/javascript" src= "Js/jquery.min.js" ></ Script><a href= "/day01/spring/mvc" >submit</a><input type= "button" id= "BT1" value= "Ajax"/>< Script type= "Text/javascript" >var data= {        "Name": "Jacky",        "Age": "20"    }    /*//Request Key/value (no need to set the request type) $ (function () {$ ("#bt1"). Click (function () {$.ajax ({ty                PE: "POST", url: "/day01/spring/mvc",//contenttype: "Application/json;charet=utf-8",        Data:data, Success:function (data) {alert (data)}) })    })    */        //Request JSON string (requires set request type)$ (function () {$ ("#bt1"). Click (function () {$.ajax ({type:"POST", URL:"/day01/spring/mvc", ContentType:"Application/json;charet=utf-8", Data:JSON.stringify (data), success:function (data) {alert (data) }            })        })    })    </script>
View Code

Controller Source:

 Packagecom.spring;ImportJava.io.PrintWriter;ImportJava.util.HashMap;ImportJava.util.Map;ImportNet.sf.json.JSONObject;ImportOrg.springframework.ui.Model;ImportOrg.springframework.web.bind.annotation.ControllerAdvice;Importorg.springframework.web.bind.annotation.PathVariable;ImportOrg.springframework.web.bind.annotation.RequestBody;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportOrg.springframework.web.bind.annotation.ResponseBody;ImportOrg.springframework.web.servlet.ModelAndView;ImportCom.model.User, @ControllerAdvice @requestmapping ("/spring") Public classtestcontrollers{//controller with no return value to implement local refresh with Ajax, controller with return value to implement page jump and data response                  /** Output The return value as object to the current page * PrintWriter Output Object **/            /*@RequestMapping ("/mvc") public void Showperson (PrintWriter printwriter, @RequestBody String param)            {System.out.println (param);            Write response body String st = "{\" name\ ": \" Zhangsna\ ", \" name1\ ": \" Zhangsna\ "}";            Map map = Jsonobject.fromobject (ST);            SYSTEM.OUT.PRINTLN (map);        PRINTWRITER.PRINTLN (map); }        */                /** POJO (JavaBean) receives key/value from the foreground, * @ResponseBody output the user object to the body of the response*/                /*@RequestMapping ("/mvc") public @ResponseBody user Showperson (user user) {Sys                     TEM.OUT.PRINTLN (user);          return user; }         */                /** Receive the JSON string passed by the foreground, * @ResponseBody output the user object to the body of response*/        /*@RequestMapping ("/mvc") @ResponseBody public Map Showperson (@RequestBody String params) {            @SuppressWarnings ("unchecked") map<string,object> Map = Jsonobject.fromobject (params);                   SYSTEM.OUT.PRINTLN (map);        return map; }*/            /** Modelandview views and models (data) * A data object built into the model **/@RequestMapping ("/demo1")         PublicModelandview Execute (model model) {//setting up the data ModelModel.addattribute ("name", "Jacky"); Model.addattribute ("Age", "20"); Model.addattribute ("School", "Shaanxi Polytechnic University"); //set up the view data ModelModelandview Mav =NewModelandview (); Mav.setviewname ("Return"); Mav.addobject ("Data", model); returnMav; }        /** Custom Parameters*/@RequestMapping ("/demo2")         PublicModelandview Execute () {MAP data=NewHashMap (); Map Map=NewHashMap (); //setting up the data ModelMap.put ("name", "Jacky"); Map.put ("Age", "20"); Map.put ("School", "Shaanxi Polytechnic University"); Data.put ("Data", map); //return to the View data model            return NewModelandview ("Return", data); }                /** @RequestParam ("user") the values passed by user and foreground are consistent **/@RequestMapping ("/demo3")         Public voidExecute (printwriter writer, @RequestParam ("User"String name) {writer.print (name); }                /** @RequestParam ("user") the values passed by user and foreground are consistent * Requestmethod.get Request method*/@RequestMapping (Value= ("/demo04"), method={requestmethod.get,requestmethod.post}) Public voidExecutes (printwriter writer, @RequestParam ("User"String name) {writer.print (name); }                /** Method={requestmethod.get,requestmethod.post} Request method * @PathVariable ("TestID") binds the variable in the URL to the controller's The rest interface can be implemented in formal parameters **/@RequestMapping (Value= ("/delete/{testid}"), method={requestmethod.get,requestmethod.post}) Public voidExecut (printwriter writer, @PathVariable ("TestID") (String ID) {Writer.print ("Delete ID is:" +ID); }    }
View Code

Response View JSP:

Import= "java.util.*" pageencoding= "Utf-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >    return JSP page. <br>     return Data: ${data}   </body>
View Code

Common Error Analysis:

1. No class error was found when running Tomcat, go to Tomcat to see that the project is deployed to Tomcat (MyEclipse and idea should also have jar package dependencies at the corresponding output path )

2. The processor cannot find handler based on the URL

  

3. Forwarding JSP page not found

  

4.json data to Java object

5. Browser 406 Error

  

SPRINGMVC data exchange

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.