日期:2014-05-16  浏览次数:20743 次

Struts 2 with Ajax
  Struts and Struts2 compared to a major improvement is support for Ajax. In this paper, look at the Div in Struts2 is how Ajax used to output the results, the main use of the Dojo.

First of all, we first create a simple use case, in this use case will be displayed on the screen of a user list, click on the userid list, the list below will show the user detailed information, showing detailed information of the user steps we will the use of Ajax.

First, create a web.xml

<? xml version = "1.0" encoding = "UTF-8"?>

<web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi : schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name> struts2 </ filter-name>
<filter-class> org.apache.struts2.dispatcher.FilterDispatcher </ filter-class>
</ filter>
<filter-mapping>
<filter-name> struts2 </ filter-name>
<url-pattern> / * </ url-pattern>
</ filter-mapping>
</ web-app>

Second, create struts.xml
<! DOCTYPE struts PUBLIC
"- / / Apache Software Foundation / / DTD Struts Configuration 2.0 / / EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="ajaxdemo" extends="struts-default">
<action name="UserListingAction">
<result> / userlisting.jsp </ result>
</ action>
<action name="UserDetailAction">
<result> / userdetail.jsp </ result>
</ action>
</ package>
</ struts>

III, page: userlisting.jsp
Displays list of users
<% @ Taglib prefix = "s" uri = "/ struts-tags"%>
<html>
<head>
<s:head theme="ajax"/>

</ head>
<script>
function show_user_details (id) (
document.frm_user.userid.value = id;
dojo.event.topic.publish ( "show_detail");
)
</ script>
<body>
<s:form name="frm_user">
<h1> User Listing </ h1>
<s:if test="userList.size> 0 ">
<table border="1">
<s:iterator value="userList">
<tr>
<td>
<s:a href="#" onclick="javascript:show_user_details('%{id}');return false;"> <s:property value="id" /> </ s: a>
</ td>
<td>
<s:property value="name" />
</ td>
</ tr>
</ s: iterator>
</ table>
</ s: if>
<s:hidden name="userid"/>
<s:url action="UserDetailAction" />
<s:div href="%{d_url}" theme="ajax" listenTopics="show_detail" formId="frm_user">
</ s: div>
</ s: form>
</ body>
</ html>

IV, page: userdetail.jsp, used to display user details from userlisting.jsp load
<% @ Taglib prefix = "s" uri = "/ struts-tags"%>
<h1> User Details </ h1>
<s:if test="userDetails != null">
<table>
<tr> <td> Id: </ td> <td> <s:property value="userDetails.id" /> </ td> </ tr>
<tr> <td> Name: </ td> <td> <s:property value="userDetails.name" /> </ td> </ tr>
<tr> <td> Email: </ td> <td> <s:property value="userDetails.email" /> </ td> </ tr>
<tr> <td> Address: </ td> <td> <s:property value="userDetails.address" /> </ td> </ tr>
</ table>
</ s: if>

5, ajaxdemo.action.UserListingAction.java, to generate a list of data users