表单提交数据的验证
硬编码
使用 java 代码进行验证配置
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.interceptor.validation.SkipValidation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class UserAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
@SkipValidation
public String register() throws Exception {
return "success";
}
@Override
public User getModel() {
return user;
}
@Override
public void validate() {
if (StringUtils.isEmpty(user.getUsername())) {
this.addFieldError("username", "账号不能为空!");
}
}
}
同动作类下,如果不想验证该方法
使用注解 @SkipValidation 跳过验证
@SkipValidation
public String query() {
return SUCCESS;
}
软编码
使用配置文件 xml 或者 properties 进行验证配置
<validators>
<field name="username">
<field-validator type="requiredstring">
<message>用户名不能为空message>
field-validator>
field>
validators>
跳过验证方式二(指定要被验证的动作方法) 命名规范:小驼峰 validate + 要验证的方法名(首字母大写)
相当于 struts 在验证拦截时,会扫描整个动作类中的方法,查找是否有 validate 开头的方法和名字后面的动作方法
有则进行拦截
public void validateQuery() {
if (StringUtils.isEmpty(user.getUsername())) {
this.addFieldError("username", "空!");
}
}
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@SuppressWarnings("serial")
public class ValidationAction extends ActionSupport implements ModelDriven<Customer> {
private Customer customer = new Customer();
@Override
public Customer getModel() {
return customer;
}
public String registerCustomer() throws Exception {
return "success";
}
}
<validators>
<field name="username">
<field-validator type="requiredstring">
<message>请输入用户名message>
field-validator>
field>
<field name="age">
<field-validator type="int">
<param name="max">60param>
<param name="min">18param>
<message>你年龄不符合要求message>
field-validator>
field>
<field name="email">
<field-validator type="email">
<message>邮箱不对呀message>
field-validator>
field>
<field name="password">
<field-validator type="requiredstring">
<message>密码不能为空message>
field-validator>
<field-validator type="stringlength">
<param name="maxLength">8param>
<param name="minLength">3param>
<message>密码长度不符合要求message>
field-validator>
field>
<field name="url">
<field-validator type="url">
<message>url不符合要求message>
field-validator>
field>
<field name="gender">
<field-validator type="required">
<message>必须选择性别message>
field-validator>
field>
<validator type="expression">
<param name="expression">
password == repassword
param>
<message>两次密码不一致message>
validator>
validators>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<form action="${pageContext.request.contextPath}/ValidationAction_registerCustomer" method="post">
用户名:<input type="text" name="username" value="${param.username }">
<font color="red"><s:property value="fieldErrors.username[0]"/>font>
<br>
邮箱:<input type="e-mail" name="email" value="${param.email }">
<font color="red"><s:property value="fieldErrors.email[0]"/>font>
<br>
年龄:<input type="text" name="age" value="${param.age }">
<font color="red"><s:property value="errors.age[0]"/>font>
<br>
密码:<input type="password" name="password" value="${param.password }">
<font color="red"><s:property value="fieldErrors.password[0]"/>font>
<br>
确认密码:<input type="password" name="repassword" value="${param.repassword }">
<font color="red"><s:property value="errorMessages[0]" />font>
<br>
url:<input type="url" name="url" value="${param.url }">
<font color="red"><s:property value="fieldErrors.url[0]"/>font>
<br>
性别:男<input type="radio" name="gender" value="男" ${param.gender=='男'?'checked':''}>女<input type="radio" name="gender" value="女"${param.gender=='女'?'checked':''}>
<font color="red"><s:property value="fieldErrors.gender[0]"/>font>
<br>
<input type="submit" value=" 提交 ">
form>
<s:debug>s:debug>
body>
html>
<action name="UserAction_*" class="com.xxx.UserAction"
method="{1}">
<result name="success">/success.jspresult>
<result name="input">/register.jspresult>
action>
<action name="queryAction" class="com.xxx.UserAction"
method="query">
<result name="success">/success.jspresult>
<result name="input">/query.jspresult>
action>
<action name="ValidationAction_*"
class="com.xxx.ValidationAction" method="{1}">
<result name="success">/success.jspresult>
<result name="input">/registerCustomer.jspresult>
action>
上传文件
import java.io.File;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
// 声明一个 File[] 属性(用来接收上传的文件)
// 注意:命名规范!文件数组的名字为表单提交的 name 属性
private File[] files;
// 声明一个 String[] 数组,用来接收上传文件的名字
// 注意:命名规范! name 属性名 + FileName
private String[] filesFileName;
// 必须提供 set/get 方法
public File[] getFiles() {
return files;
}
public void setFiles(File[] files) {
this.files = files;
}
public String[] getFilesFileName() {
return filesFileName;
}
public void setFilesFileName(String[] filesFileName) {
this.filesFileName = filesFileName;
}
// 上传动作方法
/*
* 上传文件会上传到服务器中你的工程文件夹下
*/
public String upload() throws Exception {
/*
* 1.获取文件上传的服务器路径(获取真实路径)
* 2.拼接上传文件夹路径
* 3.在服务器上创建上传的文件夹
* 4.把 struts 接收到的文件保存到该路径下
*/
// 获取 ServletContext
ServletContext application = ServletActionContext.getServletContext();
// 获取真实路径(服务器的硬盘路径)
// 参数:拼接的文件夹地址
String realPath = application.getRealPath("/upload");
System.out.println(realPath);
// 根据路径,创建文件夹(判断文件夹不存在,再创建)
// 用这个路径创建一个 File 对象
File file = new File(realPath);
if (!file.exists()) {
// 不存在,创建
file.mkdir();
}
// 把 struts 接收过来的文件放入该文件夹中
// 遍历文件数组
for (int i = 0; i < files.length; i++) {
// 取出每个文件放入
File tempFile = files[i];
// 取出每个对应的文件名
String tempFileName = filesFileName[i];
// 直接将文件重新命名 renameTo(把该文件改个名剪切过去) 方法
tempFile.renameTo(new File(realPath, tempFileName));
}
/*
* 查看上传的文件列表
*/
return "success";
}
}
<body>
<form action="${pageContext.request.contextPath }/UploadAction_upload" method="post" enctype="multipart/form-data">
<input type="file" name="files">
<input type="file" name="files">
<input type="file" name="files">
<input type="submit" value=" 上传文件 ">
form>
body>
<action name="UploadAction_*" class="com.xxx.UploadAction"
method="{1}">
<result name="success" type="redirect">/success.jspresult>
action>
<constant name="struts.multipart.maxSize" value="5368709120">constant>
下载
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport {
// 获取表单传过来的文件名
// 这里会出现文件名的中文乱码问题
// 需要修改 filename 的编码格式
private String filename;
// 声明一个读取文件的字节流属性(创建这个流,其他事 struts 来做)
private InputStream fileInputStream;// 这个名字无规范,但是需要通知 struts, 创建的是什么流
public String getFilename() {
// 修改编码格式
// 方法是给 struts 提供的
// 当系统调用时,修改编码格式
try {
filename = new String(filename.getBytes(), "iso-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public InputStream getFileInputStream() {
return fileInputStream;
}
public void setFileInputStream(InputStream fileInputStream) {
this.fileInputStream = fileInputStream;
}
// 下载方法
public String download() throws Exception {
/*
* 1.获取用户要下载的文件的真实路径(服务器路径) 2.用这个路径初始化字节流
*/
ServletContext application = ServletActionContext.getServletContext();
String realPath = application.getRealPath("/upload/" + filename);
fileInputStream = new FileInputStream(realPath);
return "success";
}
}
<body>
<form action="${pageContext.request.contextPath }/DownloadAction_download" method="post">
下载文件名:<input type="text" name="filename">
<input type="submit" value=" 下载 ">
form>
body>
<action name="DownloadAction_*" class="com.xxx.DownloadAction" method="{1}">
<result name="success" type="stream">
<param name="contentType">application/octet-streamparam>
<param name="contentDisposition">attachment;filename=${filename}param>
<param name="inputName">fileInputStreamparam>
result>
action>