Struts2知识汇总一

使用Struts2需要的配置:

使用Strut2,必须要再web.xml中为Strut2配置过滤器(只有这样才能使用Strut2框架的内容)
其中的class名称不同的版本可能名字不一样。
(以下2.2.3版本可用)

<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>

使用Strut2还需要定义一个struts.xml文件
Struts标签中需要定义一个package。
package属性解读:
name:为了区分action,可以是任意字符串。
namespace:命名空间,其实是个虚拟路径,如果为/user,则访问包内的action都要加上这个路径,
如果为/,表示访问不需要加上虚拟路径。虚拟路径,可以存在或者不存在,只是一个访问匹配而已,可以当成是一个访问前缀字符串,一般配置为/。
extends:一般值为struts-default
然后再package内部是action配置
action属性解读:
name:表示action的资源名称,相当于servlet中的url-pattern
class:action的完整类名

如果action中有多个方法,每个方法都要配置一个action,这种操作很麻烦,可以使用动态方法
此实例环境为2.3.8
再package外struts添加几个contant标签:
打开调试模式和动态方法启动

<constant name="struts.devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>

最后action的name中后缀加上_*号,method改成{1}

<action name="action_*" class="" method="{1}"></action>

其中 * 表示通配符,method中的{1}表示在请求中匹配到的第一个 * ,当接收到请求时,struts对自动将method替换成匹配的第一个通配符,从而实现动态action,也可以支持多个 * 号

这样请求为action_method1或者为action!method1时,就会调用method1。

但是这种方法容易暴露方法名称,会有安全问题。

用于定义Strut中URL和类(Action)之间的映射关系
Action包含URL,类地址,执行方法,返回结果result(页面跳转)

Struts2中编码问题:

在web.xml中的filter里添加上:

<init-param>
	<param-name>encoding</param-name>
	<param-value>UTF-8</param-value>
</init-param>
Struts2中的ActionSupport:

如果没用指定class,则默认使用Struts提供的Action support类
Strut2使用Action用来取代Servlet
使用Strut2就不能使用Servlet
Strut提供类ActionSupport,但并不是必须使用,只是一个规范。
只要作为Action类(单纯的java类)符合JavaBean规范,有set和get和字段,有个无参返回字符串的方法(Strut2默认使用execut,也可以自己定),就能使用。

ActionSupport实现了六个接口(Action的接口)
Action接口如下:

public interface Action {
   public static final String SUCCESS = "success";
   public static final String NONE = "none";
   public static final String ERROR = "error";
   public static final String INPUT = "input";
   public static final String LOGIN = "login";
   public String execute() throws Exception;
}
//返回的字符串可以使用这些表示

ActionSupport实现的接口:Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable
Action:
提供了一些常量和一个execute方法的定义
Validateable:
需要对字段进行验证时,可以实现该接口,该接口定义了validate方法
ValidationAware:
如果需要接收错误信息时,可实现该接口。错误有字段级别和action级别。
TextProvider,LocaleProvider:
国际化时用到达接口

在手工完成验证,国际化、消失错误信息,推荐继承ActionSupport类

Struts2中拦截器:

拦截器(在action中设置):和过滤器相似
当用户请求到达时,该Filter会过滤用户的请求。当请求转入Struts2框架处理时会先经过一系列的拦截器,然后再到Action。Struts2对用户的每一次请求都会创建一个Action,Action是线程安全的。
自定义拦截器:
需要在struts.xml中声明,名称和映射的类
拦截器过多难以管理,可以使用拦截器堆栈

Struts2中xml的result参数:

在struts.xml设置result参数相当于取代了servlet中跳转的操作
Struts2并不固定使用jsp作为返回值,可以设置其他类型
可以用param标签设置本地资源

<result name="success" type="freemarker">
	<param name="location">/hello.fm</param>
</result>

如果使用简写:
则相当于使用JSP(type = dispatcher)
相当于servlet中的请求转发

<result name="success">/HelloWorld.jsp</result>
---------------
<!--相当于如下,两者效果一致-->
---------------
<result name="success" type="dispatcher">/HelloWorld.jsp</result>

