struts2+ajax+json實(shí)現(xiàn)用戶登錄
來源:程序員人生 發(fā)布時間:2014-12-18 08:49:20 閱讀次數(shù):3434次
實(shí)現(xiàn)的是異步刷新登錄功能,返回出錯信息時不刷新頁面。
前端代碼:
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>struts2+ajax返回json類型數(shù)據(jù)</title>
<script type="text/javascript" src="js/
jquery.js"></script>
</head>
<body>
<h5>登錄</h5>
<br />
<form action="#" method="post">
<label for="username">用戶名:</label><input type="text" name="username" />
<label for="password">密碼:</label><input type="password" name="password" />
<input type="button" class="btn" value="登錄"/>
</form>
<br />
<h5>毛病信息</h5>
<br />
<ul>
<li><span id="error"></span></li>
</ul>
<script type="text/javascript">
/* 提交結(jié)果,履行ajax */
function btn(){
var $btn = $("input.btn");//獲得按鈕元素
//給按鈕綁定點(diǎn)擊事件
$btn.bind("click",function(){
$.ajax({
type:"post",
url:"login",//需要用來處理ajax要求的action name
data:{//設(shè)置數(shù)據(jù)源
username:$("input[name=username]").val(),
password:$("input[name=password]").val()//這里不要加"," 不然會報(bào)錯,而且根本不會提示毛病地方
},
dataType:"json",//設(shè)置需要返回的數(shù)據(jù)類型
success:function(data){
var d = eval("("+data+")");//將數(shù)據(jù)轉(zhuǎn)換成json類型,可以把data用alert()輸出出來看看究竟是甚么樣的結(jié)構(gòu)
//得到的d是1個形如{"key":"value","key1":"value1"}的數(shù)據(jù)類型,然后取值出來
if (d.success=="登錄成功!") {
window.location.href = "index.jsp";
} else {
$("#error").text(""+d.error+"");
}
},
error:function(){
alert("系統(tǒng)異常,請稍后重試!");
}//這里不要加","
});
});
}
/* 頁面加載完成,綁定事件 */
$(document).ready(function(){
btn();//點(diǎn)擊提交,履行ajax
});
</script>
</body>
</html>
struts.xml文件配置以下:
<action name="login" class="com.cn.useraction.LoginAction" method="login">
<!-- 返回json類型數(shù)據(jù) -->
<result name="success" type="json">
<param name="root">result<!-- result是action中設(shè)置的變量名,也是頁面需要返回的數(shù)據(jù),該變量必須有setter和getter方法 --></param>
</result>
<result name="UserNotExist" type="json">
<param name="root">result<!-- result是action中設(shè)置的變量名,也是頁面需要返回的數(shù)據(jù),該變量必須有setter和getter方法 --></param>
</result>
<result name="error" type="json">
<param name="root">result<!-- result是action中設(shè)置的變量名,也是頁面需要返回的數(shù)據(jù),該變量必須有setter和getter方法 --></param>
</result>
</action>
另外,需要在package標(biāo)簽中加入json信息:
<package name="useraction" extends="struts-default,json-default">
另外,導(dǎo)入用到的包:

注意,jsp中url填寫的是action的name,而利用action中返回的不同值來判斷在前端究竟要做甚么工作。
action代碼以下:
package com.cn.useraction;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import com.cn.util.DBConnection;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String result;
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
/**
* 用戶名與密碼匹配檢查
*
* @return 結(jié)果標(biāo)識 字符串 success 表示匹配成功 UserNotExist表示用戶不存在 error 表示匹配失敗
*/
private String userCheck() {
String name = null;
String pass = null;
Connection conn = DBConnection.getConn();
String sql = "select * from users where username='" + username + "'";
PreparedStatement pstmt;
try {
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
name = rs.getString("username");
pass = rs.getString("password");
ActionContext.getContext().getSession().put("userflag", rs.getString("flag"));
}
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (name == null)// 驗(yàn)證用戶名是不是存在
return "UserNotExist";
else if (name.equals(username) && pass.equals(password))// 驗(yàn)證登錄用戶名與密碼是不是匹配
return "success";
else
return "error";
}
/**
* 處理ajax要求
* @return SUCCESS
*/
public String login() throws Exception {
if (userCheck().equals("success")) {
ActionContext.getContext().getSession().put("username", username);
//將數(shù)據(jù)存儲在map里,再轉(zhuǎn)換成json類型數(shù)據(jù),也能夠自己手動構(gòu)造json類型數(shù)據(jù)
Map<String,Object> map = new HashMap<String,Object>();
map.put("success", "登錄成功!");
JSONObject json = JSONObject.fromObject(map);//將map對象轉(zhuǎn)換成json類型數(shù)據(jù)
result = json.toString();//給result賦值,傳遞給頁面
return "success";
} else if (userCheck().equals("UserNotExist")) {
//將數(shù)據(jù)存儲在map里,再轉(zhuǎn)換成json類型數(shù)據(jù),也能夠自己手動構(gòu)造json類型數(shù)據(jù)
Map<String,Object> map = new HashMap<String,Object>();
map.put("error", "登錄失敗:用戶名不存在或用戶名為空!");
JSONObject json = JSONObject.fromObject(map);//將map對象轉(zhuǎn)換成json類型數(shù)據(jù)
result = json.toString();//給result賦值,傳遞給頁面
return "UserNotExist";
} else {
//將數(shù)據(jù)存儲在map里,再轉(zhuǎn)換成json類型數(shù)據(jù),也能夠自己手動構(gòu)造json類型數(shù)據(jù)
Map<String,Object> map = new HashMap<String,Object>();
map.put("error", "登錄失敗:密碼毛病或未知的異常!");
JSONObject json = JSONObject.fromObject(map);//將map對象轉(zhuǎn)換成json類型數(shù)據(jù)
result = json.toString();//給result賦值,傳遞給頁面
return "error";
}
}
}
完成收工!
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