07.struts2中的数据合法性验证和文件上传
作者:互联网
07.struts2中的数据合法性验证和文件上传
1、数据合法性验证
编程式验证
1、继承ActionSupport
2、重写validate方法
该方法在Validation拦截器中被调用执行
拦截器栈的执行顺序
prepare
modelDrivem
params
validation
3、编写验证规则
如果不符合规则,则调用addFieldError方法
addFieldError(错误的字段名,错误提示信息)
当执行该方法的时候,该方法会向值栈中添加错误消息(fieldErrors),并且返回result name=input
配置式验证
Struts2提供的验证器
验证器配置文件必须放在被验证的属性的同包下
名称:被验证的属性所在类的类名-validation.xml
<!--基于验证器
type:Struts2自带验证器的别名,在struts-core/com/opensymphony/xwork2/validator/validators/default.xml可以看到
-->
<validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
<validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
<validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
<validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
<validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
<validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
<validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
<validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
<validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
<validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
<validator name="creditcard" class="com.opensymphony.xwork2.validator.validators.CreditCardValidator"/>
<validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
<validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
<validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
<validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
<validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
<validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>
基于验证器的配置
<validator type="int">
<!-- 验证哪个字段 -->
<param name="fieldName">stuAge</param>
<!-- 验证器需要的参数 -->
<param name="min">0</param>
<param name="max">120</param>
<!-- 不符合规则时的反馈信息 -->
<message>年龄不对头啊</message>
</validator>
基于字段的配置
<field name="stuName">
<field-validator type="requiredstring">
<!-- 该属性为true,在验证之前requiredstring会先进行.trim()方法去除两端空格,如果为false,则不会去空格 -->
<param name="trim">true</param>
<message>用户名不能为空!</message>
</field-validator>
<field-validator type="regex">
<param name="regexExpression">
<!-- 正则表达式中可能含有大量的特殊字符
<!--
[CDATA[内容]]>:其中的内容如果在XML文件中,则不需要特殊转义(< < > > & &... ...)
-->
<![CDATA[([a-zA-Z]\w*)]]>
</param>
<message>名称不合适</message>
</field-validator>
</field>
2、文件上传
A、导入jar包
commons-fileupload
commons-io
B、文件上传的三要素
表单提交方式必须为post
设置表单的enctype属性为multipart/form-data
表单中必须包含input type=file的文件框元素
C、在类中声明java.io.File对象,用于存储上传的文件
D、接收额外提交的FileName截取并拼接文件名和输出路径
E、创建FileUtils工具类
copyFile(文件来源,写入的目标);
F、配置文件上传的设置
struts.xml
案例:
导入相应的jar包
commons-fileupload
commons-io
配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>struts2Test09</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>dispatcherFilter</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>dispatcherFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
jsp页面
验证数据的合法性
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="student/registerStuInfo" method="post">
姓名:<input type="text" name="stuName"><br/>
年龄:<input type="text" name="stuAge"><br/>
邮箱:<input type="text" name="stuEmail"><br/>
<input type="submit" value="提交啊">
</form>
</body>
</html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:fielderror></s:fielderror>
<s:debug></s:debug>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>成功!</h1>
<s:debug></s:debug>
</body>
</html>
fileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="student/uploadFileMethod" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="提交">
</form>
</body>
</html>
配置struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.multipart.maxSize" value="209715200"></constant>
<package name="student" extends="struts-default" namespace="/student">
<action name="uploadFileMethod" class="com.zuxia.action.FileUploadAction" method="uploadFileMethod">
<result>
/success.jsp
</result>
</action>
<action name="registerStuInfo" class="com.zuxia.action.StudentAction" method="registerStuInfo">
<result>
/success.jsp
</result>
<result name="input">
/errorPage.jsp
</result>
</action>
</package>
</struts>
Action类
数据合法性处理类(第一种方式)
package com.zuxia.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.zuxia.entity.StudentInfo;
public class StudentAction extends ActionSupport implements ModelDriven<StudentInfo>{
private StudentInfo studentInfo;
public String registerStuInfo() {
System.out.println(studentInfo);
return "success";
}
@Override
public StudentInfo getModel() {
studentInfo = new StudentInfo();
return studentInfo;
}
/**
*
* 验证方法
/*
@Override
public void validate() {
if(studentInfo.getStuAge()<18) {
//当数据不符合验证规则的时候,如果不想程序进入控制器的目标方法继续执行,则可以调用 ActionSupport中的addFieldError来添加错误信息
addFieldError("stuAge", "年龄太小啦,不得行");
}
if(studentInfo.getStuAge()>50) {
addFieldError("stuAge", "年龄太大了,建议老年大学继续深造");
}
}
*/
}
第二种方式
配置 :类名-validation.xml文件(命名必须和所在包类名一致)
例如:StudentAction-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.2//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<!--
验证器配置文件必须放在被验证的属性的同包下
名称:被验证的属性所在类的类名-validation.xml
-->
<validators>
<!--
基于验证器
type:Struts2自带验证器的别名,在struts-core/com/opensymphony/xwork2/validator/validators/default.xml可以看到
-->
<validator type="int">
<!-- 验证哪个字段 -->
<param name="fieldName">stuAge</param>
<!-- 验证器需要的参数 -->
<param name="min">0</param>
<param name="max">120</param>
<!-- 不符合规则时的反馈信息 -->
<message>年龄不对头啊</message>
</validator>
<validator type="email">
<param name="fieldName">stuEmail</param>
<message>邮箱格式不对</message>
</validator>
<!--
基于字段配置
-->
<field name="stuName">
<field-validator type="requiredstring">
<!-- 该属性为true,在验证之前requiredstring会先进行.trim()方法去除两端空格,如果为false,则不会去空格 -->
<param name="trim">true</param>
<message>用户名不能为空!</message>
</field-validator>
<field-validator type="regex">
<param name="regexExpression">
<!-- 正则表达式中可能含有大量的特殊字符
<![CDATA[内容]]>:其中的内容如果在XML文件中,则不需要特殊转义(< < > > & &... ...)
-->
<![CDATA[([a-zA-Z]\w*)]]>
</param>
<message>名称不合适</message>
</field-validator>
</field>
</validators>
FileUploadAction.java文件上传处理类
package com.zuxia.action;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
public class FileUploadAction {
//声明java.io.File对象用于接收上传的文件
private File myFile;
/*
* 如果表单提交的是文件,则会额外追加两个提交参数
* [表单的name]ContentType
* [表单的name]FileName
* */
//文件类型
private String myFileContentType;
//文件名(通过她来获得文件的后缀)
private String myFileFileName;
public String uploadFileMethod() {
//截取后缀名
String suffix = myFileFileName.substring(myFileFileName.lastIndexOf("."));
//通过UUID随机生成一个文件名,拼接上后缀作为真正的文件名
String servetFileName = UUID.randomUUID()+suffix;
//创建文件工具类对象
FileUtils fileUtils = new FileUtils();
//创建文件保存的位置,以及文件名的file对象
File tagetPath = new File("D:/uploadFile/"+servetFileName);
try {
//保存文件操作
fileUtils.copyFile(myFile, taggetPath);
} catch (IOException e) {
System.out.println("保存文件失败");
}
return "success";
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public File getMyFile() {
return myFile;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
}
配置struts.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<!--文件上传大小的设置:默认最大为2MB,我们想上传大文件可以更改struts.multipart.maxSize属性的value值-->
<constant name="struts.multipart.maxSize" value="209715200"></constant>
<package name="student" extends="struts-default" namespace="/student">
<!--文件上传的action-->
<action name="uploadFileMethod" class="com.zuxia.action.FileUploadAction" method="uploadFileMethod">
<result>
/success.jsp
</result>
</action>
<!--数据合法性验证action-->
<action name="registerStuInfo" class="com.zuxia.action.StudentAction" method="registerStuInfo">
<result>
/success.jsp
</result>
<!--不合法就跳转-->
<result name="input">
/errorPage.jsp
</result>
</action>
</package>
</struts>
entity(实体类)
package com.zuxia.entity;
public class StudentInfo {
private String stuName;
private Integer stuAge;
private String stuEmail;
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Integer getStuAge() {
return stuAge;
}
public void setStuAge(Integer stuAge) {
this.stuAge = stuAge;
}
public String getStuEmail() {
return stuEmail;
}
public void setStuEmail(String stuEmail) {
this.stuEmail = stuEmail;
}
public StudentInfo(String stuName, Integer stuAge, String stuEmail) {
super();
this.stuName = stuName;
this.stuAge = stuAge;
this.stuEmail = stuEmail;
}
public StudentInfo() {
super();
}
@Override
public String toString() {
return "StudentInfo [stuName=" + stuName + ", stuAge=" + stuAge + ", stuEmail=" + stuEmail + "]";
}
}
标签:文件,String,struts2,jsp,stuEmail,上传,public,stuAge,07 来源: https://blog.csdn.net/ycjcson/article/details/112179806