您的位置:首页 > 其它

Ajax实现无刷新登陆

2015-04-16 15:32 190 查看
一个页面很多内容,而在登陆成功后不想整个页面都刷新一次,整个效率低,每次都要加载页面,所以需要实现无刷新登陆

只是简单地做了个一个demo,望各位大侠轻喷

jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#testBut").click(function()
{
$.ajax(
{
url:"login!loginTest.action",     //动态方法的调用
type:"POST",
dataType: "json",
data:$("#form2").serialize(),    //通过serialize()获得表单数据的值
success:function(date)
{
if(date["ok"])
{
$("#formtest").html("欢迎"+date["username"]+"登陆");
}
else
{
$("#info").html("登陆失败!");
}
},
error:function()
{
$("#info").html("登陆失败!!!!!");
},
async:false,  //<span style="color: rgb(54, 46, 43); font-family: Arial; font-size: 14px; line-height: 26px;">false为同步,ajax将浏览器锁死</span>
});
});
});
</script>
</head>

<body>

<div id="formtest" style="display: block;">
<div id="info"></div>
<form action="login!loginTest.action" method="post" id="form2">
用户名:<input type="text" name="user.username"><br/>
密码:<input type="password" name="user.password"><br/>
<input type="button" value="登陆" id="testBut">
</form>
</div>

</body>
</html>


stuts.xml文件中要支持返回的是json的数据package要继承json-default

内容如下所示:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<!-- 动态方法调用 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
<pre name="code" class="html"><span style="white-space:pre">	</span><!-- 继承<span style="font-family: Arial, Helvetica, sans-serif;">json-default</span><span style="font-family: Arial, Helvetica, sans-serif;"> --></span>



<span style="white-space:pre">	</span><package name="my" extends="json-default" namespace="/">
<action name="login" class="com.itany.action.UserAction">
<result type="json">
<span style="color: rgb(0, 130, 0); font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', Consolas, 'Courier New', monospace; line-height: 18px; background-color: rgb(250, 250, 250);"><span style="white-space:pre">			</span>     <!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 --></span>
<span style="white-space:pre">				</span><!-- root表示返回的根,action里有map这个属性,此时返回也没有页面 -->
<param name="root">map</param>
</result>
</action>
</package>
</struts>


action类:

public class UserAction extends ActionSupport
{
private String msg;

private Map<Object, Object> map =new HashMap<Object, Object>();

public Map<Object, Object> getMap()
{
return map;
}

public void setMap(Map<Object, Object> map)
{
this.map = map;
}

public User user;

public User getUser()
{
return user;
}

public void setUser(User user)
{
this.user = user;
}

 /**
<span style="white-space:pre">	</span> * 动态方法调用
<span style="white-space:pre">	</span> * 由于只是个demo,就没分dao service层了,全在action做了
<span style="white-space:pre">	</span> * <功能详细描述>
<span style="white-space:pre">	</span> * @return
<span style="white-space:pre">	</span> * @throws Exception
<span style="white-space:pre">	</span> * @see [类、类#方法、类#成员]
<span style="white-space:pre">	</span> */
public String loginTest()
{
map.clear(); //map中的数据将会被Struts2转换成JSON字符串,所以这里要先清空其中的数据  
System.out.println(user.getUsername());
System.out.println(user.getPassword());

HttpServletRequest request=ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse();

JDBCUtil util = new JDBCUtil();
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
String sql="select * from user where username=? and password=?";
List<User> users=new ArrayList<User>();
try
{
conn=util.getCon();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
rs = pstmt.executeQuery();
while (rs.next())
{
User user=new User();
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
map.put("ok", true);  <span class="comment" style="color: rgb(0, 130, 0); padding: 0px; margin: 0px; width: auto; border: 0px; font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', Consolas, 'Courier New', monospace; line-height: 18px; background-color: rgb(250, 250, 250);">// 放入一个是否操作成功的标识</span><span style="font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', Consolas, 'Courier New', monospace; line-height: 18px; background-color: rgb(250, 250, 250);">  </span>
map.put("username", user.getUsername());

return SUCCESS;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: