There are many articles about STRUTS2 and JSON on the internet, Google Plus Baidu, consulted a lot, there are a variety of practices. Among them, most of the articles are said to add a call Jsonplugin plug-in, Google code can be downloaded. I have done tests before, but also with it, but really trouble, to let Struts2 package inherit a call "Json-default" Father package. Most of the articles on the web are about how the action of struts sends JSON data back to the browser (AJAX), and I want a process that is the opposite of them (that is, sending data from the Ajax side to the server-side action and parsing it), but I can't find the right answer. Groped for three nights, not fruit. Today, I finally found a way to train my mind.
Which, whether from the browser end (Js,ajax,jquery, etc.) to the server side, or from the server side (struts Action,servlet, etc.) to send back to the client, you need to identify a point: The sent should be a JSON-formatted string.
Next, we first rewrite the login module in the loginform.jsp file, the original code, please see the Struts 2.1.6 Series Tutorial (2): User Login module Implementation, now modify the code as follows:
<%@ page language= "java" contenttype= "text/html; charset=utf-8"
pageencoding= "UTF-8"%>
<%@ Taglib prefix= "s" uri= "/struts-tags"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd"
<meta http-equiv= "Content-type" content= "text/html; charset=utf-8"
<title > login page </title>
<script type= "Text/javascript" src= "Js/jquery-1.3.2.min.js" ></SCRIPT>
<script type= "Text/javascript"
$ (function () {
$ ("#submit"). Click (function () {
var loginName1 = $ ("input[name= ' LoginName ')"). Val (); Get account
var Password1 = $ ("input[name= ' password ']"). Val ();//Get password
var jsonuser = {Loginna Me:loginname1, password:password1}; JSON object
//Note: jsonuser.tostring () This method is wrong, the toString in JavaScript is used for Boolean variables, and the following methods are applied
Var s Truser = Json.stringify (jsonusER); Converts a JSON object into a JSON-formatted string,
$.post ("Login!valid.action", {Json:struser}, callback, "JSON");
});
Function Callback (JSON) {
alert (json.msg);//Display Feedback
if (json.suc = 1) {/ /If you return "login succeeded"
Window.location.href = "admin/index.action";//Jump to background home
}
}< br>
});
</script>
<body>
<form action= "login.action" method= "POST"
Account &L T;input type= "text" name= "LoginName"/><BR/>
password <input type= "password" name= "password" ><br/>
<input type= "button" id= "Submit" value= "Login"/>
</form>
</body>
The two key sentences are:
var jsonUser = {loginName:loginName1, password:password1}; (1)
var strUser = JSON.stringify(jsonUser); (2)