首先加入
json需要的包: struts2的包不用说了当然得加入了
struts.xml配置信息
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true"/> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.ui.theme" value="simple" /> <!-- 这里继承的包是json,它里边继承了struts-default包所以就不用再继承了--> <package name="login" namespace="/" extends="json-default"> <global-allowed-methods>regex:.*</global-allowed-methods> <action name="logAction" class="com.test.action.LoginAction"> <!-- 因为用的是ajax所以成功的话我们在客户端判断跳转不跳转 --> <!-- <result name="success">/LoginSuccess.jsp</result> --> <result name="register">/Registeration.jsp</result> <!-- 这里的类型要写成json,因为是用json来传数据的不用刷新网页. --> <result type="json"> <param name="root">result</param> </result> </action> </package> </struts>
Action的主要代码
package com.test.action; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionSupport; import com.test.entity.User; import com.test.service.UserService; import net.sf.json.JSONObject; @SuppressWarnings("serial") public class LoginAction extends ActionSupport implements ServletRequestAware{ private UserService service; private HttpServletRequest request; private List<User> users; private String result; private Map<String,Object> map = new HashMap<String,Object>(); public String getResult() { return result; } public void setResult(String result) { this.result = result; } public UserService getService() { return service; } @Resource public void setService(UserService service) { this.service = service; } @Override public String execute() throws Exception { // TODO Auto-generated method stub String username = request.getParameter("name"); String password = request.getParameter("password"); map.put("msg", "账号不存在或密码错误!"); map.put("user", username); User user = service.QueryUser(username); if (user != null) { if (user.getPassword().equals(password)) { users = service.getAllUser(); map.put("msg", "success"); map.put("href", "Registeration.jsp"); } } JSONObject json = JSONObject.fromObject(map); result = json.toString(); return SUCCESS; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public String registeration() { String username = request.getParameter("name"); String password = request.getParameter("password"); if (service.exist(username)) { request.setAttribute("MSG", "账号已存在!"); return ERROR; } User user = new User(); user.setName(username); user.setPassword(password); service.add(user); return SUCCESS; } public String register() { return "register"; } @Override public void setServletRequest(HttpServletRequest request) { // TODO Auto-generated method stub this.request = request; } public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } }
这里用String格式化来传数据,其实也可以直接用Map来传,再配置文件里把result改成Action里的map变量就行.
jsp网页里的代码
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <%@ taglib prefix="s" uri="/struts-tags" %> <%@ taglib prefix="sx" uri="/struts-dojo-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 5 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"> --> <link rel="stylesheet" href="jquery1.12/jquery-ui.css"> <script src="jquery1.12/external/jquery/jquery.js"></script> <script src="jquery1.12/jquery-ui.js"></script> <sx:head/> <style type="text/css"> div,body,td,span { font-size: 12px; } form { padding: 0px; margin: 0px; } .div { padding: 10px; width: 300px; background-color: #E5E5E5; } #errorDiv { color: red; text-align: center; font-weight: bold; } </style> </head> <body> <div class="div"> <div id="errorDiv" class="errorDiv"></div> <form> 用户名: <input style="width: 148px; height: 24px; " id="name" type="text"> <br> 密 码: <input style="width: 148px; height: 24px; " id="password" type="password"><br> <input type="button" id="loginBtn" value="登陆" style="width: 92px; height: 30px; "> <input type="button" value="注册" style="width: 92px; height: 30px; " onclick="window.location.href='Registeration.jsp'"> </form> </div> <script> // 加上$()这个符号是打开网页就直接运行 $( "input[type=submit], input[type=button]" ).button(); function bindBtl() { $("#loginBtn").bind("click", function(){ // ajax的核心代码 $.ajax({ type : "post", url : "logAction", data : { name : $("#name").val(), password : $("#password").val() }, dataType : "json", success : function(data){ var d = eval("("+data+")"); if (d.msg == "success") { window.location.href = 'LoginSuccess.jsp'; }else{ $("#name").val(""+d.user+""); $("#password").val(""); document.getElementById('errorDiv').innerHTML = d.msg; } }, error : function(e){ alert(e.responseText); } }) }) } // 这里手动运行一下上边的函数给按钮绑定事件 $(document).ready(function() { bindBtl(); }); </script> </body> </html>效果图