也有类似重定向的设置(type = redirect)

<result name="success" type="redirect">/HelloWorld.jsp</result>

type为redirect时,也可以重定向到action

如果设置为chain,则转发到action。
result中可以配置参数,使用以下标签:

有的标签可以带有参数标签,参数标签的name都是struts内部规定好的,可以到struts-doc中查看参数信息

<param name=""></param>
Struts2中的值栈:

OGNL:是一个标签库,用来取出设置在值栈中的属性。
Struts构建了一个ActionContext映射以供OGNL使用:

Struts2中的ActionContext:

在Action里,可以通过ActionContext获得值栈。
JSP页面中,大部分标签可以通过name属性从值栈中获取信息
属性必须要有从值栈取出的过程(通过标签),否则Action中的属性无法取得

存放在值栈中的数据总是可用的:

在Action里获取值栈:

ValueStack stack = ActionContext.getContext().getValueStack();

Action对象在值栈中总是可用的,因此如果你的Action对象有x和y属性,你可以随时使用。

OGNL使用实例:

在Struts中使用OBNL必须要写在Struts标签里
声明标签:

<%@taglib prefix="s" uri="/struts-tags"%>

例如使用标签(OGNL):

<!---->

<!--从值栈中获取值-->
<s:property value="value"/>

<!--定义集合-->
<s:set name="list" value="{'1','2','3'}"/>

<!--迭代-->
<!--id,value可以省略-->
<s:iterator value="list" id="item">
	<s:property value="item"/>
</s:iterator>

<!--定义map类型数据-->
<s:set name="list" value="#{'1':'a','2':'b','3':'c'}">

<!--迭代map类型数据-->
<s:iterator value="#list">
	<s:property value="key"/> : <s:property value="value"/>
</s:iterator>

Struts2中web对象获取:

通过Struts提供的ServletActionContext类获取web对象:
但是耦合性低,不容易调试

HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ServletContext application = ServletActionContext.getServletContext();
PageContext pagecontext = ServletActionContext.getPageContext();

//取出方式
<s:property value="#request.x"/>

添加#的目的:struts将存放在值栈里的对象视为根对象,原生web对象不存在值栈里,不视为根对象,所以需要使用#

通过ActionContext可以获得web对象—Map依赖容器方式:

ActionContext context = ActionContext.getContext();
//获取request
Map<String,Object> request = (Map<String,Object>) context.get("request");
Map<String, Object> session = context.getSession();
Map<String, Object> application = context.getApplication();
//这样做的有点时调试的时候可以不用启动服务器,实现低耦合

通过IoC访问访问Servlet对象——Map IoC方式:
在Struts2框架中,通过IoC方式将Servlet对象注入到Action中,需要在
Action中实现以下接口:
(1)org.apache.struts2.interceptor.RequestAware
该接口有void setRequest(Map map)方法,实现该方法的Action可访问
HttpSession对象。
(2)org.apache.struts2.interceptor.SessionAware
该接口有void setSession(Map map)方法,实现该方法的Action可访问
HttpSession对象。
(3)org.apache.struts2.interceptor.ApplicationAware
该接口有void setApplication(Map map)方法,实现该方法的Action可访问
HttpSession对象。
这种实现方式需要自己设置session等对象,对象类型扩展自AbstractMap的类(可以看作是一个map),但是功能比map多

通过IoC访问访问Servlet对象——Servlet IoC方式
在Struts2框架中,通过IoC方式将Servlet对象注入到Action中,需
要在Action中实现以下接口:
(1)org.apache.struts2.interceptor.ServletContextAware
该接口有void setServletContext(ServletContext servletContext)方法,
实现该接口的Action可以直接访问ServletContext对象。
(2)org.apache.struts2.interceptor.ServletRequestAware
该接口有void setServletRequest(HttpServletRequest ruquest),实现
该接口的Action可以直接访问HttpServletRequest对象。
(3)org.apache.struts2.interceptor.ServletResponseAware
该接口有void setServleResponse (HttpServletResponse response),实
现该接口的Action可以直接访问HttpServletResponse对象。

