您的位置:首页 > 编程语言 > Java开发

JavaWeb -- Struts1 使用示例: 表单校验 防表单重复提交 表单数据封装到实体

2014-01-03 14:06 951 查看
1. struts 工作流程图





超链接



2. 入门案例

struts入门案例:

1、写一个注册页面,把请求交给 struts处理
<form action="${pageContext.request.contextPath }/Register.do" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
邮箱:<input type="text" name="email"><br/>
<input type="submit" value="注册">
</form>
<html:errors property="username"/>

2、导入struts开发包,并在web.xml文件配置struts(ActionServlet)处理所有.do请求

<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>

</servlet>

<servlet-mapping>
<servlet-name>ActionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

3、在web-inf目录中加入struts的配置文件:struts-config.xml,并配置struts收到请求后找RegisterAction处理,并配置在找RegisterAction处理请求之前,把数据封装到formbean中
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
<form-beans>
<form-bean name="UserFormBean" type="cn.itcast.web.formbean.UserFormbean"></form-bean>
</form-beans>

<!-- 配置struts收到请求后找一个action处理 -->

<action-mappings>
<action path="/Register" type="cn.itcast.web.action.RegisterAction" name="UserFormBean"></action>
</action-mappings>

</struts-config>

4、把封装数据formbean,以及处理请求的RegisterAction写出来

JavaBean 继承 ActionForm

public class UserFormbean extends ActionForm {

private String username;
private String password;
private String email;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {

ActionErrors errors = new ActionErrors();
if(this.username==null || this.username.trim().equals("")){
errors.add("username", new ActionMessage("errors.username.required"));
}
return errors;
}

}

Action:

public class RegisterAction extends Action {

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

UserFormbean bean = (UserFormbean) form;
System.out.println(bean.getUsername());
System.out.println(bean.getPassword());
System.out.println(bean.getEmail());

try{
System.out.println("向数据注册用户!!");
request.setAttribute("message", "注册成功");
}catch (Exception e) {
request.setAttribute("message", "注册失败");
}
return mapping.findForward("message");	//转发
}
}

web.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 
<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>

</servlet>

<servlet-mapping>
<servlet-name>ActionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

struts-config.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

<form-beans>
<form-bean name="UserFormBean" type="com.kevin.domain.UserFormbean"></form-bean>
</form-beans>

<action-mappings>
<action path="/Register"
type="com.kevin.action.RegisterAction"
name="UserFormBean"
input="/index.jsp">			 //bean校验错误后 回跳
<forward name="message" path="/message.jsp"></forward>   //转发
</action>
</action-mappings>

<message-resources parameter="com.yourcompany.struts.ApplicationResources" />  //配置文件  国际化
</struts-config>


----------------------- 实例 : 表单校验,防表单重复提交 表单数据封装到实体-----------------

首页

<body>
<html:link action="/RegisterUI" >注册</html:link>
</body>

/WEB-INF/jsp/register.jsp 表单页面

<%@page import="com.kevin.golobals.Preference"%>
<%@page import="com.kevin.golobals.Gender"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>注册页面</title>
</head>

<body>
<!--
html:form 发生session域中如果有org.apache.struts.action.TOKEN为随机数,它会自动生成隐藏字段
-->
<html:form action="/Register">
<table width="50%" frame="border">

<tr>
<td>用户名</td>
<td>
<html:text property="username"/>
</td>
<td>
<html:errors property="username"/>
</td>
</tr>

<tr>
<td>密码</td>
<td>
<html:password property="password" redisplay="false"/>
</td>

<td>
<html:errors property="password"/>
</td>
</tr>

<tr>
<td>确认密码</td>
<td>
<html:password property="password2"  redisplay="false"/>
</td>
<td>
<html:errors property="password2"/>
</td>
</tr>

<tr>
<td>性别</td>
<td>
<c:forEach var="g" items="<%= Gender.values() %>">
<html:radio property="gender" value="${g.name }">${g.value }</html:radio>
</c:forEach>
</td>
<td>
<html:errors property="gender"/>
</td>
</tr>

