原文:Mkyong
struts 2 action error & action message 示例
Download It – Struts2-ActionError-ActionMessage-Example.zip
展示 Struts 2 的 ActionError 和 ActionMessage 类用法的教程。
1.action error–用于向用户发送错误反馈信息–通过 < s:actionerror/ > 显示。
<s:if test="hasActionErrors()">
<div class="errors">
<s:actionerror/>
</div>
</s:if>
2.action message——用于向用户发送信息反馈消息,通过 <显示 s:actionmessage/ > 。
<s:if test="hasActionMessages()">
<div class="welcome">
<s:actionmessage/>
</div>
</s:if>
这是一个简单的登录表单,如果用户名不等于“mkyong ”,则显示错误消息(actionerror ),否则重定向到另一个页面并显示欢迎消息(actionmessage)。此外,所有标签和错误消息都是从资源包(属性文件)中检索的。
1.文件夹结构
查看此项目结构
## 2.属性文件
存储消息的两个属性文件。
登录操作.属性
#Welcome messages
welcome.hello = Hello
#error message
username.required = Username is required
password.required = Password is required
global.properties
#Global messages
global.username = Username
global.password = Password
global.submit = Submit
global.reset = Reset
3.行动
一个经典的 action 类,做一个简单的检查确保用户名等于“mkyong”,用 addActionError() 设置错误消息或者用 addActionMessage() 设置成功消息。
package com.mkyong.user.action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private String username;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
//business logic
public String execute() {
return "SUCCESS";
}
//simple validation
public void validate(){
if("mkyong".equals(getUsername())){
addActionMessage("You are valid user!");
}else{
addActionError("I don't know you, dont try to hack me!");
}
}
}
4.JSP 视图
两个简单的 css 样式的 JSP 页面来定制错误消息。
login.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<style type="text/css">
.errors {
background-color:#FFCCCC;
border:1px solid #CC0000;
width:400px;
margin-bottom:8px;
}
.errors li{
list-style: none;
}
</style>
</head>
<body>
<h1>Struts 2 ActionError & ActionMessage Example</h1>
<s:if test="hasActionErrors()">
<div class="errors">
<s:actionerror/>
</div>
</s:if>
<s:form action="validateUser">
<s:textfield key="global.username" name="username"/>
<s:password key="global.password" name="password"/>
<s:submit key="global.submit" name="submit"/>
</s:form>
</body>
</html>
welcome.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<style type="text/css">
.welcome {
background-color:#DDFFDD;
border:1px solid #009900;
width:200px;
}
.welcome li{
list-style: none;
}
</style>
</head>
<body>
<h1>Struts 2 Struts 2 ActionError & ActionMessage Example</h1>
<s:if test="hasActionMessages()">
<div class="welcome">
<s:actionmessage/>
</div>
</s:if>
<h2>
<s:property value="getText('welcome.hello')" /> :
<s:property value="username"/>
</h2>
</body>
</html>
5.struts.xml
把所有的联系在一起。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="global" />
<package name="user" namespace="/user" extends="struts-default">
<action name="login">
<result>pages/login.jsp</result>
</action>
<action name="validateUser" class="com.mkyong.user.action.LoginAction">
<result name="SUCCESS">pages/welcome.jsp</result>
<result name="input">pages/login.jsp</result>
</action>
</package>
</struts>
In Struts 2, the functionality and usage of ActionError & ActionMessage are quite similar with Struts 1.
6.运行它
http://localhost:8080/struts 2 example/user/log in . action
用户名无效,显示带有的错误信息
用户名有效,显示欢迎消息
参考
Struts 2 和 JSON 示例
原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-and-json-example/
在 Struts 2 示例中,您将学习如何通过“struts2-json-plugin.jar
”库将对象转换成 JSON 格式。
1.获取依赖库
获取 struts2-json-plugin.jar 库。
POM . XML
<!-- Struts 2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.1.8</version>
</dependency>
<!-- Struts 2 JSON Plugins -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.1.8</version>
</dependency>
2.行动(JSON)
这是一个将被转换成 JSON 格式的动作类。
package com.mkyong.common.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.opensymphony.xwork2.Action;
public class JSONDataAction{
private String string1 = "A";
private String[] stringarray1 = {
"A1","B1"};
private int number1 = 123456789;
private int[] numberarray1 = {
1,2,3,4,5,6,7,8,9};
private List<String> lists = new ArrayList<String>();
private Map<String, String> maps = new HashMap<String, String>();
//no getter method, will not include in the JSON
private String string2 = "B";
public JSONDataAction(){
lists.add("list1");
lists.add("list2");
lists.add("list3");
lists.add("list4");
lists.add("list5");
maps.put("key1", "value1");
maps.put("key2", "value2");
maps.put("key3", "value3");
maps.put("key4", "value4");
maps.put("key5", "value5");
}
public String execute() {
return Action.SUCCESS;
}
public String getString1() {
return string1;
}
public void setString1(String string1) {
this.string1 = string1;
}
public String[] getStringarray1() {
return stringarray1;
}
public void setStringarray1(String[] stringarray1) {
this.stringarray1 = stringarray1;
}
public int getNumber1() {
return number1;
}
public void setNumber1(int number1) {
this.number1 = number1;
}
public int[] getNumberarray1() {
return numberarray1;
}
public void setNumberarray1(int[] numberarray1) {
this.numberarray1 = numberarray1;
}
public List<String> getLists() {
return lists;
}
public void setLists(List<String> lists) {
this.lists = lists;
}
public Map<String, String> getMaps() {
return maps;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
}
3.struts.xml
要输出 JSON 数据,需要声明一个扩展了“ json-default ”的包,结果类型为“ json ”。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="json-default">
<action name="getJSONResult"
class="com.mkyong.common.action.JSONDataAction">
<result type="json" />
</action>
</package>
</struts>
4.演示
访问动作 URL, JSONDataAction 的属性将被转换成 JSON 格式。
http://localhost:8080/struts 2 example/getjsonresult . action
JSON 格式…
{
"lists":["list1","list2","list3","list4","list5"],
"maps":
{
"key4":"value4","key3":"value3","key5":"value5","key2":"value2","key1":"value1"
},
"number1":123456789,
"numberarray1":[1,2,3,4,5,6,7,8,9],
"string1":"A",
"stringarray1":["A1","B1"]
}
Hope this super simple example can give you an overall idea of how JSON plugin worked with Struts 2. However, there are still many useful settings are not cover here, make sure you read the Struts 2 JSON plugin documentation for more details.
下载源代码
Download It – Struts2-JSON-Example.zip
参考
Struts 2 附加标签示例
原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-append-tag-example/
Download It – Struts2-Append-Tag-Example.zip
Struts 2 append 标签用于将几个迭代器(由 List 或 Map 创建)组合成一个迭代器。在本教程中,您将使用 Struts 2 append 标签来完成以下任务:
- 将三个数组列表组合成一个迭代器。
- 将三个散列表组合成一个迭代器。
- 将 ArrayList 和 HashMap 组合成一个迭代器。
Assume 2 iterators, each has two entries, after combine with append tag into a single iterator, the order of the entries will look like following :
- 第一个迭代器的第一个条目。
- 第一个迭代器的第二个条目。
- 第二个迭代器的第一个条目。
- 第二个迭代器的第二个条目。
这只适用于列表迭代器;地图迭代器,顺序会随机。
1.行动
一个具有 3 个 ArrayList 和 3 个 HashMap 属性的 Action 类。
追加动作
package com.mkyong.common.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;
public class AppendTagAction extends ActionSupport{
private List<String> list1 = new ArrayList<String>();
private List<String> list2 = new ArrayList<String>();
private List<String> list3 = new ArrayList<String>();
private Map<String,String> map1 = new HashMap<String,String>();
private Map<String,String> map2 = new HashMap<String,String>();
private Map<String,String> map3 = new HashMap<String,String>();
public String execute() {
list1.add("List1 - 1");
list1.add("List1 - 2");
list1.add("List1 - 3");
list2.add("List2 - 1");
list2.add("List2 - 2");
list2.add("List2 - 3");
list3.add("List3 - 1");
list3.add("List3 - 2");
list3.add("List3 - 3");
map1.put("map1-key1", "map1-value1");
map1.put("map1-key2", "map1-value2");
map1.put("map1-key3", "map1-value3");
map2.put("map2-key1", "map2-value1");
map2.put("map2-key2", "map2-value2");
map2.put("map2-key3", "map2-value3");
map3.put("map3-key1", "map3-value1");
map3.put("map3-key2", "map3-value2");
map3.put("map3-key3", "map3-value3");
return SUCCESS;
}
//getter methods...
}
2.附加标签示例
一个 JSP 页面,展示了如何使用 append 标记将 3 ArrayList/3 HashMap/1 ArrayList+1 HashMap 组合成一个迭代器,并循环遍历其值并打印出来。
appendIterator.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body>
<h1>Struts 2 Append tag example</h1>
1\. Combine 3 ArrayList into a single iterator.
<s:append var="customListIterator">
<s:param value="%{list1}" />
<s:param value="%{list2}" />
<s:param value="%{list3}" />
</s:append>
<ol>
<s:iterator value="%{#customListIterator}">
<li><s:property /></li>
</s:iterator>
</ol>
2\. Combine 3 HashMap into a single iterator.
<s:append var="customMapIterator">
<s:param value="%{map1}" />
<s:param value="%{map2}" />
<s:param value="%{map3}" />
</s:append>
<ol>
<s:iterator value="%{#customMapIterator}">
<li><s:property /></li>
</s:iterator>
</ol>
3\. Combine ArrayList and HashMap into a single iterator.
<s:append var="customMixedIterator">
<s:param value="%{list1}" />
<s:param value="%{map1}" />
</s:append>
<ol>
<s:iterator value="%{#customMixedIterator}">
<li><s:property /></li>
</s:iterator>
</ol>
</body>
</html>
3.struts.xml
链接一下~
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="appendTagAction"
class="com.mkyong.common.action.AppendTagAction" >
<result name="success">pages/appendIterator.jsp</result>
</action>
</package>
</struts>
4.演示
http://localhost:8080/struts 2 example/appendtagaction . action
输出
Struts 2 Append tag example
1\. Combine 3 ArrayList into a single iterator.
1\. List1 - 1
2\. List1 - 2
3\. List1 - 3
4\. List2 - 1
5\. List2 - 2
6\. List2 - 3
7\. List3 - 1
8\. List3 - 2
9\. List3 - 3
2\. Combine 3 HashMap into a single iterator.
1\. map1-key3=map1-value3
2\. map1-key1=map1-value1
3\. map1-key2=map1-value2
4\. map2-key2=map2-value2
5\. map2-key3=map2-value3
6\. map2-key1=map2-value1
7\. map3-key3=map3-value3
8\. map3-key1=map3-value1
9\. map3-key2=map3-value2
3\. Combine ArrayList and HashMap into a single iterator.
1\. List1 - 1
2\. List1 - 2
3\. List1 - 3
4\. map1-key3=map1-value3
5\. map1-key1=map1-value1
6\. map1-key2=map1-value2
参考
Struts 2 自动完成器示例
Download It – Struts2-AutoCompleter-Example.zip
在 Struts 2 中, < sx:autocompleter > 标签是一个组合框,当用户在文本框中输入时,它会自动提示下拉建议列表。
This feature is implemented by dojo library, So, make sure you include “struts2-dojo-plugin.jar” as dependency library, put “struts-dojo-tags” tag on top of the page and output its header information via <sx:head />.
举个例子,
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>
<body>
<sx:autocompleter label="What's your lucky number?"
name="yourLuckyNumber" autoComplete="false"
list="{'1','12','13','14'}" />
产生以下 HTML
<html>
<head>
<script language="JavaScript" type="text/javascript">
// Dojo configuration
djConfig = {
isDebug: false,
bindEncoding: "UTF-8"
,baseRelativePath: "/Struts2Example/struts/dojo/"
,baseScriptUri: "/Struts2Example/struts/dojo/"
,parseWidgets : false
};
</script>
<script language="JavaScript" type="text/javascript"
src="/Struts2Example/struts/dojo/struts_dojo.js"></script>
<script language="JavaScript" type="text/javascript"
src="/Struts2Example/struts/ajax/dojoRequire.js"></script>
<link rel="stylesheet" href="/Struts2Example/struts/xhtml/styles.css"
type="text/css"/>
<script language="JavaScript" src="/Struts2Example/struts/utils.js"
type="text/javascript"></script>
<script language="JavaScript" src="/Struts2Example/struts/xhtml/validation.js"
type="text/javascript"></script>
<script language="JavaScript" src="/Struts2Example/struts/css_xhtml/validation.js"
type="text/javascript"></script>
</head>
...
<tr>
<td class="tdLabel">
<label for="resultAction_yourLuckyNumber" class="label">
What's your lucky number?:</label></td>
<td>
<select dojoType="struts:ComboBox" id="resultAction_yourLuckyNumber"
autoComplete="false" name="yourLuckyNumber"
keyName="yourLuckyNumberKey" visibleDownArrow="true" >
<option value="1">1</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</td>
</tr>
<script language="JavaScript" type="text/javascript">
djConfig.searchIds.push("resultAction_yourLuckyNumber");</script>
Struts 2 示例
一个完整的 < s:autocompleter > 标签的例子,当用户在相应的文本框中输入时,生成下拉建议列表。
1.pom.xml
下载 Struts 2 dojo 依赖库。
pom.xml
//...
<!-- Struts 2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.1.8</version>
</dependency>
<!-- Struts 2 Dojo Ajax Tags -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-dojo-plugin</artifactId>
<version>2.1.8</version>
</dependency>
//...
2.动作类
Action 类来为" autocompleter "组件生成 web 框架选项列表。
AutoCompleterAction.java
package com.mkyong.common.action;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class AutoCompleterAction extends ActionSupport{
private List<String> webframeworks = new ArrayList<String>();
private String yourFavWebFramework;
private String yourLuckyNumber;
public AutoCompleterAction(){
webframeworks.add("Spring MVC");
webframeworks.add("Struts 1.x");
webframeworks.add("Struts 2.x");
webframeworks.add("JavaServer Faces (JSF)");
webframeworks.add("Google Web Toolkit (GWT)");
webframeworks.add("Apache Wicket");
webframeworks.add("Apache Click");
webframeworks.add("Apache Cocoon");
webframeworks.add("JBoss Seam");
webframeworks.add("Stripes");
webframeworks.add("Apache Tapestry");
webframeworks.add("Others");
}
public String getYourLuckyNumber() {
return yourLuckyNumber;
}
public void setYourLuckyNumber(String yourLuckyNumber) {
this.yourLuckyNumber = yourLuckyNumber;
}
public String getYourFavWebFramework() {
return yourFavWebFramework;
}
public void setYourFavWebFramework(String yourFavWebFramework) {
this.yourFavWebFramework = yourFavWebFramework;
}
public List<String> getWebframeworks() {
return webframeworks;
}
public void setWebframeworks(List<String> webframeworks) {
this.webframeworks = webframeworks;
}
public String display() {
return NONE;
}
}
3.结果页面
通过“ < s:autocompleter > ”标签渲染“ autocompleter ”组件,通过 Java list 和 OGNL 生成自动下拉建议列表。
autocompleter.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>
<body>
<h1>Struts 2 autocompleter example</h1>
<s:form action="resultAction" namespace="/" method="POST" >
<sx:autocompleter label="What's your lucky number?"
name="yourLuckyNumber" autoComplete="false"
list="{
'1','12','13','14','21','22','23','24',
'31','32','33','34','41','42','43','44'}" />
<sx:autocompleter label="What's your favorite web framework?"
list="webframeworks" name="yourFavWebFramework" />
<s:submit value="submit" name="submit" />
</s:form>
</body>
</html>
result.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<h1>Struts 2 autocompleter example</h1>
<h2>
Lucky Number : <s:property value="yourLuckyNumber"/>
</h2>
<h2>
Web Appication Frameworks : <s:property value="yourFavWebFramework"/>
</h2>
</body>
</html>
3.struts.xml
全部链接起来~
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="autoCompleterAction"
class="com.mkyong.common.action.AutoCompleterAction"
method="display">
<result name="none">pages/autocompleter.jsp</result>
</action>
<action name="resultAction"
class="com.mkyong.common.action.AutoCompleterAction" >
<result name="success">pages/result.jsp</result>
</action>
</package>
</struts>
4.演示
http://localhost:8080/struts 2 example/autocomplete action . action
Here’s another example to show the use of JSON data to provide a list of the select options to the autocompleter component – Struts 2 autocompleter + JSON example.
参考
Struts 2 自动完成器+ JSON 示例
Download It – Struts2-AutoCompleter-JSON-Example.zip
在最后一个 Struts 2 autocompleter 示例中,您了解了如何通过 Java list 和 ONGL 表达式为 autocompleter 组件生成一个选择选项列表。或者,也可以通过 JSON 数据生成选择选项。
Before you proceed, make sure you understand the basic usage of autocompleter component and JSON plugin. Read the below articles.
Struts 2 自动完成器+ JSON 示例
在本教程中,您将使用 Struts 2 JSON 插件将一个对象转换成 JSON 格式,并将其传递给自动完成器组件。
1.获取依赖库
获取所有的依赖库。
pom.xml
<!-- Struts 2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.1.8</version>
</dependency>
<!-- Struts 2 Dojo Ajax Tags -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-dojo-plugin</artifactId>
<version>2.1.8</version>
</dependency>
<!-- Struts 2 JSON Plugins -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.1.8</version>
</dependency>
2.行动
一个稍后要转换成 JSON 格式的类,为自动完成器组件提供一个选择选项列表。
DatabaseJSON.java
package com.mkyong.common.action;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.Action;
public class DatabaseJSON{
private Map<String, String> databases = new HashMap<String, String>();
public DatabaseJSON(){
databases.put("MySQL", "MySQL");
databases.put("Oracle", "Oracle");
databases.put("PostgreSQL", "PostgreSQL");
databases.put("Microsoft SQL Server", "Microsoft SQL Server");
databases.put("DB2", "DB2");
databases.put("Others", "Others");
}
public String execute() {
return Action.SUCCESS;
}
public Map<String, String> getDatabases() {
return databases;
}
public void setDatabases(Map<String, String> databases) {
this.databases = databases;
}
}
一个普通的 Action 类,只做重定向工作并存储 autocompleter 值。
AutoCompleterAction.java
package com.mkyong.common.action;
import com.opensymphony.xwork2.ActionSupport;
public class AutoCompleterAction extends ActionSupport{
private String yourDatabase;
public String display() {
return NONE;
}
public String getYourDatabase() {
return yourDatabase;
}
public void setYourDatabase(String yourDatabase) {
this.yourDatabase = yourDatabase;
}
}
3.结果
这里有点棘手,使用一个" s:url “标签指向一个” databaseJSON "动作,它将以 JSON 格式返回一个选项列表。并通过 href=“%{databaseList}” 将其链接到自动完成器组件。
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>
<body>
<h1>Struts 2 autocompleter + JSON example</h1>
<s:form action="resultAction" namespace="/" method="POST" >
<s:url id="databaseList" action="databaseJSON" />
<sx:autocompleter label="What's your favorite Database Server?"
href="%{databaseList}" name="yourFavDatabase" />
<s:submit value="submit" name="submit" />
</s:form>
</body>
</html>
4.struts.xml
按如下方式配置操作和 JSON 提供程序:
databases
It means, convert the DatabaseJSON’s databases property into JSON format, but the entire object.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="json" namespace="/" extends="json-default">
<action name="databaseJSON"
class="com.mkyong.common.action.DatabaseJSON">
<result type="json" >
<param name="root">databases</param>
</result>
</action>
</package>
<package name="default" namespace="/" extends="struts-default">
<action name="autoCompleterAction"
class="com.mkyong.common.action.AutoCompleterAction"
method="display">
<result name="none">pages/autocompleter-json.jsp</result>
</action>
<action name="resultAction"
class="com.mkyong.common.action.AutoCompleterAction" >
<result name="success">pages/result.jsp</result>
</action>
</package>
</struts>
4.演示
访问动作 URL,现在 JSON 数据提供了自动完成器选择选项。
http://localhost:8080/struts 2 example/autocomplete action . action
或者,您可以通过以下 URL
直接访问 JSON 数据:http://localhost:8080/struts 2 example/database JSON . action
{
"PostgreSQL":"PostgreSQL",
"MySQL":"MySQL",
"Others":"Others",
"Oracle":"Oracle",
"Microsoft SQL Server":"Microsoft SQL Server",
"DB2":"DB2"
}
参考
Struts 2 bean 标记示例
原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-bean-tag-example/
Download It – Struts2-Bean-Tag-Example.zip
Struts 2 " bean "标签用于在 JSP 页面中实例化一个类。在本教程中,您将使用“ bean ”标记实例化一个名为“ HelloBean ”的类,通过“ param ”元素设置其属性并打印出值。
1.简单豆
一个简单的类,稍后使用 bean 标签来实例化它。
地狱篇. java
package com.mkyong.common.action;
public class HelloBean{
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2.行动
转发请求的操作类。
BeanTagAction.java
package com.mkyong.common.action;
import com.opensymphony.xwork2.ActionSupport;
public class BeanTagAction extends ActionSupport{
public String execute() {
return SUCCESS;
}
}
2.Bean 标记示例
一个 JSP 页面,展示了如何使用“ bean ”标记实例化“ HelloBean ”。
In “bean” tag, you can assign a name to the bean via a “var” attribute, later you can access the bean via #var_bean_name , or its property value via #var_bean_name.property.
bean.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body>
<h1>Struts 2 Bean tag example</h1>
<s:bean name="com.mkyong.common.action.HelloBean" var="hello">
<s:param name="msg">Hello Bean Tag</s:param>
</s:bean>
The HelloBean's msg property value : <s:property value="#hello.msg"/>
</body>
</html>
3.struts.xml
链接一下~
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="beanTagAction"
class="com.mkyong.common.action.BeanTagAction" >
<result name="success">pages/bean.jsp</result>
</action>
</package>
</struts>
4.演示
http://localhost:8080/struts 2 example/bean tag action . action
输出
参考
Struts 2 中文本地化问题
一个 Struts 2 i18n 显示中文字符的本地化问题…
案例 1:包含特殊字符的属性文件
一个属性文件以中文存储用户名、密码和提交信息。这个属性文件是以 UTF 8 格式创建的,但是内容不是用 native2ascii 编码的。
让我们尝试通过几个 UI 标签来显示中文字符。视图页面被声明为以带有 HTML meta 标签的 UTF-8 格式显示。
...
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
...
<s:form action="validateUser">
<s:textfield key="global.username" name="username"/>
<s:password key="global.password" name="password"/>
<s:submit key="global.submit" name="submit" />
<div>Testing 1 : <s:property value="getText('global.username')" /></div>
<div>Testing 2 : <s:text name="global.password" /></div></br/>
</s:form>
...
<s:url id="localezhCN" namespace="/" action="locale" >
<s:param name="request_locale" >zh_CN</s:param>
</s:url>
...
<s:a href="%{localezhCN}" >Chinese</s:a>
...
结果
令人惊讶的是,下面三个 UI 标签能够正确显示中文消息,
<s:textfield key="global.username" name="username"/>
<s:password key="global.password" name="password"/>
Testing 2 : <s:text name="global.password" />
但是“ s:submit ”和“ getText() ”都无法显示?
According to Java’s i18n documentation, to display a special character correctly with resource bundle, it must be precessed with the native2ascii tool.
在深入研究了 TextProvider.getText() 源代码后,它使用 resource bundle.getString()从资源包中检索消息,因此不正确的消息是合理的。但是为什么“ s:text ”、“ s:textfield ”和“ s:password ”能够正确显示中文信息,为什么“ s:submit ”会失败呢?我脑子里的问题太多了,让我们来看案例 2…
案例 2:带有特殊字符的属性文件(编码)
这一次,使用 native2ascii 工具处理属性文件,并正确编码中文字符。
结果
结果完全相反,现在“ s:submit ”和“ getText() ”能够正确显示,但是其他 UI 组件都失败了。这是预期工作,因为 Struts 2 推荐 getText() 显示 i18n 或本地化消息。问题是,为什么“ s:submit 不一样?
支柱 2…怎么了?
以下是我心中的一些疑问…
- 为什么 s:submit 的表现如此不同?
- i18n 应该很简单,为什么 Struts 2 有这种问题?还是我误解了 Struts 2 i18n 的工作原理?
- 为什么资源包中的消息有这么多显示方式?为什么不直接用一种方法分组呢?在 Struts 1 中,只使用“bean:message ”,为什么在 Struts 2 中看起来如此复杂?
- Struts 2 支持 XML 资源包吗?我只是不喜欢使用 native2ascii 工具将数据编码为 UTF 8 格式,这使得属性文件不可读。Apache Wicket 在这个问题上做得非常好,可能 Struts 2 应该借鉴一下。
- 那么,如何在 Struts 2 中正确显示汉字呢? Many articles and tutorials are told that the following methods are able to display the message from resource bundle:
<s:text name="global.username"/>
<s:property value="getText('global.username')"/>
但是,这仅适用于英语或一些“类似英语(欧洲)”的字符,例如法国、德国。但是对于中文或日文的“大方块”字符,两种方法将返回完全不同的输出。真的不知道如何将 Struts 2 本地化为中文和日文。
更新于…(2010 年 6 月 16 日)
从百度搜索引擎中挖掘解决方案,在其中一篇中文文章中找到了间接解决方案——Struts 2 国际化实例
解决办法
问题出在 HTML meta 标签上,
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
In Struts 1, the above meta tag is required to display the UTF-8 data correctly, but this is not true for Struts 2.
在 Struts 2 中,meta 标签不再起作用,我们应该把 **< %@页面 content type = " text/html;charset = UTF-8 "%>**标签在查看页面的第一行。举个例子,
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
...
结果
所有的中文信息都显示正确。
对我之前问题的回答
- 为什么 s:submit 的表现如此不同?答:对此不予置评
- i18n 应该很简单,为什么 Struts 2 有这种问题?还是我误解了 Struts 2 i18n 的工作原理?
答:一定要把 < %@页 content type = " text/html;charset = UTF-8 "%>"在查看页面的第一行。 - 为什么资源包中的消息有这么多显示方式?为什么不直接用一种方法分组呢?在 Struts 1 中,只使用“bean:message ”,为什么在 Struts 2 中看起来如此复杂?
A: s:text,key,getText(),name…,都能够正确渲染中文或 UTF 8 编码的数据,只要确保在视图页面中放入正确的“charset”即可。我仍然倾向于只使用一种方法来控制消息包(比如 Struts 1),太多的等价选项只会让开发人员感到困惑。 - Struts 2 支持 XML 资源包吗?我只是不喜欢使用 native2ascii 工具将数据编码为 UTF 8 格式,这使得属性文件不可读。Apache Wicket 在这个问题上做得非常好,可能 Struts 2 应该借鉴一下。
答:希望 Struts 2 能在下一个版本支持 XML 资源包。 - 那么,如何在 Struts 2 中正确显示汉字呢?
答:见上解。
Download it – Struts2-i18n-issue-Example
参考
- http://www . mkyong . com/Java/Java-convert-Chinese-character-to-unicode-with-native 2 ascii/
- http://forums.sun.com/thread.jspa?threadID=5185040
- http://www . mail-archive . com/user @ struts . Apache . org/msg 85490 . html
- http://www . code ranch . com/t/452139/Struts/application resources-properties-utf-characters # 2013 557
- http://struts.apache.org/2.1.8/docs/localization.html
- http://hxzon 00 . blog . 163 . com/blog/static/10489241620088121449163/
multiple languages struts2 (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById®;if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!‘undefined’){i[c]++} else{i[c]=1;} })(window, document, ‘InContent’, ‘script’, ‘mediaType’, ‘carambola_proxy’,‘Cbola_IC’,‘localStorage’,‘set’,‘get’,‘Item’,‘cbolaDt’,‘//web.archive.org/web/20190601051037/https://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0’)
struts 2–为操作类配置静态参数
Download It – Struts-Action-Static-ParamExample.zip
在某些情况下,您可能需要为动作类分配一些预定义的或静态的参数值。
定义了动作的静态参数
在 Struts 2 中,可以在 struts.xml 文件中进行配置,通过 < param > 标签,例如
struts.xml
<struts>
<constant name="struts.custom.i18n.resources" value="global" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="locale" class="com.mkyong.common.action.LocaleAction">
<result name="SUCCESS">pages/welcome.jsp</result>
<param name="EnglishParam">English</param>
<param name="ChineseParam">Chinese</param>
<param name="FranceParam">France</param>
</action>
</package>
</struts>
它将三个预定义参数值分配给一个 LocaleAction 操作类。
从操作中获取静态参数
为了从 struts.xml 中获取静态参数值,Action 类必须实现参数化接口。它可以通过地图属性或 JavaBean 属性来访问。
The Action’s static parameters is control by the staticParams Interceptor, which is included in the default stack “struts-default.xml”. ## 1.地图属性
在动作类初始化期间,staticParams 拦截器将通过 setParams() 方法将预定义参数值的引用传递给动作类。
//...
import com.opensymphony.xwork2.config.entities.Parameterizable;
public class LocaleAction implements Parameterizable{
Map<String, String> params;
//...
public void setParams(Map<String, String> params) {
this.params = params;
}
}
2.JavaBean 属性
在 Action 类初始化期间,如果您正确地创建了 getter 和 setter 方法,staticParams 拦截器会将预定义的参数值设置为对应于“param”元素的每个 JavaBean 属性。
//...
import com.opensymphony.xwork2.config.entities.Parameterizable;
public class LocaleAction implements Parameterizable{
String englishParam;
String chineseParam;
String franceParam;
public String getEnglishParam() {
return englishParam;
}
public void setEnglishParam(String englishParam) {
this.englishParam = englishParam;
}
public String getChineseParam() {
return chineseParam;
}
public void setChineseParam(String chineseParam) {
this.chineseParam = chineseParam;
}
public String getFranceParam() {
return franceParam;
}
public void setFranceParam(String franceParam) {
this.franceParam = franceParam;
}
//...
}
Struts 2 创建自己的拦截器
Download it – Struts2-Create-Own-Interceptor-Example.zip
在本教程中,它展示了如何在 Struts 2 中创建自己的拦截器。
总结步骤:
- 创建一个类实现com . open symphony . xwork 2 . interceptor . interceptor。
- 实现 **intercept(ActionInvocation 调用)**方法。
- 在 struts.xml 中配置拦截器。
- 把它和行动联系起来。
Struts 2 interceptors
Struts 2 comes with many ready interceptors, make sure you check the list of the available Struts 2 interceptors before you create your own interceptor.
创建自己的拦截器的完整示例:
1.行动
转发用户请求和打印消息的简单操作。
HelloAction.java
package com.mkyong.common.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport{
public String execute() throws Exception {
System.out.println("HelloAction execute() is called");
return SUCCESS;
}
}
2.拦截机
一个完整的拦截器示例。
PrintMsgInterceptor.java
package com.mkyong.common.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class PrintMsgInterceptor implements Interceptor{
//called during interceptor destruction
public void destroy() {
System.out.println("CustomInterceptor destroy() is called...");
}
//called during interceptor initialization
public void init() {
System.out.println("CustomInterceptor init() is called...");
}
//put interceptor code here
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("CustomInterceptor, before invocation.invoke()...");
String result = invocation.invoke();
System.out.println("CustomInterceptor, after invocation.invoke()...");
return result;
}
}
解释
拦截器类必须实现com . open symphony . xwork 2 . interceptor . interceptor 接口。拦截器初始化时,调用init();拦截器破坏, destroy() 被调用。最后,将所有完成工作的拦截器代码放在**intercept(action invocation invocation)**方法中。
invocation.invoke()
In the interceptor intercept() method, you must called the invocation.invoke() and return it’s result. This is the method responsible for calling the next interceptor or the action. The action will failed to continue without calling the invocation.invoke() method.destroy() is not reliable
It’s not recommend to put any code inside the destroy(), because this method is not reliable. When your application server is force shutdown or be killed by command, the destroy() will not be called. ## 3.struts.xml
在 struts.xml 文件中配置拦截器。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="printMsgInterceptor"
class="com.mkyong.common.interceptor.PrintMsgInterceptor"></interceptor>
<interceptor-stack name="newStack">
<interceptor-ref name="printMsgInterceptor"/>
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<action name="helloAction"
class="com.mkyong.common.action.HelloAction" >
<interceptor-ref name="newStack"/>
<result name="success">pages/hello.jsp</result>
</action>
</package>
</struts>
4.演示
在服务器初始化期间,拦截器 init() 方法被调用。
INFO: Overriding property struts.i18n.reload - old value: false new value: true
15 Julai 2010 11:37:42 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
INFO: Overriding property struts.configuration.xml.reload - old value: false new value: true
CustomInterceptor init() is called...
15 Julai 2010 11:37:42 AM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
15 Julai 2010 11:37:42 AM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
15 Julai 2010 11:37:42 AM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/20 config=null
15 Julai 2010 11:37:42 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 994 ms
当您通过 URL 访问操作时:http://localhost:8080/struts 2 example/hello action . action
INFO: Overriding property struts.i18n.reload - old value: false new value: true
15 Julai 2010 11:37:42 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
INFO: Overriding property struts.configuration.xml.reload - old value: false new value: true
CustomInterceptor init() is called...
15 Julai 2010 11:37:42 AM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
15 Julai 2010 11:37:42 AM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
15 Julai 2010 11:37:42 AM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/20 config=null
15 Julai 2010 11:37:42 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 994 ms
CustomInterceptor, before invocation.invoke()...
HelloAction execute() is called
CustomInterceptor, after invocation.invoke()...
参考
Struts 2 日期标记示例
原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-date-tag-example/
Download It – Struts2-Date-Tag-Example.zip
Struts 2 " date 标签用于以两种方式格式化日期对象:
- 自定义日期格式(如“日/月/年”)。
- “nice”属性将日期格式化为易于阅读的符号,如“此日期是 162 天前”。
在本教程中,它展示了使用 Struts 2 " date “标记将日期对象格式化为"自定义日期格式"和"易读符号”。
1.行动
转发请求的操作类,并用预定义的日期初始化日期对象。
date tagging . Java
package com.mkyong.common.action;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
public class DateTagAction extends ActionSupport{
public Date customDate;
public String execute() {
Calendar cal = Calendar.getInstance();
//set date to january 31, 2010
cal.set(2010, 0, 31);
Date newDate = cal.getTime();
setCustomDate(newDate);
return SUCCESS;
}
public Date getCustomDate() {
return customDate;
}
public void setCustomDate(Date customDate) {
this.customDate = customDate;
}
}
2.日期标签示例
一个 JSP 页面,展示了如何使用“ date 标记来格式化日期对象:
- 默认日期格式。
- 自定义日期格式。
- 易读的符号。
date.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body>
<h1>Struts 2 date tag example</h1>
<ol>
<li>
Default date format
--> <strong><s:date name="customDate" /></strong>
</li>
<li>
Date format in "dd/MM/yyyy"
--> <strong><s:date name="customDate" format="dd/MM/yyyy" /></strong>
</li>
<li>
In Date tag, set the nice attribute to "true"
--> <strong><s:date name="customDate" nice="true" /></strong>
</li>
</ol>
</body>
</html>
3.struts.xml
链接一下~
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="dateTagAction"
class="com.mkyong.common.action.DateTagAction" >
<result name="success">pages/date.jsp</result>
</action>
</package>
</struts>
4.演示
http://localhost:8080/struts 2 example/datetagaction . action
输出
参考
Struts 2 日期时间选择器示例
Download It – Struts2-DateTimePicker-Example.zip
在 Struts 2 中,dojo ajax 标签“<sx:datetime picker>”会呈现一个文本框并在后面追加一个日历图标,点击日历图标会提示一个日期时间选择器组件。
创建一个日期时间选择组件,只需确保:
1。下载 struts2-dojo-plugin.jar 库。
2。包括“struts-dojo-tags”标记,并输出其标题。
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>
举个例子,
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>
<body>
<sx:datetimepicker name="date2" label="Format (dd-MMM-yyyy)"
displayFormat="dd-MMM-yyyy" value="%{'2010-01-01'}"/>
...
产生了下面的 HTML,几个 dojo 和 JavaScript 库来创建一个日期时间选择组件。
<html>
<head>
<script language="JavaScript" type="text/javascript">
// Dojo configuration
djConfig = {
isDebug: false,
bindEncoding: "UTF-8"
,baseRelativePath: "/Struts2Example/struts/dojo/"
,baseScriptUri: "/Struts2Example/struts/dojo/"
,parseWidgets : false
};
</script>
<script language="JavaScript" type="text/javascript"
src="/Struts2Example/struts/dojo/struts_dojo.js"></script>
<script language="JavaScript" type="text/javascript"
src="/Struts2Example/struts/ajax/dojoRequire.js"></script>
<link rel="stylesheet" href="/Struts2Example/struts/xhtml/styles.css" type="text/css"/>
<script language="JavaScript" src="/Struts2Example/struts/utils.js"
type="text/javascript"></script>
<script language="JavaScript" src="/Struts2Example/struts/xhtml/validation.js"
type="text/javascript"></script>
<script language="JavaScript" src="/Struts2Example/struts/css_xhtml/validation.js"
type="text/javascript"></script>
</head>
...
<td class="tdLabel">
<label for="widget_1291193434" class="label">Format (dd-MMM-yyyy):
</label></td>
<td>
<div dojoType="struts:StrutsDatePicker" id="widget_1291193434"
value="2010-01-01" name="date2" inputName="dojo.date2"
displayFormat="dd-MMM-yyyy" saveFormat="rfc"></div>
</td>
</tr>
<script language="JavaScript" type="text/javascript">
djConfig.searchIds.push("widget_1291193434");</script>
Struts 2 示例
一个完整的完整示例,使用 < s:datetimepicker > 标签生成一个 datetimepicker 组件,并展示如何使用 OGNL 和 Java 属性将默认日期设置为“ datetimepicker ”组件。
1.pom.xml
下载 Struts 2 dojo 依赖库。
pom.xml
//...
<!-- Struts 2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.1.8</version>
</dependency>
<!-- Struts 2 Dojo Ajax Tags -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-dojo-plugin</artifactId>
<version>2.1.8</version>
</dependency>
//...
2.动作类
存储选定日期的操作类。
date time pick . Java
package com.mkyong.common.action;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
public class DateTimePickerAction extends ActionSupport{
private Date date1;
private Date date2;
private Date date3;
//return today date
public Date getTodayDate(){
return new Date();
}
//getter and setter methods
public String execute() throws Exception{
return SUCCESS;
}
public String display() {
return NONE;
}
}
3.结果页面
通过“ < s:datetimepicker > ”标签呈现日期时间选择器组件,通过 Java 属性和 OGNL 设置默认日期。
The ‘displayFormat‘ attribute is supported in many date patterns, read this article – Date Format Patterns.Ensure you put the “struts-dojo-tags” tag and render it’s header <sx:head />
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>
datetimepicker.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>
<body>
<h1>Struts 2 datetimepicker example</h1>
<s:form action="resultAction" namespace="/" method="POST" >
<sx:datetimepicker name="date1" label="Format (dd-MMM-yyyy)"
displayFormat="dd-MMM-yyyy" value="todayDate" />
<sx:datetimepicker name="date2" label="Format (dd-MMM-yyyy)"
displayFormat="dd-MMM-yyyy" value="%{'2010-01-01'}"/>
<sx:datetimepicker name="date3" label="Format (dd-MMM-yyyy)"
displayFormat="dd-MMM-yyyy" value="%{'today'}"/>
<s:submit value="submit" name="submit" />
</s:form>
</body>
</html>
result.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<h1>Struts 2 datetimepicker example</h1>
<h2>
Date1 : <s:property value="date1"/>
</h2>
<h2>
Date 2 : <s:property value="date2"/>
</h2>
<h2>
Date 3 : <s:property value="date3"/>
</h2>
</body>
</html>
3.struts.xml
全部链接起来~
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="dateTimePickerAction"
class="com.mkyong.common.action.DateTimePickerAction"
method="display">
<result name="none">pages/datetimepicker.jsp</result>
</action>
<action name="resultAction"
class="com.mkyong.common.action.DateTimePickerAction" >
<result name="success">pages/result.jsp</result>
</action>
</package>
</struts>
4.演示
http://localhost:8080/struts 2 example/datetimepickeraction . action
参考
Struts 2 调试标记示例
原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-debug-tag-example/
Download It – Struts2-Debug-Tag-Example.zip
在 Struts 2 中,“ debug 标签是一个非常有用的调试标签,用来输出“值栈的内容,以及 web 页面中的“栈上下文细节。在本教程中,它展示了在 JSP 页面中使用“ debug ”标记。
1.行动
一个简单的 Action 类,带有一个“ propertyInStack 属性,稍后显示在值堆栈中。
DebugTagAction.java
package com.mkyong.common.action;
import com.opensymphony.xwork2.ActionSupport;
public class DebugTagAction extends ActionSupport{
public String propertyInStack;
public String getPropertyInStack() {
return propertyInStack;
}
public void setPropertyInStack(String propertyInStack) {
this.propertyInStack = propertyInStack;
}
}
2.日期标签示例
一个 JSP 页面,显示使用" debug “标签输出系统的"值栈"和"栈上下文”。
debug.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body>
<h1>Struts 2 debug tag example</h1>
<s:debug />
</body>
</html>
The <s:debug /> will generate a text link named “debug“, you need to click on the text link to expand the debugging details. ## 3.struts.xml
链接一下~
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="debugTagAction"
class="com.mkyong.common.action.DebugTagAction" >
<result name="success">pages/debug.jsp</result>
</action>
</package>
</struts>
4.演示
http://localhost:8080/struts 2 example/debugtagaction . action
输出
参考
struts 2–开发模式示例
在 Struts 2 开发中,这应该是要学习的第一个可配置值。为了启用 Struts 2 开发模式,您可以通过给予自动配置和属性文件重新加载和额外的日志记录和调试特性来显著提高您的 Struts 2 开发速度。
The auto reload feature is really a convenient feature. Each time i made changed in properties or XML configuration file, the application is no longer need to restart to take effect.By default, the Struts 2 development mode is disabled.
启用 Strut2 开发模式
在 struts 属性文件或 XML 配置文件中将" struts.devMode "值设置为 true。
struts.properties
struts.devMode = true
struts.xml
<struts>
<constant name="struts.devMode" value="true" />
</struts>
禁用 Strut2 开发模式
在 struts 属性文件或 XML 配置文件中将" struts.devMode "设置为 false。
struts.properties
struts.devMode = false
struts.xml
<struts>
<constant name="struts.devMode" value="false" />
</struts>
The development mode is only suitable in development or debugging environment. In production environment, you HAVE TO disabled it. It will caused significant impact on performance, because the entire application configuration, properties files will be reloaded on every request, many extra logging and debug information will be provide also.Before commit Struts configuration file, just make sure the development mode is turn off. I saw many accidentally commit cases – commit with development mode enable, and someone just grab the source code for QA environment. To be Frankly, QA seldom will do the performance test, they just make sure the functionality are there, and end with a development mode enabled application deployed to the production. Guess what? you will receive many screaming phone calls from clients very soon… ## 参考
Struts 2 下载文件示例
Download it – Struts2-Download-File-Example.zip
一个 Struts 2 的例子,展示了使用自定义结果类型来允许用户下载文件。
1.行动
在 Action 类中,声明了 InputStream 数据类型及其 getter 方法。
DownloadAction.java
package com.mkyong.common.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport{
private InputStream fileInputStream;
public InputStream getFileInputStream() {
return fileInputStream;
}
public String execute() throws Exception {
fileInputStream = new FileInputStream(new File("C:\\downloadfile.txt"));
return SUCCESS;
}
}
2.查看页面
一个普通的页面,有一个下载文件的链接。
下载页. jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<h1>Struts 2 download file example</h1>
<s:url id="fileDownload" namespace="/" action="download" ></s:url>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
});
</script><h2>Download file - <s:a href="%{fileDownload}">fileABC.txt</s:a>
</h2>
</body>
</html>
3.struts.xml
定义下载文件细节,不言自明。****值是动作的 InputStream 属性的名称。
Read this Struts 2 Stream Result documentation for more detail explanation.
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="">
<result name="success">pages/downloadPage.jsp</result>
</action>
<action name="download" class="com.mkyong.common.action.DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="fileABC.txt"</param>
<param name="bufferSize">1024</param>
</result>
</action>
</package>
</struts>
4.运行它
http://localhost:8080/struts 2 example/
参考
- http://struts.apache.org/2.x/docs/stream-result.html
- http://www.iana.org/assignments/media-types/
- http://www . mkyong . com/struts/struts-download-file-from-website-example/
- http://www . mkyong . com/Java/how-to-download-file-from-website-Java-JSP/
- http://struts . Apache . org/2 . x/docs/how-can-we-return-a-text-string-as-the-response . html
download file struts2 (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById®;if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!‘undefined’){i[c]++} else{i[c]=1;} })(window, document, ‘InContent’, ‘script’, ‘mediaType’, ‘carambola_proxy’,‘Cbola_IC’,‘localStorage’,‘set’,‘get’,‘Item’,‘cbolaDt’,‘//web.archive.org/web/20190304031742/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0’)
Struts 2 execAndWait 拦截器示例
Download it – Struts2-ExecAndWait-Interceptor-Example.zip
Struts 2 附带了一个非常有趣的“执行和等待”拦截器,名为“执行和等待”,这是一个非常方便的拦截器,用于在后台长时间运行的操作,同时向用户显示一个自定义的等待页面。在本教程中,它展示了一个使用 Struts 2 execAndWait 拦截器的完整示例。
1.行动
一个普通的 action 类,用一个很长的运行过程来演示 execAndWait 效果。
LongProcessAction.java
package com.mkyong.common.action;
import com.opensymphony.xwork2.ActionSupport;
public class LongProcessAction extends ActionSupport{
public String execute() throws Exception {
//it should be delay few seconds,
//unless you have a super powerful computer.
for(int i =0; i<1000000; i++){
System.out.println(i);
}
return SUCCESS;
}
}
2.JSP 页面
创建两个页面:
- wait.jsp-在处理长时间运行的流程时向用户显示。
- success.jsp——流程完成后显示给用户。
HTML meta refresh
Remember to put the meta refresh on top of the waiting page; Otherwise, the page will not redirect to the success page, even the process is completed.
在这个wait.jsp中,元刷新被设置为每 5 秒重新加载一次页面,如果该过程完成,它将重定向到 success.jsp 的**,否则停留在同一页面。**
wait.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="refresh" content="5;url=<s:url includeParams="all" />"/>
</head>
<body>
<h1>Struts 2 execAndWait example</h1>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
});
</script><h2>Please wait while we process your request...</h2>
</body>
</html>
success.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body>
<h1>Struts 2 execAndWait example</h1>
<h2>Done</h2>
</body>
</html>
3.执行和等待拦截器
链接 action 类并声明了" execAndWait "拦截器。
execAndWait parameters
- 延迟(可选):显示 wait.jsp 的初始延迟时间,以毫秒为单位。默认为无延迟。
- delaySleepInterval(可选):检查后台进程是否已经完成的间隔,以毫秒为单位。默认值为 100 毫秒。
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="longProcessAction"
class="com.mkyong.common.action.LongProcessAction" >
<interceptor-ref name="execAndWait">
<param name="delay">1000</param>
<param name="delaySleepInterval">500</param>
</interceptor-ref>
<result name="wait">pages/wait.jsp</result>
<result name="success">pages/success.jsp</result>
</action>
</package>
</struts>
在这种情况下,它将延迟 1 秒显示wait.jsp,并每隔 500 毫秒检查一次后台进程是否已经完成。即使这个过程完成了,仍然需要等待 wait.jsp 的meta refresh 来激活页面重载。
4.演示
访问 URL:http://localhost:8080/struts 2 example/longprocessaction . action
延时 1 秒,显示wait.jsp。
过程完成后,自动显示success.jsp。
参考
interceptor struts2 (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById®;if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!‘undefined’){i[c]++} else{i[c]=1;} })(window, document, ‘InContent’, ‘script’, ‘mediaType’, ‘carambola_proxy’,‘Cbola_IC’,‘localStorage’,‘set’,‘get’,‘Item’,‘cbolaDt’,‘//web.archive.org/web/20190214232659/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0’)