这种方式时得到一个真正的servlet对象,依赖容器

Struts2应答的请求后缀:

如何查看Struts支持的扩展名?
到org.apache.struts2的default.properties
该文件配置了一些应用的常量,比如动态方法调用开关,文件上传大小等等
其中可以看到:
struts.action.extension=action,
表示默认支持action和无后缀的请求。
如何添加支持的扩展名?
在struts.xml添加contant标签配置常量:

Struts2中的文件上传:

Struts2中的文件上传基于html的表单:

<form action="upload" method="post" enctype="multipart/form-data">
   <label for="myFile">Upload your file</label>
   <input type="file" name="myFile" />
   <input type="submit" value="Upload"/>
</form>

当文件上传时,它通常会存储在临时目录中,然后Action类应对其进行处理或移动到固定目录中,以确保数据不会丢失。
Struts2在文件上传时需要使用拦截器FileUpload
只要上传文件设置了过滤器,过滤器会自动提供属性到值栈中

[文件名参数] file类型 - 这是用户已上传的实际文件。
[文件名参数] ContentType String类型 - 这是上传的文件的内容类型。
[文件名参数] FileName String类型 - 这是上传的文件的名称。

例如:上传的文件名称为myFile:
过滤器可以分析上传文件并为action提供如下值:
myFile(File)
myFileContentType(String)
myFileFileName(String)
由于上传的文件默认实在临时目录里,所以要及时转存到安全路径:
这是要是使用Struts2提供的FileUtils.copyFile

File destFile  = new File(destPath, myFileFileName);
FileUtils.copyFile(myFile, destFile);
Strut2中的标签库:

表单标签示例:

<%@ taglib prefix="s" uri="/struts-tags"%>
	<s:form action="" method="post">
		<s:textfield name="name" label="name" size="20"></s:textfield>
		<s:textfield name="age" label="age" size="20"></s:textfield>
		<s:submit value="submit" name="submit" align="left"></s:submit>
	</s:form>

表单标签:
其中action和method和html中的表单是一样的
<s:textfield>表示文本输入框,size为长度
<s:submit>为提交按钮

向页面传递数据:

<s:addActionError/>
<s:addActionMessage/>

二者仅语义不同

定义对象标签:

<!--name:类路径,var:实例名称-->
<s:bean name="" var="">
	<!--name:参数名,value:参数值-->
	<s:param name="" value=""/>
	<s:param name="" value=""/>
</s:bean>

格式化时间(需要Date对象):

<!--name:实例名称,format:字符串格式-->
<s:date name="" format="" >

直接运行action类标签:

<!--name:action请求名称,executeResult:是否执行结果-->
<s:action name="" executeResult=""></s:action>

更多标签官网查询。

Struts2中的验证框架:

ActionSupport中有一个validate方法。
该方法会自动在execute方法前调用,可以使用这个方法对客户端传递过来的数据进行验证。
使用addFieldError()方法可以将错误信息根据name属性添加到表单上。
addFieldError方法接受两个参数,第一个是出错时应用的form字段名称,第二个是在form字段上方显示的错误信息。
使用验证框架时,需要在struts.xml中添加result结果类型input,该结果表示在触发addFieldError方法后转跳的页面。(一般为出错的表单页面)

使用XML验证:
使用XML会使代码耦合度降低:
在action类旁边放置一个xml文件
xml文件需要命名为’[action-class]’-validation.xml
例如Action的名称为:Abc
则xml文件名称为:Abc-validation.xml
xml示例(为name属性为number的字段添加范围验证):

<validators>
	<field name="number">
		<field-validator type="int">
			<param name="min">10</param>
			<param name="max">50</param>
			<message>
				Number must be in between 10 and 50
			</message>
		</field-validator>
	</field>
</validators>

使用XML还有更多灵活的验证方法,可以到官网查看。

发布了68 篇原创文章 · 获赞 12 · 访问量 5213

猜你喜欢

转载自blog.csdn.net/qq_40963076/article/details/104523855
今日推荐