Struts2学习笔记(二)

时间:2023-02-26 19:41:51

写在前面

被Struts2的各种奇葩错误整的精神衰弱,改了一下午也不见效果,后来出去跑个步,回来再调试,发现错误都没有了,郁闷。以后改Struts2的错误不再寄希望于Jrebel的自动更新部署了,还是不要怕麻烦,多重启几次服务器,多刷新几次页面,去跑跑步喝喝咖啡,可能柳暗花明就好了吧。

配置自定义拦截器:

public class CheckAuthInterceptor extends MethodFilterInterceptor {
@Override
protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
HttpSession session = ServletActionContext.getRequest().getSession();
Object user = session.getAttribute("user");
if (null == user) {
return "login";
}
return actionInvocation.invoke();
}
}
<package name="p1" namespace="/user" extends="struts-default">
<interceptors>
<interceptor name="CheckAuth" class="com.cheng.web.interceptor.CheckAuthInterceptor"></interceptor>
<interceptor-stack name="myDefaultStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="CheckAuth"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="*" method="{1}" class="com.cheng.web.action.UserAction">
<interceptor-ref name="myDefaultStack">
<param name="CheckAuth.excludeMethods">add,login</param>
</interceptor-ref>
<result name="success" type="redirect">/user/${location}</result>
<result name="input">/WEB-INF/user/{1}.jsp</result>
<result name="login">/WEB-INF/user/login.jsp</result>
<allowed-methods>add,login,index</allowed-methods>
</action>
</package>

多文件上传:

private File[] images;
private String[] imagesContentType;
private String[] imagesFileName;
public String upload() {
String realPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload");
for (int i = 0; i < images.length; i++) {
images[i].renameTo(new File(realPath, imagesFileName[i]));
}
return SUCCESS;
}

文件下载:

InputStream inputStream;
public String download() throws FileNotFoundException {
String realPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload/user.jpg");
inputStream = new FileInputStream(new File(realPath));
return SUCCESS;
}
<result name="success" type="stream">
<param name="inputName">inputStream</param>
<param name="contentType">application/octet-stream</param>
<param name="contentDisposition">attachment;filename=user.jpg</param>
</result>

数据声明式验证:

UserAction-add-validation.xml

<validators>
<field name="user.account">
<field-validator type="requiredstring" short-circuit="true">
<message>用户名不能为空</message>
</field-validator>
</field>
<field name="user.password">
<field-validator type="requiredstring">
<message>密码不能为空</message>
</field-validator>
</field>
</validators>