<tr>
<td>生日</td>
<td>
<html:text property="birthday"></html:text>
</td>
<td>
<html:errors property="birthday"/>
</td>
</tr>

<tr>
<td>收入</td>
<td>
<html:text property="income"></html:text>
</td>
<td>
<html:errors property="income"/>
</td>
</tr>

<tr>
<td>城市</td>
<td>
<html:select property="city">
<html:option value="beijing">北京</html:option>
<html:option value="guangzhou">广州</html:option>
<html:option value="shanghai">上海</html:option>
</html:select>
</td>
<td>

</td>
</tr>

<tr>
<td>爱好</td>
<td>

<c:forEach var="pre" items="<%=Preference.values() %>">
<html:multibox property="preference" value="${pre.name }"/>${pre.value}
</c:forEach>
</td>
<td>
<html:errors property="preference"/>
</td>
</tr>

<tr>
<td>邮箱</td>
<td>
<html:text property="email"></html:text>
</td>
<td>
<html:errors property="email"/>
</td>
</tr>

<tr>
<td>
<input type="reset" value="清空">
</td>
<td>
<input type="submit" value="注册">
</td>
</tr>
</table>
</html:form>

</body>
</html>

com.kevin.domain , 表单数据bean 数据校验

public class UserFormBean extends ActionForm {

private String username;
private String password;
private String password2;
private String gender;
private String birthday;
private String income;
private String city;
private String[] preference;
private String email;

@Override
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {

ActionErrors errors = new ActionErrors();

if(isEmpty(this.username))
addMessage(errors, "username", "用户名不能为空");
else
{
if(!this.username.matches("^[A-Za-z]{3,9}"))
addMessage(errors, "username", "用户名必须是3-9位字母");
}

//密码不能为空,要是3-9的字母或数字
if(isEmpty(this.password)){
addMessage(errors, "password", "密码不能为空");
}else{
if(!this.password.matches("\\w{3,9}")){
addMessage(errors,"password", "密码必须是3-8位字母或数字");
}
}

//二次密码不能为空,并且要和一次密码一致
if(isEmpty(this.password2)){
addMessage(errors, "password2", "密码不能为空");
}else{
if(!this.password2.equals(this.password)){
addMessage(errors,"password2", "两次密码必须要一致");
}
}

//性别不能为空,并且要是枚举的一个实例的值
if(isEmpty(this.gender)){
addMessage(errors, "gender", "性别不能为空");
}else{
try{
Gender.valueOf(this.gender.toUpperCase());
}catch (Exception e) {
addMessage(errors, "gender", "性别非法");
}
}

//生日可以为空,不为空时,要是一个日期
if(!isEmpty(this.birthday)){
try{
DateLocaleConverter conver = new DateLocaleConverter(Locale.CHINA, "yy-M-d");
conver.convert(this.birthday);
}catch (Exception e) {
addMessage(errors, "birthday", "生日不能一个合法的日期");
}
}

//收入要是一个数字,可以为空
if(!isEmpty(this.income)){
try{
Double.parseDouble(this.income);
}catch (Exception e) {
addMessage(errors, "income", "收入要是一个数字");
}
}

//爱好可以为空,不为空时要是合法的枚举值:String[] preference;
if(this.preference!=null && this.preference.length>0){
for(String pre : this.preference){
try{
Preference.valueOf(pre.toUpperCase());
}catch (Exception e) {
addMessage(errors, "preference", "爱好输入有误");
}
}
}

//邮箱可以为空,不为空时,要是一个格式有效的邮箱
if(!isEmpty(this.email)){
if(!this.email.matches("\\w+@\\w+(\\.\\w+)+")){
addMessage(errors, "email", "邮箱格式非法");
}
}

return errors;
}

private boolean isEmpty(String value){
if(value==null || value.trim().equals("")){
return true;
}
return false;
}

private void addMessage(ActionErrors errors,String key,String message){
errors.add(key,new ActionMessage(message,false));
}//validate

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getIncome() {
return income;
}
public void setIncome(String income) {
this.income = income;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String[] getPreference() {
return preference;
}
public void setPreference(String[] preference) {
this.preference = preference;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

实体数据bean

public class User {

private String id;
private String username;
private String password;
private Gender gender;
private Date birthday;  //null
private double income;
private String city;
private Preference[] preference;
private String email;

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public double getIncome() {
return income;
}
public void setIncome(double income) {
this.income = income;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Preference[] getPreference() {
return preference;
}
public void setPreference(Preference[] preference) {
this.preference = preference;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

}

com.kevin.action Action

public class RegisterUIAction extends Action {

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

saveToken(request); //org.apache.struts.action.TOKEN 防表单重复提交
return mapping.findForward("register");
}
}
public class RegisterAction extends Action { //表单处理 注册 Action

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

//将表单数据封装到实体中
User user = new User();
UserFormBean formbean = (UserFormBean) form;
BeanUtils.copyProperties(user, formbean);
System.out.println(user.getUsername());

try
{
if(isTokenValid(request)){
resetToken(request);  //清楚session中的token
System.out.println("处理用户注册请求.....");
request.setAttribute("message", "注册成功");
}else{
System.out.println("对不起,您是重复提交");
}
}
catch (Exception e)
{
e.printStackTrace();
request.setAttribute("message", "注册失败");
}

//return mapping.findForward("message");
return null;
}

}

监听器,注册beanutils 转换器

public class WebInitListener implements ServletContextListener {

@Override
public void contextInitialized(ServletContextEvent arg0) {

//注册转换日期的转换器
ConvertUtils.register(new Converter(){
public Object convert(Class type, Object value) {
if(value==null){
return null;
}
if(value instanceof String){
String d = (String)value;
if(d.trim().equals("")){
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(d);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
throw new RuntimeException("输入类的类型不是String");
}
}, Date.class);

//转性别枚举
ConvertUtils.register(new Converter(){
public Object convert(Class type, Object value) {
if(value==null){
return null;
}
return Gender.valueOf(((String) value).toUpperCase());
}

}, Gender.class);

//转爱好枚举数组
ConvertUtils.register(new Converter(){

public Object convert(Class type, Object value) {
if(value==null){
return null;
}
String pres[] = (String[]) value;
Preference p[] = new Preference[pres.length];
for(int i=0;i<pres.length;i++){
p[i] = Preference.valueOf(pres[i].toUpperCase());
}
return p;
}

},Preference[].class);

}

@Override
public void contextDestroyed(ServletContextEvent arg0) {

}

}

com.kevin.golobals 枚举类

public enum Gender {

MALE("male","男"),FEMALE("female","女");

private String name;
private String value;
private Gender(String name,String value){
this.name= name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
public enum Preference {

SING("sing","唱歌"),DANCE("dance","跳舞"),FOOTBALL("football","足球");

private String name;
private String value;
private Preference(String name, String value)
{
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}

struts-config.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
<form-beans >
<form-bean name="UserFormBean" type="com.kevin.domain.UserFormBean"></form-bean>
</form-beans>

<global-exceptions />
<global-forwards />

<action-mappings>
<action path="/RegisterUI"
type="com.kevin.action.RegisterUIAction" >
<forward name="register" path="/WEB-INF/jsp/register.jsp"></forward>
</action>

<action path="/Register"
type="com.kevin.action.RegisterAction"
name="UserFormBean"
scope="request"
validate="true"
input="/WEB-INF/jsp/register.jsp"
>
<forward name="message" path="/message.jsp"></forward>
</action>

</action-mappings>

<message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>


web.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name />
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.kevin.web.filter.EncodingFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
<listener-class>com.kevin.web.listener.WebInitListener</listener-class>
</listener>

</web-app>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