暑期项目经验(五)--struts+ajax

              struts+ajax

一、ajax知识点

二、struts+ajax

a.  index.jsp

<%@ 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>StrutsAjaxJson Demo</title>
    <script type="text/javascript" src="js/jquery-1.4.3.js"></script>
    <script type="text/javascript">
        function loadInfo1(){
            $.ajax({
                url:'returnMsg.action',
                type:'post',
                dataType:'json',
                success:function (msg){
                    $("#info1").html("发送成功:" + msg);
                },
                error: function (xhr){
                    $("#info1").html("抱歉!发送失败!错误:" + xhr.responseText);
                }
            });
        }
        
        function loadInfo2(){
            $.ajax({
                url:'returnUser.action',
                type:'post',
                dataType:'text',
                success:function (msg){
                    $("#info2").html("发送成功:" + msg);
                },
                error: function (xhr){
                    $("#info2").html("抱歉!发送失败!错误:" + xhr.responseText);
                }
            });
        }
        
        function loadInfo4(){
             $.ajax({
            url: 'sendMessage.action',
            data: "teacherName="+obj1+"&theme="+obj2+"&content="+obj3,
            contentType: 'application/json; charset=utf-8',
            type: 'get',
            dataType: 'text/html',
            success: function (data) {
                if (data) {
                    document.getElementById("span_msg_tips").innerHTML = "<div class='center' style='padding:30px;'><span class='red'>您的短消息已发送成功!</span> <a href='/msg/inbox'>返回收信箱</a></div>";
                } else {
                    $("#span_msg_tips").html("抱歉!发送失败!错误:");
                }
            },
            error: function (xhr) {
                $("#span_msg_tips").html("抱歉!发送失败!错误:" + xhr.responseText);
            }
        });
        }
        
        
        function loadInfo3(){
            $.ajax({
                url:'returnList.action',
                type:'post',
                dataType:'text',
                success:function (msg){
                    $("#info3").html("发送成功:" + msg);
                },
                error: function (xhr){
                    $("#info3").html("抱歉!发送失败!错误:" + xhr.responseText);
                }
            });
        }
        
        function SendMessage() {
        var title = document.getElementById("txtTitle").value;
        var content = document.getElementById("txtContent").value;
        var incept = document.getElementById("txtIncept").value;

        if (incept == "") {
            alert("收件人是必填的");
            $("#txtIncept").focus();
            return;
        }

        if (title == "") {
            alert("主题是必填的");
            $("#txtTitle").focus();
            return;
        }
        if (content == "") {
            alert("内容是必填的");
            $("#txtContent").focus();
            return;
        }
        $("#span_msg_tips").html("正在发送...");
        var obj1 = $("#txtIncept").val();
        var obj2 = $("#txtTitle").val();
        var obj3 = $("#txtContent").val();
        alert(obj1+":"+obj2+":"+obj3);
        $.post(
            "sendMessage.action",
            {"teacherName":obj1,"theme":obj2,"content":obj3},
            function(data){
                 if (data) {
                    document.getElementById("span_msg_tips").innerHTML = "<div class='center' style='padding:30px;'><span class='red'>您的短消息已发送成功!</span> <a href='/msg/inbox'>返回收信箱</a></div>";
                } else {
                    $("#span_msg_tips").html("抱歉!发送失败!错误:");
                }
            });
       
    }
    </script>
  </head>
  
  <body>
    <input type="button" value="获取后台返回单个json值" id="btnGet" onclick="loadInfo1()" />
    <div id="info1"></div>
     <input type="button" value="获取后台返回json对象" id="btnGet" onclick="loadInfo2()" />
    <div id="info2"></div>
     <input type="button" value="获取后台返回json List对象" id="btnGet" onclick="loadInfo3()" />
    <div id="info3"></div>
    
    <table width="100%" border="0" >
            <tr>
                <td align="right" valign="top" class="stitle_green" width="60px">收件人: </td>
                <td valign="top"><input name="teacherName" type="text" maxlength="90" id="txtIncept" class="text_fixedsys" style="300px" /></td>
            </tr>
            <tr>
                <td align="right" valign="top" class="stitle_green">主题: </td>
                <td valign="top"><input name="theme" type="text" id="txtTitle" class="text_fixedsys" style="300px" /></td>
            </tr>
            <tr>
                <td align="right" valign="top" class="stitle_green">内容: </td>
                <td>
                     <div style="text-align:right;padding-right:60px;">
                        <span id="span_msg_tips" style="color:red"></span>
                    </div>
                    <textarea name="content" rows="2" cols="20" id="txtContent" class="text_fixedsys" style="90%;height:200px"></textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center" height="50">
                    <input type="button" value=" 发 送 " id="btnSend" onclick="SendMessage()">
                </td>
            </tr>
    </table>
  </body>
