Ajax 是一種在無需重新載入整個網頁的情況下,能夠更新部分網頁的技術。 很久沒有動過ajax了,趁此機會複習一下,寫一個簡單的例子 一.項目結構: 二.需要的jar包 三.具體代碼: 1.web.xml 2.Action UserLoginAction.java AjaxAction.java 3 ...
Ajax 是一種在無需重新載入整個網頁的情況下,能夠更新部分網頁的技術。
很久沒有動過ajax了,趁此機會複習一下,寫一個簡單的例子
一.項目結構:
二.需要的jar包
三.具體代碼:
1.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts2</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
2.Action
UserLoginAction.java
package Action; import com.opensymphony.xwork2.ActionSupport;
/**
* @author user:liuadmin
* @version date:2017年12月8日 上午6:54:00
*
*/ public class UserLoginAction extends ActionSupport { private static final long serialVersionUID = 1L; 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; } /** * userlogin * * @return SUCCESS */ public String login() { System.out.println("execute!!!"); if ("admin".equals(this.username) && "123".equals(this.password)) return "success"; else if (password == null && username == null) return "error"; else return "error"; } }
AjaxAction.java
package Action; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONObject; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionSupport;
/**
* @author user:liuadmin
* @version date:2017年12月8日 上午6:56:00
*
*/ public class AjaxAction extends ActionSupport implements ServletRequestAware { private static final long serialVersionUID = 1L; private HttpServletRequest request; private String result; public void setServletRequest(HttpServletRequest arg0) { this.request = arg0; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } /** * 處理ajax請求 * * @return SUCCESS */ public String executeAjax() { try { // 獲取數據 String name = request.getParameter("name"); int age = Integer.parseInt(request.getParameter("age")); String position = request.getParameter("position"); // 將數據存儲在map里,再轉換成json類型數據,也可以自己手動構造json類型數據 Map<String, Object> map = new HashMap<String, Object>(); map.put("name", name); map.put("age", age); map.put("position", position); JSONObject json = JSONObject.fromObject(map);// 將map對象轉換成json類型數據 result = json.toString();// 給result賦值,傳遞給頁面 } catch (Exception e) { e.printStackTrace(); } return SUCCESS; } }
3.struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!--解決亂碼 --> <constant name="struts.i18n.encoding" value="UTF-8"></constant> <include file="struts-default.xml" /> <package name="struts" extends="struts-default,json-default"> <action name="login" class="Action.UserLoginAction" method="login"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> <action name="executeAjax" method="executeAjax" class="Action.AjaxAction"> <result name="fail"></result> <!-- 返回json類型數據 --> <result type="json"> <param name="root">result<!-- result是action中設置的變數名,也是頁面需要返回的數據,該變數必須有setter和getter方法 --></param> </result> </action> </package> </struts>
4.jsp
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Login</title> </head> <body> Please enter your account number and password <form id="from" action="login" method="post"> account number:<input type="text" name="username" id="username" /><br /> password:<input type="password" name="password" id="pass" /><br /> <input type="submit" value="login" /> </form> </body> </html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Ajax+Struts2 is Demo</title> </head> <body > ====>Login successfully!<br /> account number:${request.username}<br /> password:${request.password}<br> <div id="div_json"> <h5>錄入數據</h5> <br /> <form action="executeAjax" method="post"> <label for="name">姓名:</label><input type="text" name="name" /> <label for="age">年齡:</label><input type="text" name="age" /> <label for="position">職務:</label><input type="text" name="position" /> <input type="button" class="btn" value="提交結果"/> </form> <br /> <h5>顯示結果</h5> <br /> <ul> <li>姓名:<span id="s_name">贊無數據</span></li> <li class="li_layout">年齡:<span id="s_age">暫無數據</span></li> <li class="li_layout">職務:<span id="s_position">暫無數據</span></li> </ul> </div> <script type="text/javascript" src="js/jquery-1.8.2.js"></script> <script type="text/javascript"> /* 提交結果,執行ajax */ function btn(){ var $btn = $("input.btn");//獲取按鈕元素 //給按鈕綁定點擊事件 $btn.bind("click",function(){ $.ajax({ type:"post", url:"AjaxAction/executeAjax",//需要用來處理ajax請求的action,excuteAjax為處理的方法名,JsonAction為action名 data:{//設置數據源 name:$("input[name=name]").val(), age:$("input[name=age]").val(), position:$("input[name=position]").val()//這裡不要加"," 不然會報錯,而且根本不會提示錯誤地方 }, dataType:"json",//設置需要返回的數據類型 success:function(data){ var d = eval("("+data+")");//將數據轉換成json類型,可以把data用alert()輸出出來看看到底是什麼樣的結構 //得到的d是一個形如{"key":"value","key1":"value1"}的數據類型,然後取值出來 $("#s_name").text(""+d.name+""); $("#s_age").text(""+d.age+""); $("#s_position").text(""+d.position+""); }, error:function(){ alert("系統異常,請稍後重試!"); }//這裡不要加"," }); }); } /* 頁面載入完成,綁定事件 */ $(document).ready(function(){ btn();//點擊提交,執行ajax }); </script> </body> </html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>error</title> </head> <body> Login failed </body> </html>
代碼上重要的地方都會註釋,不明白的可以評論.
源碼下載: https://pan.baidu.com/s/1jIAarKM 密碼: exgk