I just started to contact SPRINGMVC, Project construction reference https://my.oschina.net/gaussik/blog/385697. When using idea write login registration, want to through the Ajax way to submit data to the background, and then encountered title the garbled problem, and then a lot of Niang, finally solved. Nonsense not much to say, directly on the code.
The first is the login page login.jsp
1<%--2 Created by IntelliJ.3 user:peng0274Date:2016/11/115time:15:486To change ThisTemplate Use File | Settings |File Templates.7--%>8<%@ page contenttype= "Text/html;charset=utf-8" pageencoding= "Utf-8" language= "java"%>9Ten One<title>index</title> A<script type= "Text/javascript" src= "/js/jquery.min.js" ></script> -<script type= "Text/javascript" > - function Login () { thevar name=$ ("#id1"). Val (); -var pwd=$ ("#id2"). Val (); - $.ajax ({ -URL: '/login ', +Type: ' Post ', -ContentType: ' Application/json ', +Data:JSON.stringify ({' username ': name, ' password '):p WD}), ADataType: ' JSON ', atAsyncfalse, - success:function (msg) { - //alert ("Page content changes"); - //$ ("#p"). Text (msg.msg); -Window.location.href= "success.jsp?id=" +math.random (); - }, in error:function () { -Alert ("Failure"); to } + }); - } the</script> * $<body>Panax Notoginseng<form> -Username:<input id= "ID1" type= "text" name= "username"/><br> thePassword:<input id= "id2" type= "password" name= "password"/><br> +<input id= "ID3" type= "button" value= "Login" onclick= "login ()"/><br> A<%--<p id= "P" > click Login I will change </p>--%> the</form> +</body> -View Code
Then the background Java code
1 PackageController;2 3 Importorg.json.JSONException;4 ImportOrg.json.JSONObject;5 ImportOrg.springframework.stereotype.Controller;6 ImportOrg.springframework.ui.Model;7 Importorg.springframework.web.bind.annotation.RequestMapping;8 ImportOrg.springframework.web.bind.annotation.ResponseBody;9 Ten @Controller One Public classMaincontroller { A @ResponseBody - /* - Watch out, it's here. That's what I wrote before. Remember to restart the server after you modify it. the @RequestMapping ("/login") - */ -@RequestMapping (value = "/login", produces = {"TEXT/HTML;CHARSET=UTF-8;"}) - PublicString Hello (model model) { +Jsonobject Jsonobject =NewJsonobject (); - Try { +Jsonobject.put ("msg", "Chinese garbled")); A}Catch(jsonexception e) { at e.printstacktrace (); - } - returnjsonobject.tostring (); - //return "Success"; - } -}View Code
Remember to restart the server after you modify it
Remember to restart the server after you modify it
Remember to restart the server after you modify it
The important thing to say three times, modify the place to add
produces = {"Text/html;charset=utf-8;"}
These words, but did not restart the server, engaged for four hours.
SPRINGMVC, through the Ajax way to submit page data, back in the background JSON data Chinese information garbled