您的位置:首页 > 编程语言 > Java开发

浅谈Struts2下

2015-06-11 21:32 441 查看
计应134(实验班) 张人川

一、文件上传

在WEB-INFO/lib下加入commons-flileupload-1.2.1.jar,commons-io-1.3.2.jar

把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 uploadImagContentType; //得到文件的类型
private String uploadImag FileName; //得到文件的名字
getter setter
.
.
.
public String upload() throws Exception{
String realpath=ServletActionContext.getServletContext.getRealPath(“/image
“);
if(uploadImage!=null){
File file=new File(realpath);
if(!file.exists()) file.mkdirs();
FileUtils.copyFile( uploadImage , new File(
file , uploadImageFileName));
ActionContext.getContext().put(“message”,”上传成功”);
}
return “success”;
}
}

二、自定义拦截器
需要实现com.opensymphony.xwork2.interceptor.Interceptor接口
public String intercept(ActionInvocation invocation) throws Exception{
if(sesion存在用户){
String result=invocation.invoke(); //返回Action所调方法的名称
}else{
return “logon”;
}
}
在package里写interceptors
<interceptors>
<interceptor name=”permission” class=”com.icss.interceptro.PermissionInterceptor”/>
<interceptor-stack name=”permissionStack”>
<interceptor-ref name=”defaultStack”/>
<interceptor-ref name=”permission”/>
</interceptor-stack>
</interceptors>
Action里写
<interceptor-ref name=”permissionStack”/>

如果希望包下所有的Action都使用自定义拦截器,可以通过<default-interceptor-ref name=””/>把它定义为默认拦截器;注意每个包只能指定一个默认拦截器,且如果该包下的某个Action显示指定了某个拦截器,则默认拦截器不会起作用;

三、输入校验
采用手工编写代码实现
对所有方法进行校验
Action继承ActionSupport重写validate()方法
public class PersonAction extends ActionSupport{
private String username;
private String mobile;
getter setter;
.
.
.
public void validate(){
if(this.username==null || “”.equals(this.username.trim())){
this.addFieldError(“username”,”用户名不能为空”);
}
if(this.mobile==null || “”.equeal(this.mobile.trimm())){
this.addFileError(“mobile”,”手机号不能为空”);
}else{
if(!Pattern.compile(“^1[358]\\d{9}$”).matcher(this.mobile)
.matches()){
This.addFieldError(“mobile”,”手机号格式不正确”);
}
}
}
}
//验证失败返回input视图所以<result name=”input”></result>
<s:fieldError/>
对某个方法进行校验
提供validateXxx(),校验xxx()方法
基于xml的输入校验
对所有方法进行校验
Action继承ActionSupport,并将校验文件和Action类放在同一包下,
文件的取名格式为:ActionClassName-validation.xml
<validators>
<field name=”username”>
<field-validator type=”requiredstring”>
<param name=”trim” >true</param>
<message>用户名不能为空</message>
</field-validator>
</field>
<validators>
关于type属性的值见com.opensymphony.xwork2.validator.validators下
的default.xml中;
校验器的例子:
Email:
<field-validator type=”email”>
<message>电子邮箱地址无效</message>
</field>
Regex
<field-validator type=”regex”>
<param name=”expression”>![CDATA[^1[358]\D{9}$]]</param>
<message>手机号格式不正确</message>
</field>
Int
<field-validator type=”int”>
<param name=”min”>1</param>
<param name=”max”>150</param>
<message>年龄必须在1-150之间</message>
</field>
OGNL
<field-validator type=”fieldexpression”>
<param name=”expression”>![CDATA[imagefile.length
()<=0]]</param>
<message>文件不能为空</message>
</field>
对指定方法进行校验
ActionClassName-ActionName-validation.xml
<action name=”user-*” method=”{1}”></action>
//提交哪个对哪个方法进行哪个方法进行校验;

四、输入校验的流程

类型转换器对请求参数进行类型转换,并把转换后的值赋给action中的属性

如果在执行类型那个转换的过程中出现异常,系统会将异常信息保存到ActionContext,

conversionError拦截器将异常信息添加到fieldErrors里;
系统通过反射技术先调用action中的validateXxx()方法
在调用validate()方法

如果系统中的fieldErrors存在错误信息,系统将发送名称为input的视图

五、国际化
baseName_en_US.properties
baseName_zh_CN.properties
配置全局资源和国际化信息
struts.xml.
<constant name=”struts.custom.i18n.resources” value=” baseName”/>
Jsp
<s:text name=””/> //name为资源文件中的key
<s:text name=”welcome”>
<s:param>wanglei</s:param>
<s:param>study</s:param>
</s:text>
在Action类中可以继承ActionSupport,使用getText(“key”)得到国际化信息
getText(“welcome”,new String[]{“liming”,”study”});
资源文件
Key=value
welcome={0},欢迎来到XXXX{1}
配置包范围的全局化资源文件
package_en_US.properties
package_zh_CN.properties
package为固定写法,而不是包名
Action范围资源文件
在Action类所在的路径,放置ActionClassName_en_US.properties,
ActionClassName_zh_CN.properties
国际化—Jsp中直接访问某个资源文件
<s:i18n name=”baseName”>
<s:text name=”welcome”/>
</s:i18n>
访问com.icsss.action包下的资源文件
<s:i18n name=”com/icss/action/package”>
<s:text name=”welcome”>
<s:param>小张</s:param>
</s:text>
</s:i18n>

六、日期类型
xxxx-xx-xx形式写年月日可以直接转换为java.utli.Date;

七、类型转换器
局部类型转化器(com.opensymphony.xwork2.conversion.impl.DefaultTypeConberter)
public class DateTypeConverter extends DefaultTypeConvert{
public object convertValue(Map<String , Object> context , Object value ,Class toType){
SimpleDateFormate dateFormat=new SimpleDateFormat(“yyyy/MM/dd”);
try{
if(toType==Date.class){
String[] params=(String[])value;
return dateFormat.parse(params[0]);
}else if(toType==String.class){
Date date=(Date)value;
return dateFormat.format(date);
}
}catch(ParseException e){
return null;
}
}
}
在Action类所在的包下放置ActionClassName-conversion.properties
在properties文件中的内容为:
属性名称=类型转换器的去类名称
birthday=com.icss.conversion.DateTypeConverter
全局类型转换器
xwork-conversion.properties
内容为:待转换的类型=类型转换器的全名称
Java.util.Date=com.icss.conversion.DateConverter

八、访问或添加request/session/application属性
ActionContext ctx=ActionContext.getContext();
ctx.getApplication().put(); //往ServletContext或Application属性里放置
ctx.getSession(0.put();
ctx.put(); //往request里放值

九、获取request/session/application对象
方法一:
通过ServletActionContext类直接获取
HttpServletRequest request=ServletActionContext.getRequest();
ServletContext servletContext=ServletActionContxt.getServletContext();
HttpServletResponse respone=ServletActionContext.getResponse();
方法二:
实现指定接口,由Struts框架运行时注入:
public class HelloWorldAction implement ServletRequestAware,ServletResponseAware,
ServletContxtAware{
private HttpServletRequest request;
private ServletContext servletContext;
private HttpServletResponse respone;
setter
.
.
.
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: