Struts2转换器、拦截器的简单介绍
自定义类型转换器:java.util.Date类型的属性可以接收格式为2009-07-20的请求参数值。但如果我们需要接收格式为20091221的请求参数,我们必须定义类型转换器,否则struts2无法自动完成类型转换。
import java.util.Date;
public class HelloWorldAction {
private Date createtime;
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
}
public class DateConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map context, Object value, Class toType) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
try {
if(toType == Date.class){//当字符串向Date类型转换时
String[] params = (String[]) value;// Request.getParameterValues()
return dateFormat.parse(params[0]);
}else if(toType == String.class){//当Date转换成字符串时
Date date = (Date) value;
return dateFormat.format(date);
}
} catch (ParseException e) {}
return null;
}
}
将上面的类型转换器注册为局部类型转换器:
在Action类所在的包下放置ActionClassName-conversion.properties文件,ActionClassName是Action的类名,后面的-conversion.properties是固定写法,对于本例而言,文件的名称应为HelloWorldAction-conversion.properties 。在properties文件中的内容为:
属性名称=类型转换器的全类名
对于本例而言, HelloWorldAction-conversion.properties文件中的内容为:
createtime= cn.itcast.conversion.DateConverter
自定义全局类型转换器:
将上面的类型转换器注册为全局类型转换器:
在WEB-INF/classes下放置xwork-conversion.properties文件 。在properties文件中的内容为:
待转换的类型=类型转换器的全类名
对于本例而言, xwork-conversion.properties文件中的内容为:
java.util.Date= cn.itcast.conversion.DateConverter
访问或添加request/session/application属性
public String scope() throws Exception{
ActionContext ctx = ActionContext.getContext();
ctx.getApplication().put("app", "应用范围");//往ServletContext里放入app
ctx.getSession().put("ses", "session范围");//往session里放入ses
ctx.put("req", "request范围");//往request里放入req
return "scope";
}
JSP:
<body>
${applicationScope.app} <br>
${sessionScope.ses}<br>
${requestScope.req}<br>
</body>
文件上传
第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。
第二步:把form表的enctype设置为:“multipart/form-data“,如下:
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
<input type="file" name="uploadImage">
</form>
第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:
public class HelloWorldAction{
private File uploadImage;//得到上传的文件
private String uploadImageContentType;//得到文件的类型
private String uploadImageFileName;//得到文件的名称
//这里略省了属性的getter/setter方法
public String upload() throws Exception{
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
File file = new File(realpath);
if(!file.exists()) file.mkdirs();
FileUtils.copyFile(uploadImage, new File(file, uploadImageFileName));
return "success";
}
}
多文件上传
第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。
第二步:把form表的enctype设置为:“multipart/form-data“,如下:
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
<input type="file" name="uploadImages">
<input type="file" name="uploadImages">
</form>
第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:
public class HelloWorldAction{
private File[] uploadImages;//得到上传的文件
private String[] uploadImagesContentType;//得到文件的类型
private String[] uploadImagesFileName;//得到文件的名称
//这里略省了属性的getter/setter方法
public String upload() throws Exception{
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
File file = new File(realpath);
if(!file.exists()) file.mkdirs();
for(int i=0 ;i<uploadImages.length; i++){ File uploadImage = uploadImages[i];
FileUtils.copyFile(uploadImage, new File(file, uploadImagesFileName[i]));
}
return "success";
}}
拦截器
Struts2另一核心技术是拦截器,英文名为Interceptor。它原来是WebWork框架中一个很好的支持国际化、校验、类型转换的工具。现在WebWork和Struts合并成Struts2之后,理所当然也成为了Struts2的一部分。
拦截器本身也是一个普通的Java对象,它的功能是动态拦截Action调用,在Action执行前后执行拦截器本身提供的各种各样的Web项目需求。当然也可以阻止Action的执行,同时也可以提取Action中可以复用的部分。
在Struts2中还有个拦截器栈的概念,其实它就是拦截器的一个集合。它把多个拦截器集合起来,按照在栈中配置的顺序执行,特别是针对Action可以拦截相应的方法或者字段。
拦截器示例
public class MyTimerInterceptor extends AbstractInterceptor{
public String intercept(ActionInvocation invocation)
throws Exception {
//预处理工作
long startTime = System.currentTimeMillis();
//执行后续拦截器或Action
String result = invocation.invoke();
//后续处理工作
long execTime = System.currentTimeMillis() - startTime;
System.out.println("The interval time is "+execTime+" ms");
//返回结果字符串
return result;
}
}
Struts 2自带拦截器
Params拦截器
负责将请求参数设置为Action属性
servletConfig拦截器
将源于Servlet API的各种对象注入到Action
fileUpload拦截器
对文件上传提供支持
exception拦截器
捕获异常,并且将异常映射到用户自定义的错误页面
validation拦截器
调用验证框架进行数据验证
workflow拦截器
调用Action类的validate(),执行编码验证
配置拦截器
<package name="packName" extends="struts-default" namespace="/manage">
<interceptors>
<!-- 定义拦截器 -->
<interceptor name="interceptorName" class="interceptorClass" />
<!-- 定义拦截器栈 -->
<interceptor-stack name="interceptorStackName">
<!--指定引用的拦截器-->
<interceptor-ref name="interceptorName|interceptorStackName" />
</interceptor-stack>
</interceptors>
<!--定义默认的拦截器引用-->
<default-interceptor-ref name="interceptorName|interceptorStackName" />
<action name="actionName" class="actionClass">
<!—为Action指定拦截器引用-->
<interceptor-ref name="interceptorName|interceptorStackName" />
<!--省略其他配置-->
</action>
</package> --------------------编程问答--------------------
写片博客多好 --------------------编程问答-------------------- 新手啊,还不知道具体咋用的呢 --------------------编程问答-------------------- 初略发现,定义了拦截器之后没有引用defaultStack ?
补充:Java , Web 开发