Struts2总结(二)

2014-11-24 07:23:22 · 作者: · 浏览: 1
private String[] imageFileName;// 得到文件的名称
........
........
........

public String execute() throws Exception {
// 构建真实的存放路径
StringrealPath = ServletActionContext.getServletContext().getRealPath(
"/image");
System.out.println(realPath);
if (image != null) {
for (int i = 0; i < image.length; i++) {
Filesavefile = new File(new File(realPath), imageFileName[i]);
if(!savefile.getParentFile().exists()) {
savefile.getParentFile().mkdirs();
}
FileUtils.copyFile(image[i], savefile);
}
ActionContext.getContext().put("message", "上传成功");

}
return "success";
}

9. 编写自定义拦截器:
1) 继承自Interceptor接口来实现。
[java]
public class PermissionInterceptor implements Interceptor {

public void destroy() {
}

public void init() {
}

public String intercept(ActionInvocation invocation) throws Exception {
Object user = ActionContext.getContext().getSession().get("user");
if(user!=null) return invocation.invoke(); //如果user不为null,代表用户已经登录,允许执行action中的方法
ActionContext.getContext().put("message", "你没有权限执行该操作");
return "success";
}

}


2) 在xml中的配置为:
[html]

class="com.lcq.Interceptor.PermissionInterceptor" />







/WEB-INF/page/message.jsp


method="execute">


10. 对action的所有方法进行输入校验
1) 要进行验证的内容:
[html]



用户名:用户名不能为空

手机号:不能为空,并且要符合手机号的格式1,3/5/8,后面是9个数字




2) 在action中继承ActionSupport重写validate()方法:
[java]
@Override
public void validate() {//对action的所有方法进行校验
if(this.username == null || "".equals(this.username.trim())){
this.addFieldError("username", "用户名不能为空");
}
if(this.mobile == null || "".equals(this.mobile.trim())){
this.addFieldError("mobile", "手机号不能为空");
}else{
if(!Pattern.compile("^1[358]\\d{9}{1}quot;).matcher(this.mobile).matches()){
this.addFieldError("mobile", "手机号格式不对");
}
}


}


3) 在validate方法中将错误信息放在错误集合中,转到input页面,所以在xml中的配置是:
[html]


method="{1}">
/index.jsp
/WEB-INF/page/message.jsp



4) 如果只是对个别的方法进行校验则只要改正validate方法为validateXxxx()就行,其中Xxxx是要校验的方法的名称。
[java]
public void validateUpdate() {//对action的update()方法进行校验
if(this.username == null || "".equals(this.username.trim())){
this.addFieldError("username", "用户名不能为空");
}
if(this.mobile == null || "".equals(this.mobile.trim())){
this.addFieldError("mobile", "手机号不能为空");
}else{
if(!Pattern.compile("^1[358]\\d{9}{1}quot;).matcher(this.mobile).matches()){
this.addFieldError("mobile", "手机号格式不对");
}
}


}


11. 基于xml的输入校验
1) 只要在要校验的action所在包下建立相应的action的xml验证文件即可,在xml中编写:
2) 如果只是对action中的指定方法进行校验则只要修改xml的文件名即可,修改为PersonAction-person-manage_update-validation.xml则该文件只对action中的update方法进行校验
[html]



true