jsp code:
<script>
//login
function submitForm(thisObj, thisEvent) {
var userName = $('#userName').val();
var pwd = $('#pwd').val();
var myData = {
"mydata": {"userName": userName, "pwd" : pwd}
};
$.ajax({
type: "POST",
url: "/login",
data: {
jsonData: JSON.stringify(myData)
},
dataType: "json"
});
return false;
}
</script>
<tr><td><input type="text" id="userName" name="userName" size="30" maxlength="30"></td></tr>
<tr><td><input type="password" id="pwd" name="pwd" size="30" maxlength="30"></td></tr>
<tr><td><button class="button" type="submit" value="Login" name="Submit" accesskey="s" onClick="return submitForm(this,event)">LOG IN</button></td></tr>
servlet:
public class login extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType("application/json");
PrintWriter out = res.getWriter();
StringBuffer sbuffer = new StringBuffer();
String inLine = null;
String sUsername = "";
try{
BufferedReader reader = req.getReader();
while ((inLine = reader.readLine()) != null)
sbuffer.append(inLine);
if (sbuffer.length() != 0){
JSONObject jsObj = new JSONObject(sbuffer.toString());
sUsername = jsObj.optString("userName");
sPwd = jsObj.optString("pwd");
}
}catch(Exception e){
out.println(retResponse("E","error"));
return;
}
sUsername = sUsername.trim();
sPwd = sPwd.trim();
}
}
web.xml:
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
我想使用json和servlet将我的登录/pwd传递到服务器端进行验证。我是json的新手。我参考了网上的例子并开发了上面的代码。但它不起作用。有人知道我的编码错了吗?我已经被login.class放在WEB-INFO文件夹下了。
我做错了什么。它的工作在我更改ajax库之后。从…起http://ajax.googl...到https://ajax.googl...