HttpServletResponse response = ServletActionContext.getResponse();
上传文件
public String doAddLogo(){if(ValidateUtil.isValid(logoPhotoFileName)){//1.实现上传// /upload文件夹真实路径String dir = sc.getRealPath("/upload");//扩展名String ext = logoPhotoFileName.substring(logoPhotoFileName.lastIndexOf("."));//纳秒时间作为文件名long l = System.nanoTime();File newFile = new File(dir,l + ext);//文件另存为logoPhoto.renameTo(newFile);//2.更新路径surveyService.updateLogoPhotoPath(sid,"/upload/" + l + ext);}return "designSurveyAction" ;}
上传文件大小
<interceptor-ref name="defaultStack">
<param name="modelDriven.refreshModelBeforeResult">true</param>
<!-- 文件大小 -->
<param name="fileUpload.maximumSize">60000</param>
<!-- 文件扩展名 -->
<param name="fileUpload.allowedExtensions">.jpg,.jpeg,.png,.bmp,.gif</param>
<!-- 文件内容类型 -->
<param name="fileUpload.allowedTypes">image/jpg,image/jpeg,image/pjpeg,image/png,image/gif,image/bmp</param>
</interceptor-ref>
truts.multipart.maxSize掌控整个项目所上传文件的最大的Size;
1.struts.multipart.maxSize掌控整个项目所上传文件的最大的Size。超过了这个size,后台报错,程序处理不了如此大的文件。fielderror里面会有如下的 提示:the request was rejected because its size (16272982) exceeds the configured maximum (9000000)
2.fileUpload拦截器的maximumSize属性必须小于struts.multipart.maxSize的值。
struts.multipart.maxSize默认2M,当maximumSize大于2M时,必须设置struts.multipart.maxSize的值大于maximumSize。
3.当上传的文件大于struts.multipart.maxSize时,系统报错
当上传的文件在struts.multipart.maxSize和maximumSize之间时,系统提示:
File too large: file "MSF的概念.ppt" "upload__5133e516_129ce85285f__7ffa_00000005.tmp" 6007104
当上传的文件小于maximumSize,上传成功。
对错误消息国际化
1.创建SurveyAction.properties
[struts-core-x.x.x.jar/org.apache.struts/struts-message.properties]
struts.messages.error.file.too.large=The file is to large to be uploaded: {0} "{1}" "{2}" {3}
struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}
2.创建临时文件1.txt(记事本编写(gb2312))
struts.messages.error.file.too.large=文件太大!
struts.messages.error.content.type.not.allowed=类型不对!
struts.messages.error.file.extension.not.allowed=扩展名不符!
3.对1.txt进行转码(ascii码)
cmd
d:
cd xxxx
native2ascii -encoding gb2312 1.txt 2.txt
4.刷新项目,产生一个2.txt文件
5.删除1.txt文件
6.重命名2.txt --> SurveyAction_zh_CN.properties
ActionContext、ServletActionContext和ServletContext
ActionContext是Action的上下文,主要是一些值。
ServletActionContext提供了servlet接口,操作Cookies等时候会用到。
ServletContext是整个应用的环境,可以获得web.xml里的参数和值。
Struts2获取Session的三种方式
1、Map<String,Object> map = ActionContext.getContext().getSession();
2、HttpSession session = ServletActionContext.getRequest().getSession();
3、让Action实现SessionAware接口,并实现public void setSession(Map<String, Object> session) {} 方法,Struts2会在实例化Action后调用该方法,通过方法参数将Session对象注入进来。如果我们想获取Session,我们可以定义成员变量,接收注入进来的Session对象。
三种方式的比较:
返回类型的对比:1,3获取的Session类型是Map<String,Object>类型,2获取的类型是HttpSession。
获取方式对比:
1,2是我们主动获取Session,3是采用注入的方式自动注入Session,这是被动的。
推荐使用3来创建Session,因为它更为灵活而且符合面向接口编程的思想。
2、HttpSession session = ServletActionContext.getRequest().getSession();
3、让Action实现SessionAware接口,并实现public void setSession(Map<String, Object> session) {} 方法,Struts2会在实例化Action后调用该方法,通过方法参数将Session对象注入进来。如果我们想获取Session,我们可以定义成员变量,接收注入进来的Session对象。
三种方式的比较:
返回类型的对比:1,3获取的Session类型是Map<String,Object>类型,2获取的类型是HttpSession。
获取方式对比:
1,2是我们主动获取Session,3是采用注入的方式自动注入Session,这是被动的。
推荐使用3来创建Session,因为它更为灵活而且符合面向接口编程的思想。
转发重定向
struts2校验方法:response.sendRedirectory()
request.getDispacher(“index.jsp”).forward(request, response);
1、通过覆盖ActionSupport类的validate方法即可在自己的Action类中校验输入项的值。序列化的时候
2、添加UserAction-validation.xml内容public void validate() { //1.非空 if(!ValidateUtil.isValid(model.getEmail())){ addFieldError("email", "email是必填项!"); } f(!ValidateUtil.isValid(model.getPassword())){ addFieldError("password", "password是必填项!"); } if(!ValidateUtil.isValid(model.getNickName())){ addFieldError("nickName", "nickName是必填项!"); } if(hasErrors()){ return ; } //2.密码一致性 if(!model.getPassword().equals(confirmPassword)){ addFieldError("password", "密码不一致!"); return ; } //3.email占用 if(userService.isRegisted(model.getEmail())){ addFieldError("email", "email已占用!"); } }
<validator type="requiredstring"> <param name="fieldName">username</param> <message>用户名不能为空!</message> </validator>
3、校验动作类中的指定方法,只要把上面的校验文件名改成UserAction-user_add-validation.xml即可。
其中user_add匹配struts.xml文件中的user_*
4、
UserAction-user_regist-validation.xml
<field name="name">
<field-validator type="requiredstring">
<message>姓名不能为空!</message>
</field-validator>
</field>
jsp文件中:<s:fielderror fieldName="name"/>action中的:this.addActionError(“”);
jsp中:<s:actionerror />
//transient:临时的
private transient Survey survey;
截取文件扩展名:
String ext = logoPhotoFileName.substring(logoPhotoFileName.lastIndexOf("."));
将超链接的参数部分滤掉 ?xxxx
actionName = actionName.substring(0, actionName.indexOf("?"));
poi直接输出流返回:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write( baos);
return new ByteArrayInputStream(baos.toByteArray());
<action name="CollectionSurveyAction" class="collectionSurveyAction">
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="inputName">is</param>
<param name="bufferSize">1024</param>
</result>
</action>
拦截器权限过滤:
获得ServletContex方法:public String intercept(ActionInvocation arg0) throws Exception { BaseAction action = (BaseAction) arg0.getAction(); ActionProxy proxy = arg0.getProxy(); String ns = proxy.getNamespace(); String actionName = proxy.getActionName(); if(ValidateUtil.hasRight(ns, actionName, ServletActionContext.getRequest(),action)){ return arg0.invoke(); } return "login" ; }
1、implements ServletContextAwar
//注入ServletContext
public void setServletContext(ServletContext servletContext) {
this.sc = servletContext ;
}
2、HttpSession session = req.getSession();
ServletContext sc = session.getServletContext();
AJAX
public String findByName() throws IOException { User existUser = userService.findByUsername(user.getUsername()); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); if (existUser != null) { // 查询到该用户:用户名已经存在 response.getWriter().println("<font color='red'>用户名已经存在</font>"); } else { // 没查询到该用户:用户名可以使用 response.getWriter().println("<font color='green'>用户名可以使用</font>"); } return NONE; }
文件上传
private File upload;
private String uploadFileName;
private String uploadContentType;
只需要写setter方法即可
表单中的name=”upload”
FileUtils.copyFile(upload, diskFile); // import org.apache.commons.io.FileUtils;