Strut2 Ajax JSON Demo

來源:互聯網
上載者:User

標籤:

一、背景

由於項目的需要重拾Struts,做的時候發現好多東西都忘了,寫一個小小的demo,就花了大半天,還好最後終於調通了。

情境描述:前段頁面輸入使用者名稱,後端將使用者名稱和其他資訊通過Ajax以Json的格式回傳回來

使用工具:IDE:Myeclipse2014,伺服器:Apache-tomcat-7.0.57,Struts-2.3.20及其lib,jQuery:jquery-1.11.2.min.js

需要引入的Struts包:兩者需要的包有共同的地方,注意不要重複引入

  Struts所需的包:

    commons-fileupload-x.y.z.jar

    commons-io-x.y.z.jar

    commons-lang.x.y.jar

    commons-lang3.y.jar

    commons-logging-x.y.z.jar

    commons-logging-api-x.y.jar

    freemarker-x.y.z.jar

    javassist-.xy.z.GA

    ognl.jar

    struts2-core.jar

    xwork-core.jar

  JSON需要的包:

    commons-collections.jar

    commons-lang.jar

    commons-beanutils.jar

    commons-logging.jar

    ezmorph.jar

    json-lib.jar

    struts-json-plugin.jar

二、頁面代碼:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%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>Welcome Login</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="./javascript/jquery-1.11.2.min.js"></script>
<!--此處引用jQuery-->

<!-- 此段為Ajax與後端互動部分--> <script type="text/javascript"> $(document).ready(function(){ $("#usrname").change(function(){ $("logtip").empty(); $.ajax({ url : "login", // 幕後處理程式,對應Action type : "post", // 資料發送方式 dataType : "json", // 接受資料格式 data:{ usrname : $("#usrname").val() }, // 要傳遞的資料 // 回傳函數 timeout:20000, // 佈建要求逾時時間(毫秒)。 error: function () { //請求失敗時調用函數。 $("#logtip").html("請求失敗!"); }, success:function(dataObj){ //請求成功後回呼函數。 //alert(dataObj); str = jQuery.parseJSON(dataObj); $("#echoname").html(str.usrname); $("#echowd").html(str.passwd); } }); }); }); </script> </head> <body> <div> 歡迎進入Struts2.3的世界 </div> <div> <div> <span>帳號:</span> <span><input type="text" name="usrname" id="usrname"/></span> <span id="logtip"></span> </div> <div> <span>帳號:</span> <span id="echoname"></span> <span>密碼: </span> <span id="echowd"></span> </div> </div> </body></html>

 

三、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.enable.DynamicMethodInvocation" value="false" />    <constant name="struts.devMode" value="true" />    <package name="Check" namespace="/" extends="json-default">        <action name="login" class="demo.ajax.login.LoginAction" method="execute">            <result type="json">                <param name="root">result</param>            </result>        </action>    </package>    <!-- Add packages here --></struts>

1、result中type設定成json之後,容器會把action的屬性自動封裝到一個json對象中(json攔截器來做),然後調用ajax的callback方法. 返回json資料。

  我的做法是將map轉換成了json格式的字串,使用 root 參數返回的格式為  {"passwd":"success", "usrname":"love"},可以使用 jQuery.parseJSON 解析

2、根對象在JSON中資料添加一個”root”標識。如果要使用它,Action必須遵循以下幾點:

   1)返回的頁面類型中”content-type”必須是”application/json”;

   2)JSON內容必須是符合格式要求的;

   3)Action中field必須有public的set方法(是不是沒有set方法就不會將field添加到JSON資料中,有待驗證);

   4)它支援的類型有: 基本類型(int,long...String), Date, List, Map, Primitive Arrays, 其它class, 對象數組;

   5)在JSON中任何的Object會被封裝在list或map中,資料會被封裝程Long,如果是含有的資料則會被封裝程Double,數組會被封裝程List。

3、除了root參數,另外還有includeProperties 參數,excludeProperties 參數,具體情況請查看參考文章中的 《struts2學習——struts2與json》

 

四、java代碼
package demo.ajax.login;import java.util.HashMap;import java.util.Map;import net.sf.json.JSONObject;public class LoginAction {    private String usrname;    private String result;            public String execute(){        String passwd="success";        Map map = new HashMap();        map.put("usrname", usrname);        map.put("passwd", passwd);                System.out.println(usrname);        
     /*此處將map轉換為json格式的String類型*/ JSONObject jsonObj
= JSONObject.fromObject(map); result = jsonObj.toString(); return "success"; } public String getUsrname() { return usrname; } public void setUsrname(String usrname) { this.usrname = usrname; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }

 

四、遇到的問題與總結

 

五、參考文章

struts2學習——struts2與json   http://huing.blog.51cto.com/1669631/1286327

Strut2 Ajax JSON Demo

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.