JavaEE-控制器Struts2
2015年9月20日
2015年9月23日重构
1 目标:web应用控制器。拦截所有请求,预处理,映射请求和处理类,根据处理结果跳转到不同的页面。
2 原理:为web应用增加struct2过滤器,将过滤过程抽象为接口。
struts是开源软件,目的是为了减少MVC设计模型开发Web应用的时间。struts可以清晰地区分控制,事务逻辑和外观,简化了开发应用程序的过程。
参考:
3 流程:安装struts2库。配置web应用(web.xml)。配置struts2(struts.xml)。实现业务action。
参考:http://blog.csdn.net/wwwgeyang777/article/details/19078545
3.1 安装struts2库:仅安装需要库,全部安装可能会有冲突。
将以下jar从Struts2的lib文件夹中copy到web应用的lib文件夹中。
参考:
3.2 配置web应用:在web.xml中增加struts2过滤器,过滤所有请求。
增加一个过滤器,指定为Struts的StrutsPrepareAndExecuteFilter。
过滤器配置方法参见:Servlet-过滤器Filter.docx
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"id="WebApp_ID" version="3.1">
<display-name>Struts2Demo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<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>
</web-app>
3.3 配置struts2:在struts.xml实现请求与业务过滤器action的映射,结果映射等。
请求与业务过滤器映射:action将name请求映射到class中处理。
结果映射:result将name结果映射到指定目标。
注意:struts.xml的名称是固定的。位置也是固定(src目录中)。
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee"extends="struts-default">
<action name="login"class="lee.LoginAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
3.4 实现业务过滤器Action:进行预处理。并返回结果。
创建预处理类:继承ActionSupport。实现execute()函数(默认调用)。
/**
*
*/
package lee;
importcom.opensymphony.xwork2.ActionSupport;
/**
* @author sf
*
*/
public class LoginActionextends ActionSupport {
publicString execute(){
System.out.println("this is lee.LoginAction.");
return SUCCESS;
}
}
3.5 过滤请求:过滤器的action名称就是请求的名称或名称.action。
Struts2将过滤请求为action名称的请求或者名称.action的请求(此处为仿照Rails约定)。
注意:区分大小写。
示例:
http://192.168.41.130:8080/Struts2Demo/login.action
和http://192.168.41.130:8080/Struts2Demo/login是相同的。
但是http://192.168.41.130:8080/Struts2Demo/login.Action却无法识别。
3.6 示例:过滤login请求,并返回成功页面
//web.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"id="WebApp_ID" version="3.1">
<display-name>Struts2Demo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<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>
</web-app>
//struts.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee"extends="struts-default">
<action name="login"class="lee.LoginAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
//LoginAction.java
/**
*
*/
package lee;
importcom.opensymphony.xwork2.ActionSupport;
/**
* @author sf
*
*/
public class LoginActionextends ActionSupport {
publicString execute(){
System.out.println("this is lee.LoginAction.");
return SUCCESS;
}
}
//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>
<metahttp-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Indexjsp</title>
</head>
<body>
</body>
</html>
注意:添加index.jsp,用于响应空请求,否则会出现无空请求响应警告(不影响正常运行)。
参考:http://bbs.csdn.net/topics/310118421
4 方法:struts2配置
组织结构:以struts标签为根。
4.1 请求和处理类映射:structs.xml中设置action(业务控制器)。
4.1.1组织结构:action组织package,请求的组织namespace。
action组织:各个action的组织结构,主要用于后台分类,可以继承(extends,默认组织为struts-default)。
请求组织:组织不同的请求路径,用于客户请求调用。
参考:http://bbs.csdn.net/topics/380031036
http://blog.csdn.net/sapphire_aling/article/details/6073265
示例:请求路径为/lee3/action名称。action置于package之中。
<struts>
<packagename="lee2" namespace="/lee3"extends="struts-default">
<action name="carInfo"class="lee.CarInfoAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
<action name="student"class="lee.Student">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
4.1.2请求:在jsp中设置每个请求的action名称。
<body>
<s:form action="login">
<s:textfield name="username"key="user"/>
<s:textfield name="password"key="pass" />
<s:submit key="login"/>
</s:form>
</body>
4.1.3映射:请求处理映射(action的name和class),结果映射(result标签)
4.1.3.1 请求与业务过滤器映射:action将name请求映射到class中处理。
注意:请求受到namespace影响。
<action name="login"class="lee.LoginAction">
4.1.3.2 结果映射:result将结果name结果映射到指定目标。
result预设5个结果(预设值定义于Action接口),可以增加自己定义结果值。
预设结果宏:SUCCESS(默认值)、INPUT、ERROR、LOGIN、NONE
<resultname="success">/Welcome.jsp</result>
4.1.3.3 示例:自定义结果值
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee2" namespace="/lee3"extends="struts-default">
<action name="carInfo"class="lee.CarInfoAction">
<resultname="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="student"class="lee.Student">
<resultname="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
</action>
</package>
</struts>
//Student.java
package lee;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
System.out.println("lee.Student");
return"xx23";
}
}
4.2 处理类:Action,struts2的基本单位
4.2.1处理类:可以是任意的POJO,默认调用execute()函数。
4.2.2实用处理类:Action接口是标准处理接口。ActionSupport是Action接口的默认实现。一般使用ActionSupport的派生类快速实现处理类。
Action接口:定义标准返回值,默认处理函数execute()。
ActionSupport:实现Action接口,包括数据校验等大量的实用函数。
4.2.3设置参数:带有getter,setter的属性可以直接在请求中使用。
可以在get或post的方式设置。
示例:get方式设置:
http://192.168.41.130:8080/Struts2Demo/lee3/student?name=xxx&age=222
4.2.4获取结果参数:过滤器返回后,处理类中的属性会以reqeust.attribute的形式返回给客户端。可以使用request.getAttribute(参数名)获取。
参考:http://www.linuxidc.com/Linux/2014-06/103106.htm
4.2.5示例
4.2.5.1 自定义参数的设置和读取。
//请求:http://192.168.41.130:8080/Struts2Demo/lee3/student?name=xxx&age=222
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee2" namespace="/lee3"extends="struts-default">
<action name="carInfo"class="lee.CarInfoAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
<action name="student"class="lee.Student">
<resultname="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
</action>
</package>
</struts>
//error.jsp
<%@ pagelanguage="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>
<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>error.jsp</title>
</head>
<body>
this is error.jsp
<%String username=(String)request.getAttribute("name"); %>
<%=username %>
</body>
</html>
//Student.java
package lee;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
System.out.println("lee.Student="+name+","+age);
this.name="backgroundName";
this.age=16;
return"xx23";
}
}
//结果
4.2.5.2 实用处理类
package lee;
importcom.opensymphony.xwork2.ActionContext;
importcom.opensymphony.xwork2.ActionSupport;
public class LoginAction 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;
}
public String execute() throws Exception
{
if(getUsername().equals("abc") &&getPassword().equals("123"))
{
ActionContext.getContext().getSession().put("user",getUsername());
return SUCCESS;
}
else{
return ERROR;
}
}
}
4.3 结果映射:设置result对应的结果页面。
结果中可以OGNL表达式。
4.3.1全局结果:<global-results>…其中是result标签。
4.3.2局部结果:在action中定义result标签。
4.3.3结果定义result:包含name和type属性。name表示收到的结果字符串,type表示结果的处理方式。标签值为结果目标。
结果字符串:name。默认为success,预设5个。参见:结果映射:result将结果name结果映射到指定目标。
结果处理方式type:由struts-defualt.xml中可以查看预设部分type。可以自定义。
常用预设类:页面作为字符串输出plainText,重定向(重新生成请求,丢弃参数)redirect,重定位(保留参数)dispatcher(默认),重定向action(redirectAction)(重新生成action请求),重定位action(chain)(保留参数)。
注意:重定向可能生成无限循环(服务器不处理,浏览器报错)。重定位也可能生成无限循环,服务器识别后报错。
示例:字符串输出plainText
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee2" namespace="/lee3"extends="struts-default">
<action name="carInfo"class="lee.CarInfoAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
<action name="student"class="lee.Student">
<resultname="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
<resultname="str" type="plainText">
<paramname="location">/error.jsp</param>
<paramname="charSet">GBK</param>
</result>
<result name="chain"type="chain" >carInfo</result>
<result name="redirectAction"type="redirectAction">student</result>
</action>
</package>
</struts>
//Student.java
package lee;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionContext;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
System.out.println("execute:lee.Student="+name+","+age);
return"str";
}
public String myAction(){
System.out.println("myAction:lee.Student="+name+","+age);
return "xx23";
}
public String myMethod(){
System.out.println("myMethod:lee.Student="+name+","+age);
return "xx23";
}
}
//请求:http://192.168.41.130:8080/Struts2Demo/lee3/student?name=xxx&age=222
4.4 其它
4.4.1配置文件:struts.xml(自定义),struts-default.xml(默认),struts-plugin.xml(插件),struts.properties(常量配置)。
4.4.1.1 文件加载顺序:struts-default.xml-》struts-plugin.xml-》struts.xml-》struts.properties-》web.xml。
4.4.1.2 组织:配置文件都放在WEB-INF/classes目录中。
4.4.2常量配置:struts.properties或配置文件
目标:配置struts全局属性。只能设置预定义属性。
原理:web.xml中设置初始化参数。
流程:定义初始化参数,读取参数。
方法:struts.xml(推荐)或web.xml(Filter方式)或struts.properties(webwork兼容性)。
4.4.2.1 struts.xml(推荐):constant标签中使用name-value设置。
设置:<constantname="struts.custom.i18n.resources" value="mess" />
读取:此值由Struts2读取并配置相应的属性。
示例:
//struts.xml
<struts>
<constant name="struts.custom.i18n.resources"value="mess" />
<constant name="struts.i18n.encoding"value="GBK"/>
<package name="lee"extends="struts-default">
</struts>
4.4.2.2 web.xml:使用init-param标签设置常量
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>struts.custom.i18n.resources</param-name>
<param-value>mess</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
4.4.2.3 struts.properties(兼容WebWork):使用标准属性的key-value设置整个struts的常量。
示例:
4.4.3struts.xml的扩展子文件:include
4.4.3.1 目标:将struts.xml分为多个子文件,防止单个文件过于复杂。
4.4.3.2 原理:将指定文件插入到struts.xml。
4.4.3.3 流程:定义分文件xml(与Struts.xml结构相同)。使用include加入到struts.xml。
示例:
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee" namespace=""extends="struts-default">
<action name="carInfo" class="lee.CarInfoAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
//struts.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="myparam"value="paramXXXX"></constant>
<constant name="struts.i18n.encoding"value="GBK"></constant>
<package name="lee" namespace="" extends="struts-default">
<action name="login"class="lee.LoginAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
<includefile="mystruts-1.xml"/>
</struts>
4.4.3.4 方法:include标签添加子文件。
格式:<include file="子文件名"/>
4.4.4Action访问ServletAPI:ActionContext访问常用参数。
目标:获取Servlet的上下文参数。
原理:将servlet参数以Map的形式读写。
流程:使用ActionContext的静态函数getActionContext()获取实例。
方法:
request attribute:get(name)、put()。
request请求参数:getParameters()、setParameters()。
session参数:getSession()、setSession。
application参数:getApplication(),setApplication()。
示例:
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee" namespace=""extends="struts-default">
<action name="carInfo"class="lee.CarInfoAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
//Student.java
package lee;
importcom.opensymphony.xwork2.ActionContext;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
System.out.println("lee.Student="+name+","+age);
ActionContext ctx=ActionContext.getContext();
System.out.println("req="+ctx.getParameters());
ctx.put("age22",122);
this.name="background.name";
return "xx23";
}
}
//error.jsp
<%@ pagelanguage="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>
<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>error.jsp</title>
</head>
<body>
this is error.jsp
<% String username=(String)request.getAttribute("name");%>
<%=request.getAttribute("age22") %>
<%=username %>
</body>
</html>
4.4.5Action访问ServletAPI:访问所有Servlet参数ServletActionContext。
struts2提供了获取ServletAPI的封装类(推荐,ServletActionContext)。也可以直接操作API(实现ServletXXXAware),但会增加藕合度(不推荐,忽略)。
ServletActionContext:读写当前ServletAPI。
ActionContext,PageContext,HttpServletRquest,HttpServletResponse,ServletContext等。
示例:
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee" namespace=""extends="struts-default">
<action name="carInfo"class="lee.CarInfoAction">
<result name="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
//Student.java
package lee;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionContext;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
System.out.println("lee.Student="+name+","+age);
ActionContext ctx=ActionContext.getContext();
System.out.println("req="+ctx.getParameters());
ctx.put("age22", 122);
this.name="background.name";
//servlet api
System.out.println("req="+ServletActionContext.getRequest().getParameterMap());
ServletActionContext.getRequest().setAttribute("name22","ServletActionContext22");
return "xx23";
}
}
//error.jsp
<%@ pagelanguage="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>
<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>error.jsp</title>
</head>
<body>
this is error.jsp
<% Stringusername=(String)request.getAttribute("name"); %>
<%=request.getAttribute("age22") %>
<%=username %>
<%=request.getAttribute("name22") %>
</body>
</html>
4.4.6自定义Action处理类的方法:method属性
在struts.xml中设置action标签的method属性。默认使用execute()。
可以为一个处理类定义多个方法处理不同的action请求。
示例:
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee2" namespace="/lee3"extends="struts-default">
<action name="carInfo"class="lee.CarInfoAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
<actionname="student" class="lee.Student"method="myMethod">
<resultname="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
</action>
</package>
</struts>
//Student.java
package lee;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionContext;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
System.out.println("lee.Student="+name+","+age);
ActionContext ctx=ActionContext.getContext();
System.out.println("req="+ctx.getParameters());
ctx.put("age22", 122);
this.name="background.name";
//servlet api
System.out.println("req="+ServletActionContext.getRequest().getParameterMap());
ServletActionContext.getRequest().setAttribute("name22","ServletActionContext22");
return "xx23";
}
public String myAction(){
System.out.println("myAction:lee.Student="+name+","+age);
return "xx23";
}
publicString myMethod(){
System.out.println("myMethod:lee.Student="+name+","+age);
return"xx23";
}
}
//error.jsp
<%@ pagelanguage="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>
<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>error.jsp</title>
</head>
<body>
this is error.jsp
<% Stringusername=(String)request.getAttribute("name"); %>
<%=request.getAttribute("age22") %>
<%=username %>
<%=request.getAttribute("name22") %>
</body>
</html>
//请求:http://192.168.41.130:8080/Struts2Demo/lee3/student?name=xxx&age=222
4.4.7动态指定方法:在前端动态指定Action的方法
目标:由前端动态指定action调用的方法。
原理:使用action!method指定动态方法,由struts2识别。
流程:后台开启动态方法,实现动态方法。前台指定请求动态方法。
方法:
设置struts2开启动态方法功能:在struts.xml中设置开关
<constantname="struts.enable.DynamicMethodInvocation"value="true"/>
实现动态action:在action类中实现。要求与execute()方法相似。
请求action的方法:actionName!methodName。
示例:
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constantname="struts.enable.DynamicMethodInvocation"value="true"/>
<package name="lee2" namespace="/lee3"extends="struts-default">
<action name="carInfo"class="lee.CarInfoAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
<action name="student"class="lee.Student">
<result name="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
</action>
</package>
</struts>
//Student.java
package lee;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionContext;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
System.out.println("lee.Student="+name+","+age);
ActionContext ctx=ActionContext.getContext();
System.out.println("req="+ctx.getParameters());
ctx.put("age22", 122);
this.name="background.name";
//servlet api
System.out.println("req="+ServletActionContext.getRequest().getParameterMap());
ServletActionContext.getRequest().setAttribute("name22","ServletActionContext22");
return "xx23";
}
publicString myAction(){
System.out.println("myAction:lee.Student="+name+","+age);
return "xx23";
}
}
//error.jsp
<%@ pagelanguage="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>
<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>error.jsp</title>
</head>
<body>
this is error.jsp
<% Stringusername=(String)request.getAttribute("name"); %>
<%=request.getAttribute("age22") %>
<%=username %>
<%=request.getAttribute("name22") %>
</body>
</html>
//请求:http://192.168.41.130:8080/Struts2Demo/lee3/student!myAction?name=xxx&age=222
4.4.8Action通配符批量设置
Action中可以使用*作为通配符(代表一个或多个字符),匹配结果由{N}表示第N个*。
如果有多个action能够匹配,则调用先搜索到的。
示例:使用通配符,处理多个相似action。
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee2" namespace="/lee3"extends="struts-default">
<action name="carInfo"class="lee.CarInfoAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
<action name="student" class="lee.Student">
<resultname="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
</action>
<actionname="*My" class="lee.Student" method="{1}">
<resultname="success">/success.jsp</result>
<result name="xx23">/error.jsp</result>
</action>
</package>
</struts>
//Student.java
package lee;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionContext;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
System.out.println("lee.Student="+name+","+age);
ActionContext ctx=ActionContext.getContext();
System.out.println("req="+ctx.getParameters());
ctx.put("age22", 122);
this.name="background.name";
//servlet api
System.out.println("req="+ServletActionContext.getRequest().getParameterMap());
ServletActionContext.getRequest().setAttribute("name22","ServletActionContext22");
return "xx23";
}
public String myAction(){
System.out.println("myAction:lee.Student="+name+","+age);
return "xx23";
}
public String myMethod(){
System.out.println("myMethod:lee.Student="+name+","+age);
return "xx23";
}
}
//error.jsp
<%@ pagelanguage="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>
<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>error.jsp</title>
</head>
<body>
this is error.jsp
<% String username=(String)request.getAttribute("name");%>
<%=request.getAttribute("age22") %>
<%=username %>
<%=request.getAttribute("name22") %>
</body>
</html>
//请求:http://192.168.41.130:8080/Struts2Demo/lee3/myActionMy?name=xxx&age=222
4.4.9默认Action:default-action-ref
目标:所有没有指定action的请求,将自动调用默认action。
原理:设置默认action,无相符的action将调用默认action。
流程:先定义<default-action-ref name="实际action的name"【class=”默认action的处理类”】/>,再定义实际action或实现默认action处理类。
注意:默认action必须在实际action之前定义。
注意:
示例:
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee2" namespace="/lee3"extends="struts-default">
<default-action-refname="student"/>
<action name="carInfo"class="lee.CarInfoAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
<action name="student"class="lee.Student">
<resultname="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
</action>
<action name="*My"class="lee.Student" method="{1}">
<resultname="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
</action>
</package>
</struts></struts>
//Student.java
package lee;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionContext;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
System.out.println("lee.Student="+name+","+age);
ActionContext ctx=ActionContext.getContext();
System.out.println("req="+ctx.getParameters());
ctx.put("age22", 122);
this.name="background.name";
//servlet api
System.out.println("req="+ServletActionContext.getRequest().getParameterMap());
ServletActionContext.getRequest().setAttribute("name22","ServletActionContext22");
return "xx23";
}
public String myAction(){
System.out.println("myAction:lee.Student="+name+","+age);
return "xx23";
}
public String myMethod(){
System.out.println("myMethod:lee.Student="+name+","+age);
return "xx23";
}
}
//error.jsp
<%@ pagelanguage="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>
<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>error.jsp</title>
</head>
<body>
this is error.jsp
<% Stringusername=(String)request.getAttribute("name"); %>
<%=request.getAttribute("age22") %>
<%=username %>
<%=request.getAttribute("name22") %>
</body>
</html>
//请求:http://192.168.41.130:8080/Struts2Demo/lee3/myActionMy?name=xxx&age=222
4.4.10Action的默认处理类:default-class-ref
目标:action不指定处理类时,自动调用默认的处理类。
原理:默认的处理类是ActionSupport,通过<default-class-ref/>可以指定自定义类。
流程:设置<default-class-ref/>,创建处理类。
示例:
//mystruts-1.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee2" namespace="/lee3"extends="struts-default">
<default-class-refclass="lee.Student"/>
<actionname="myXX">
<resultname="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
</action>
<action name="carInfo"class="lee.CarInfoAction">
<result name="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
<action name="student"class="lee.Student">
<resultname="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
</action>
<action name="*My" class="lee.Student"method="{1}">
<resultname="success">/success.jsp</result>
<resultname="xx23">/error.jsp</result>
</action>
</package>
</struts>
//Student.java
package lee;
importorg.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
System.out.println("lee.Student="+name+","+age);
ActionContext ctx=ActionContext.getContext();
System.out.println("req="+ctx.getParameters());
ctx.put("age22", 122);
this.name="background.name";
//servlet api
System.out.println("req="+ServletActionContext.getRequest().getParameterMap());
ServletActionContext.getRequest().setAttribute("name22","ServletActionContext22");
return "xx23";
}
public String myAction(){
System.out.println("myAction:lee.Student="+name+","+age);
return "xx23";
}
public String myMethod(){
System.out.println("myMethod:lee.Student="+name+","+age);
return "xx23";
}
}
//error.jsp
<%@ pagelanguage="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>
<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>error.jsp</title>
</head>
<body>
this is error.jsp
<% Stringusername=(String)request.getAttribute("name"); %>
<%=request.getAttribute("age22") %>
<%=username %>
<%=request.getAttribute("name22") %>
</body>
</html>
//请求:http://192.168.41.130:8080/Struts2Demo/lee3/myXX?name=xxx&age=222
4.4.11事件监听:PreResultListener。
4.4.12异常处理:Exceptio映射。
目标:将异常捕获,然后输出异常信息,并处理结果。
方法:
4.4.12.1 捕获:struts-default.xml默认增加了异常拦截器。
4.4.12.2 映射:struts.xml中使用<exception-mapping>映射异常,将捕获的异常映射到处理结果。
示例:
<action name="*"class="lee.LoginAction" method="{1}">
<exception-mappingexception="java.lang.Exception" result="exception"/>
<resultname="input">/login.jsp</result>
<resultname="error">/error.jsp</result>
<resultname="success">/Welcome.jsp</result>
<resultname="test">/test.jsp</result>
<resultname="exception">/exception.jsp</result>
</action>
4.4.12.3 输出显示:jsp中使用异常标签显示。
异常信息本身:<s:property value=”exception”/>
堆栈:<s:property value=”exceptionStack”/>
异常信息文本:<s:property value=”exception.message”/>
示例:
<%@ pagelanguage="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<%@ taglibprefix="s" uri="/struts-tags" %>
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>Catch AnException</title>
</head>
<body>
exception=<s:propertyvalue="exception"/><br/>
*********************************************<br/>
stack=<s:property value="exceptionStack"/><br/>
*********************************************<br/>
message=<s:property value="exception.message"/>
</body>
</html>
5 约定:0配置。
6 标签