</html>

b.userInfo.java

package com.pxj.entity;

public class UserInfo {
    private int userId;
    private String userName;
    private String pwd;
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    
}

c.TestAction.java

package com.pxj.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.Action;
import com.pxj.entity.UserInfo;

@SuppressWarnings("unchecked")
public class TestAction {
    private String msg;            //使用json返回单个值
    private UserInfo userInfo;  //使用json返回对象
    private List userInfoList;  //使用json返回List对象
    private String teacherName,theme,content;
    
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public UserInfo getUserInfo() {
        return userInfo;
    }
    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }
    public List getUserInfoList() {
        return userInfoList;
    }
    public void setUserInfoList(List userInfoList) {
        this.userInfoList = userInfoList;
    }
    public String getTeacherName() {
        return teacherName;
    }
    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }
    public String getTheme() {
        return theme;
    }
    public void setTheme(String theme) {
        this.theme = theme;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String returnMsg(){
        this.msg="成功返回单个值";
        return Action.SUCCESS;
    }
    public String returnUser(){
        userInfo = new UserInfo();
        userInfo.setUserId(1001);
        userInfo.setUserName("刘栋");
        userInfo.setPwd("123");
        return Action.SUCCESS;
    }
    public String returnList(){
        userInfoList = new ArrayList<UserInfo>();
        UserInfo u1 = new UserInfo();
        u1.setUserId(2001);
        u1.setUserName("张三");
        u1.setPwd("123");
        UserInfo u2 = new UserInfo();
        u2.setUserId(2002);
        u2.setUserName("李四");
        u2.setPwd("456");
        userInfoList.add(u1);
        userInfoList.add(u2);
        return Action.SUCCESS;
    }
    
    public String sendMessage(){
        System.out.println("teacherName--theme--content:"+teacherName+":"+theme+":"+content);
        return Action.SUCCESS;
    }
}

d.struts.xml

<?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>
    <package name="default" namespace="/" extends="json-default">
    
        <action name="returnMsg" class="com.pxj.action.TestAction" method="returnMsg">
            <result name="success" type="json">
                <param name="root">msg</param>
            </result>
        </action>
        
        <action name="returnUser" class="com.pxj.action.TestAction" method="returnUser">
            <result name="success" type="json">
                <param name="includeProperties">userInfo.userId,userInfo.userName,userInfo.pwd</param>
                <!--输出UserInfo的所有属性 
                <param name="includeProperties">userInfo.*</param>
                 -->
            </result>
        </action>
        
        <action name="returnList" class="com.pxj.action.TestAction" method="returnList">
            <result name="success" type="json">
                <param name="includeProperties">userInfoList[d+].userName,userInfoList[d+].pwd</param>
            </result>
        </action>
        
        <action name="sendMessage" class="com.pxj.action.TestAction" method="sendMessage">
            <result name="success" type="json"></result>
        </action>
    </package>
</struts>
原文地址:https://www.cnblogs.com/pxjgood/p/3991354.html