Java---Ajax在Struts2框架的应用实例

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

 

posted @ 2017-12-08 07:27  沉梦昂志~  阅读(459)  评论(0编辑  收藏  举报