In this article, I will introduce 3 ways in writing validators in Struts2-Spring-Hibernate application.
First of all, create package com.ssh.bean and create a bean named 'User' under this package:
User.java
1 package com.ssh.bean;
2
3 public class User {
4 private long id;
5 private String username;
6 private String password;
7 private String firstname;
8 private String lastname;
9 private String email;
10 private String street;
11 private String city;
12 private String state;
13 private String zip;
14
15 public long getId() {
16 return id;
17 }
18 public void setId(long id) {
19 this.id = id;
20 }
21 public String getUsername() {
22 return username;
23 }
24 public void setUsername(String username) {
25 this.username = username;
26 }
27 public String getPassword() {
28 return password;
29 }
30 public void setPassword(String password) {
31 this.password = password;
32 }
33 public String getFirstname() {
34 return firstname;
35 }
36 public void setFirstname(String firstname) {
37 this.firstname = firstname;
38 }
39 public String getLastname() {
40 return lastname;
41 }
42 public void setLastname(String lastname) {
43 this.lastname = lastname;
44 }
45 public String getEmail() {
46 return email;
47 }
48 public void setEmail(String email) {
49 this.email = email;
50 }
51 public String getStreet() {
52 return street;
53 }
54 public void setStreet(String street) {
55 this.street = street;
56 }
57 public String getCity() {
58 return city;
59 }
60 public void setCity(String city) {
61 this.city = city;
62 }
63 public String getState() {
64 return state;
65 }
66 public void setState(String state) {
67 this.state = state;
68 }
69 public String getZip() {
70 return zip;
71 }
72 public void setZip(String zip) {
73 this.zip = zip;
74 }
75 }
Under the same package, create User.hbm.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE hibernate-mapping PUBLIC
3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5 <hibernate-mapping>
6 <class name="com.ssh.bean.User" table="user">
7 <id name="id" type="java.lang.Long" column="id">
8 <generator class="increment"></generator>
9 </id>
10 <property name="username" type="string" column="username" length="200"></property>
11 <property name="password" type="string" column="password" length="200"></property>
12 <property name="firstname" type="string" column="firstname" length="200"></property>
13 <property name="lastname" type="string" column="lastname" length="200"></property>
14 <property name="email" type="string" column="email" length="200"></property>
15 <property name="street" type="string" column="street" length="200"></property>
16 <property name="city" type="string" column="city" length="200"></property>
17 <property name="state" type="string" column="state" length="50"></property>
18 <property name="zip" type="string" column="zip" length="50"></property>
19 </class>
20 </hibernate-mapping>
Create hibernate.cfg.xml directory under 'src':
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE hibernate-configuration PUBLIC
3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
5
6 <hibernate-configuration>
7 <session-factory>
8 <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/blogjava</property>
9 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
10 <property name="hibernate.connection.username">root</property>
11 <property name="hibernate.connection.password">123456789</property>
12 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
13 <property name="hibernate.show_sql">true</property>
14
15 <mapping resource="com/ssh/bean/User.hbm.xml"/>
16 </session-factory>
17 </hibernate-configuration>
In this configuration file, I am using MySql and the database schema is blogjava.
My database admin username is root and password is 123456789. Change them if it is needed according to your database.
Then, create package com.ssh.test and create ExportDB.java under this package:
1 package com.ssh.test;
2
3 import org.hibernate.cfg.Configuration;
4 import org.hibernate.tool.hbm2ddl.SchemaExport;
5
6 public class ExportDB {
7 public static void main(String[] args){
8 Configuration cfg = new Configuration().configure();
9 SchemaExport export = new SchemaExport(cfg);
10 export.create(true, true);
11 }
12 }
Run this class and a table named 'user' is created under 'blogjava'. There are 2 lines printed out in console:
drop table if exists user
create table user (id bigint not null, username varchar(200), password varchar(200), firstname varchar(200), lastname varchar(200), email varchar(200), street varchar(200), city varchar(200), state varchar(50), zip varchar(50), primary key (id))
The reason not using create SQL directory in MySql but using hibernate technique is it can better realize the OO idea.
Check the table 'user' under command line:
Now we create register.jsp under WebContent directly, if you are using MyEclipse, it's probably 'WebRoot'.
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib prefix="s" uri="/struts-tags"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>New User Registration</title>
9 </head>
10 <body>
11 <s:form action="register" theme="simple">
12 <table style="border-collapse: collapse" align="left"
13 bordercolor=#3f8805 cellspacing=0 cellpadding=0 width="20%" border=1>
14 <tr>
15 <td>username</td>
16 <td><s:textfield name="user.username"></s:textfield></td>
17 </tr>
18 <tr>
19 <td>password</td>
20 <td><s:password name="user.password"></s:password></td>
21 </tr>
22 <tr>
23 <td>re-password</td>
24 <td><s:password name="repassword"></s:password></td>
25 </tr>
26 <tr>
27 <td>firstname</td>
28 <td><s:textfield name="user.firstname"></s:textfield></td>
29 </tr>
30 <tr>
31 <td>lastname</td>
32 <td><s:textfield name="user.lastname"></s:textfield></td>
33 </tr>
34 <tr>
35 <td>email</td>
36 <td><s:textfield name="user.email"></s:textfield></td>
37 </tr>
38 <tr>
39 <td>street address</td>
40 <td><s:textfield name="user.street"></s:textfield></td>
41 </tr>
42 <tr>
43 <td>city</td>
44 <td><s:textfield name="user.city"></s:textfield></td>
45 </tr>
46 <tr>
47 <td>state</td>
48 <td><s:textfield name="user.state"></s:textfield></td>
49 </tr>
50 <tr>
51 <td>zip code</td>
52 <td><s:textfield name="user.zip"></s:textfield></td>
53 </tr>
54 <tr>
55 <td></td>
56 <td><s:submit></s:submit> <s:reset></s:reset></td>
57 </tr>
58 </table>
59 </s:form>
60 </body>
61 </html>
In this case, I don't use css because it's only a demo of struts2 validator.
Start up Tomcat server and open web browser with "http://localhost:8080/loginbystruts/register.jsp"
Actually, because of validator, register.jsp will be changed a little by adding field error.
Now it's time to create struts.xml under 'src' directly:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4 "http://struts.apache.org/dtds/struts-2.0.dtd">
5 <struts>
6 <package name="sshlogin" extends="struts-default">
7 <action name="login" class="loginAction" method="login">
8 <result name="success">/user.jsp</result>
9 <result name="input">/login.jsp</result>
10 </action>
11
12 <action name="register" class="registerAction" method="register">
13 <result name="success">/user.jsp</result>
14 <result name="input">/register.jsp</result>
15 </action>
16 </package>
17 </struts>
Create Spring MVC: DAO and Service interface as well as their implementation classes like following struture:
UserDao.java:
1 package com.ssh.dao;
2
3 import com.ssh.bean.User;
4 import java.util.List;
5 public interface UserDao {
6 public void save(User user);
7 public void remove(User user);
8 public User findUserById(long id);
9 public List<User> findAll();
10 public void update(User user);
11 }
UserDaoImpl.java
1 package com.ssh.dao.impl;
2
3 import java.util.List;
4 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
5 import com.ssh.bean.User;
6 import com.ssh.dao.UserDao;
7
8 public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
9 @SuppressWarnings("unchecked")
10 @Override
11 public List<User> findAll() {
12 // TODO Auto-generated method stub
13 String hql = "from User user order by user.id desc";
14 return (List<User>) this.getHibernateTemplate().find(hql);
15 }
16
17 @Override
18 public User findUserById(long id) {
19 // TODO Auto-generated method stub
20 User user = (User) this.getHibernateTemplate().get(User.class, id);
21 return user;
22 }
23
24 @Override
25 public void remove(User user) {
26 // TODO Auto-generated method stub
27 this.getHibernateTemplate().delete(user);
28 }
29
30 @Override
31 public void save(User user) {
32 // TODO Auto-generated method stub
33 this.getHibernateTemplate().save(user);
34 }
35
36 @Override
37 public void update(User user) {
38 // TODO Auto-generated method stub
39 this.getHibernateTemplate().update(user);
40 }
41 }
UserService.java
1 package com.ssh.service;
2
3 import java.util.List;
4 import com.ssh.bean.User;
5
6 public interface UserService {
7 public void save(User user);
8 public void remove(User user);
9 public User findUserById(long id);
10 public List<User> findAll();
11 public void update(User user);
12 }
13
UserServiceImpl.java
1 package com.ssh.service.impl;
2
3 import java.util.List;
4 import com.ssh.bean.User;
5 import com.ssh.dao.UserDao;
6 import com.ssh.service.UserService;
7
8 public class UserServiceImpl implements UserService {
9
10 private UserDao userDao;
11
12 public UserDao getUserDao() {
13 return userDao;
14 }
15
16 public void setUserDao(UserDao userDao) {
17 this.userDao = userDao;
18 }
19
20 @Override
21 public List<User> findAll() {
22 // TODO Auto-generated method stub
23 return this.userDao.findAll();
24 }
25
26 @Override
27 public User findUserById(long id) {
28 // TODO Auto-generated method stub
29 return this.userDao.findUserById(id);
30 }
31
32 @Override
33 public void remove(User user) {
34 // TODO Auto-generated method stub
35 this.userDao.remove(user);
36 }
37
38 @Override
39 public void save(User user) {
40 // TODO Auto-generated method stub
41 this.userDao.save(user);
42 }
43
44 @Override
45 public void update(User user) {
46 // TODO Auto-generated method stub
47 this.userDao.update(user);
48 }
49
50 }
51
Create applicationContext.xml under 'WebContent/WEB-INF'
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="
5 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
6
7 <!-- <bean/> definitions here -->
8 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
9 <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
10 <property name="url" value="jdbc:mysql://localhost:3306/blogjava"></property>
11 <property name="username" value="root"></property>
12 <property name="password" value="112358"></property>
13 <property name="maxActive" value="100"></property>
14 <property name="maxIdle" value="30"></property>
15 <property name="maxWait" value="500"></property>
16 <property name="defaultAutoCommit" value="true"></property>
17 </bean>
18 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
19 <property name="dataSource" ref="dataSource"></property>
20 <property name="hibernateProperties">
21 <props>
22 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
23 <prop key="show_sql">true</prop>
24 </props>
25 </property>
26 <property name="mappingResources">
27 <list>
28 <value>com/ssh/bean/User.hbm.xml</value>
29 </list>
30 </property>
31 </bean>
32
33 <bean id="userDao" class="com.ssh.dao.impl.UserDaoImpl" scope="singleton">
34 <property name="sessionFactory">
35 <ref bean="sessionFactory"/>
36 </property>
37 </bean>
38
39 <bean id="userService" class="com.ssh.service.impl.UserServiceImpl">
40 <property name="userDao">
41 <ref bean="userDao"/>
42 </property>
43 </bean>
44
45 <bean id="loginAction" class="com.ssh.action.LoginAction" scope="prototype">
46 <property name="userService">
47 <ref bean="userService"/>
48 </property>
49 </bean>
50
51 <bean id="registerAction" class="com.ssh.action.RegisterAction" scope="prototype">
52 <property name="userService">
53 <ref bean="userService"></ref>
54 </property>
55 </bean>
56 </beans>
Configure web.xml in the same directory as applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xmlns="http://java.sun.com/xml/ns/javaee"
4 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
6 id="WebApp_ID" version="2.5">
7 <display-name>loginbystruts</display-name>
8 <filter>
9 <filter-name>struts2</filter-name>
10 <filter-class>
11 org.apache.struts2.dispatcher.FilterDispatcher
12 </filter-class>
13 </filter>
14 <filter-mapping>
15 <filter-name>struts2</filter-name>
16 <url-pattern>/*</url-pattern>
17 </filter-mapping>
18 <listener>
19 <listener-class>
20 org.springframework.web.context.ContextLoaderListener
21 </listener-class>
22 </listener>
23 </web-app>
Create package com.ssh.action and then create RegisterAction.java and LoginAction.java
RegisterAction.java
1 package com.ssh.action;
2
3 import com.opensymphony.xwork2.ActionSupport;
4 import com.ssh.bean.User;
5 import com.ssh.service.UserService;
6
7 public class RegisterAction extends ActionSupport {
8 private UserService userService;
9 private User user;
10 private String repassword;
11 public UserService getUserService() {
12 return userService;
13 }
14 public void setUserService(UserService userService) {
15 this.userService = userService;
16 }
17 public User getUser() {
18 return user;
19 }
20 public void setUser(User user) {
21 this.user = user;
22 }
23 public String getRepassword() {
24 return repassword;
25 }
26 public void setRepassword(String repassword) {
27 this.repassword = repassword;
28 }
29
30 public String register(){
31 this.userService.save(user);
32 return SUCCESS;
33 }
34 @Override
35 public void validate() {
36 // TODO Auto-generated method stub
37 if(null == this.user.getUsername() || "".equals(this.user.getUsername()))
38 this.addFieldError("username", "username is null");
39 if(null == this.user.getPassword() || "".equals(this.user.getPassword()))
40 this.addFieldError("password", "password is null");
41 if(null == this.repassword || "".equals(this.repassword))
42 this.addFieldError("repassword", "confirm your password");
43 if(null == this.user.getEmail() || "".equals(this.user.getEmail()))
44 this.addFieldError("email", "email is null");
45
46 }
47 }
LoginAction.java
1 package com.ssh.action;
2
3 import java.util.List;
4 import com.opensymphony.xwork2.ActionSupport;
5 import com.ssh.bean.User;
6 import com.ssh.service.UserService;
7
8 public class LoginAction extends ActionSupport {
9 private UserService userService;
10 private User user;
11 public void setUserService(UserService userService) {
12 this.userService = userService;
13 }
14
15 public User getUser() {
16 return user;
17 }
18
19 public void setUser(User user) {
20 this.user = user;
21 }
22
23 public String login(){
24 List<User> users = this.userService.findAll();
25 if(users == null || users.isEmpty())
26 return INPUT;
27 for(int i=0; i<users.size(); i++){
28 User u = users.get(i);
29 if(u.getUsername().equals(user.getUsername())){
30 if(u.getPassword().equals(user.getPassword()))
31 return SUCCESS;
32 else
33 continue;
34 }else
35 continue;
36 }
37 return INPUT;
38 }
39
40 @Override
41 public void validate() {
42 // TODO Auto-generated method stub
43 if(null == this.user.getUsername() || "".equals(this.user.getUsername()))
44 this.addFieldError("username", "username is null");
45 if(null == this.user.getPassword() || "".equals(this.user.getPassword()))
46 this.addFieldError("password", "password is null");
47 }
48 }
49
Edit register.jsp again according to the previous one:
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib prefix="s" uri="/struts-tags"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>New User Registration</title>
9 </head>
10 <body>
11 <s:form action="register" theme="simple">
12 <table style="border-collapse: collapse" align="left"
13 bordercolor=#3f8805 cellspacing=0 cellpadding=0 width="20%" border=1>
14 <tr>
15 <td>username</td>
16 <td>
17 <s:fielderror cssStyle="color:red">
18 <s:param>username</s:param>
19 </s:fielderror>
20 <s:textfield name="user.username"></s:textfield>
21 </td>
22 </tr>
23 <tr>
24 <td>password</td>
25 <td>
26 <s:fielderror cssStyle="color:red">
27 <s:param>password</s:param>
28 </s:fielderror>
29 <s:password name="user.password"></s:password>
30 </td>
31 </tr>
32 <tr>
33 <td>re-password</td>
34 <td>
35 <s:fielderror cssStyle="color:red">
36 <s:param>repassword</s:param>
37 </s:fielderror>
38 <s:password name="repassword"></s:password>
39 </td>
40 </tr>
41 <tr>
42 <td>firstname</td>
43 <td><s:textfield name="user.firstname"></s:textfield></td>
44 </tr>
45 <tr>
46 <td>lastname</td>
47 <td><s:textfield name="user.lastname"></s:textfield></td>
48 </tr>
49 <tr>
50 <td>email</td>
51 <td>
52 <s:fielderror cssStyle="color:red">
53 <s:param>email</s:param>
54 </s:fielderror>
55 <s:textfield name="user.email"></s:textfield>
56 </td>
57 </tr>
58 <tr>
59 <td>street address</td>
60 <td><s:textfield name="user.street"></s:textfield></td>
61 </tr>
62 <tr>
63 <td>city</td>
64 <td><s:textfield name="user.city"></s:textfield></td>
65 </tr>
66 <tr>
67 <td>state</td>
68 <td><s:textfield name="user.state"></s:textfield></td>
69 </tr>
70 <tr>
71 <td>zip code</td>
72 <td><s:textfield name="user.zip"></s:textfield></td>
73 </tr>
74 <tr>
75 <td></td>
76 <td><s:submit></s:submit> <s:reset></s:reset></td>
77 </tr>
78 </table>
79 </s:form>
80 </body>
81 </html>
login.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib prefix="s" uri="/struts-tags"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>Login</title>
9 </head>
10 <body>
11 <%-- action="login" actually can work with this error. --%>
12 <s:form action="login" theme="simple">
13 <table style="border-collapse: collapse" align="left"
14 bordercolor=#3f8805 cellspacing=0 cellpadding=0 width="20%" border=1>
15 <tr>
16 <td>username</td>
17 <td>
18 <s:fielderror cssStyle="color:red">
19 <s:param>username</s:param>
20 </s:fielderror>
21 <s:textfield name="user.username"></s:textfield>
22 </td>
23 </tr>
24
25 <tr>
26 <td>password</td>
27 <td>
28 <s:fielderror cssStyle="color:red">
29 <s:param>password</s:param>
30 </s:fielderror>
31 <s:password name="user.password"></s:password>
32 </td>
33 </tr>
34 <tr>
35 <td></td>
36 <td>
37 <s:submit></s:submit>
38 <s:reset></s:reset>
39 </td>
40 </tr>
41 </table>
42 </s:form>
43 </body>
44 </html>
Start Tomcat server and open web browser with http://localhost:8080/loginbystruts/register.jsp
If click submit without type in any information:
Now test address "http://localhost:8080/loginbystruts/login.jsp"
Without any information, it will be:
Now, let me introduce another method implementing struts2 validator based on XML without re-writing validate() method in LoginAction.java and RegisterAction.java.
First, annotate validate in both LoginAction.java and RegisterAction.java
LoginAction.java
1 package com.ssh.action;
2
3 import java.util.List;
4 import com.opensymphony.xwork2.ActionSupport;
5 import com.ssh.bean.User;
6 import com.ssh.service.UserService;
7
8 public class LoginAction extends ActionSupport {
9 private UserService userService;
10 private User user;
11 public void setUserService(UserService userService) {
12 this.userService = userService;
13 }
14
15 public User getUser() {
16 return user;
17 }
18
19 public void setUser(User user) {
20 this.user = user;
21 }
22
23 public String login(){
24 List<User> users = this.userService.findAll();
25 if(users == null || users.isEmpty())
26 return INPUT;
27 for(int i=0; i<users.size(); i++){
28 User u = users.get(i);
29 if(u.getUsername().equals(user.getUsername())){
30 if(u.getPassword().equals(user.getPassword()))
31 return SUCCESS;
32 else
33 continue;
34 }else
35 continue;
36 }
37 return INPUT;
38 }
39 /*
40 @Override
41 public void validate() {
42 // TODO Auto-generated method stub
43 if(null == this.user.getUsername() || "".equals(this.user.getUsername()))
44 this.addFieldError("username", "username is null");
45 if(null == this.user.getPassword() || "".equals(this.user.getPassword()))
46 this.addFieldError("password", "password is null");
47 }
48 */
49 }
50
RegisterAction.java
1 package com.ssh.action;
2
3 import com.opensymphony.xwork2.ActionSupport;
4 import com.ssh.bean.User;
5 import com.ssh.service.UserService;
6
7 public class RegisterAction extends ActionSupport {
8 private UserService userService;
9 private User user;
10 private String repassword;
11 public UserService getUserService() {
12 return userService;
13 }
14 public void setUserService(UserService userService) {
15 this.userService = userService;
16 }
17 public User getUser() {
18 return user;
19 }
20 public void setUser(User user) {
21 this.user = user;
22 }
23 public String getRepassword() {
24 return repassword;
25 }
26 public void setRepassword(String repassword) {
27 this.repassword = repassword;
28 }
29
30 public String register(){
31 this.userService.save(user);
32 return SUCCESS;
33 }
34 /*
35 @Override
36 public void validate() {
37 // TODO Auto-generated method stub
38 if(null == this.user.getUsername() || "".equals(this.user.getUsername()))
39 this.addFieldError("username", "username is null");
40 if(null == this.user.getPassword() || "".equals(this.user.getPassword()))
41 this.addFieldError("password", "password is null");
42 if(null == this.repassword || "".equals(this.repassword))
43 this.addFieldError("repassword", "confirm your password");
44 if(null == this.user.getEmail() || "".equals(this.user.getEmail()))
45 this.addFieldError("email", "email is null");
46
47 }
48 */
49 }
Now new LoginAction-validation.xml and RegisterAction-validation.xml.
Here is the naming rules: ***-validation.xml, *** must be same as the name as the action, such as if you have UserAction.java, the validator xml name must be UserAction-validation.xml. Second, ***-validation.xml must be in the same package with its action class.
In this case, There are LoginAction-validation.xml and RegisterAction-validation.xml, and they stay with LoginAction.java and RegisterAction.java;
LoginAction-validation.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
3 "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
4
5 <validators>
6 <field name="user.username">
7 <field-validator type="requiredstring">
8 <message>You must enter your username</message>
9 </field-validator>
10 </field>
11 <field name="user.password">
12 <field-validator type="requiredstring">
13 <message>You must enter your password</message>
14 </field-validator>
15 </field>
16 </validators>
RegisterAction-validation.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
3 "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
4
5 <validators>
6 <field name="user.username">
7 <field-validator type="requiredstring">
8 <message>You must enter your username</message>
9 </field-validator>
10 </field>
11 <field name="user.password">
12 <field-validator type="requiredstring">
13 <message>You must enter your password</message>
14 </field-validator>
15 </field>
16 <field name="repassword">
17 <field-validator type="requiredstring">
18 <message>You must confirm your password</message>
19 </field-validator>
20 </field>
21 <field name="user.email">
22 <field-validator type="requiredstring">
23 <message>You must enter your email address</message>
24 </field-validator>
25 </field>
26 </validators>
Then, I need to change login.jsp and register.jsp according to the field name. It requires the <s:param>**</s:param> in <s:fielderror> have the same content as <field name="***">, now it is user.username rather than username in the previous validation method. 'repassword' stays out of change because it's only a base variable.
login.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib prefix="s" uri="/struts-tags"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>Login</title>
9 </head>
10 <body>
11 <%-- action="login" actually can work with this error. --%>
12 <s:form action="login" theme="simple">
13 <table style="border-collapse: collapse" align="left"
14 bordercolor=#3f8805 cellspacing=0 cellpadding=0 width="20%" border=1>
15 <tr>
16 <td>username</td>
17 <td>
18 <s:fielderror cssStyle="color:red">
19 <s:param>user.username</s:param>
20 </s:fielderror>
21 <s:textfield name="user.username"></s:textfield>
22 </td>
23 </tr>
24
25 <tr>
26 <td>password</td>
27 <td>
28 <s:fielderror cssStyle="color:red">
29 <s:param>user.password</s:param>
30 </s:fielderror>
31 <s:password name="user.password"></s:password>
32 </td>
33 </tr>
34 <tr>
35 <td></td>
36 <td>
37 <s:submit></s:submit>
38 <s:reset></s:reset>
39 </td>
40 </tr>
41 </table>
42 </s:form>
43 </body>
44 </html>
register.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib prefix="s" uri="/struts-tags"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>New User Registration</title>
9 </head>
10 <body>
11 <s:form action="register" theme="simple">
12 <table style="border-collapse: collapse" align="left"
13 bordercolor=#3f8805 cellspacing=0 cellpadding=0 width="20%" border=1>
14 <tr>
15 <td>username</td>
16 <td>
17 <s:fielderror cssStyle="color:red">
18 <s:param>user.username</s:param>
19 </s:fielderror>
20 <s:textfield name="user.username"></s:textfield>
21 </td>
22 </tr>
23 <tr>
24 <td>password</td>
25 <td>
26 <s:fielderror cssStyle="color:red">
27 <s:param>user.password</s:param>
28 </s:fielderror>
29 <s:password name="user.password"></s:password>
30 </td>
31 </tr>
32 <tr>
33 <td>re-password</td>
34 <td>
35 <s:fielderror cssStyle="color:red">
36 <s:param>repassword</s:param>
37 </s:fielderror>
38 <s:password name="repassword"></s:password>
39 </td>
40 </tr>
41 <tr>
42 <td>firstname</td>
43 <td><s:textfield name="user.firstname"></s:textfield></td>
44 </tr>
45 <tr>
46 <td>lastname</td>
47 <td><s:textfield name="user.lastname"></s:textfield></td>
48 </tr>
49 <tr>
50 <td>email</td>
51 <td>
52 <s:fielderror cssStyle="color:red">
53 <s:param>user.email</s:param>
54 </s:fielderror>
55 <s:textfield name="user.email"></s:textfield>
56 </td>
57 </tr>
58 <tr>
59 <td>street address</td>
60 <td><s:textfield name="user.street"></s:textfield></td>
61 </tr>
62 <tr>
63 <td>city</td>
64 <td><s:textfield name="user.city"></s:textfield></td>
65 </tr>
66 <tr>
67 <td>state</td>
68 <td><s:textfield name="user.state"></s:textfield></td>
69 </tr>
70 <tr>
71 <td>zip code</td>
72 <td><s:textfield name="user.zip"></s:textfield></td>
73 </tr>
74 <tr>
75 <td></td>
76 <td><s:submit></s:submit> <s:reset></s:reset></td>
77 </tr>
78 </table>
79 </s:form>
80 </body>
81 </html>
Now test again:
For better comparison, I change the error printou to "You must enter ....".
Now, let me introduce the third method of validator in struts2.
Using type="visitor" in validator.
First, annotate all the validators in previous method, and add new ones in RegisterAction-validation.xml and LoginAction-validation.xml
RegisterAction-validation.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
3 "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
4 <!--
5 <validators>
6 <field name="user.username">
7 <field-validator type="requiredstring">
8 <message>You must enter your username</message>
9 </field-validator>
10 </field>
11 <field name="user.password">
12 <field-validator type="requiredstring">
13 <message>You must enter your password</message>
14 </field-validator>
15 </field>
16 <field name="repassword">
17 <field-validator type="requiredstring">
18 <message>You must confirm your password</message>
19 </field-validator>
20 </field>
21 <field name="user.email">
22 <field-validator type="requiredstring">
23 <message>You must enter your email address</message>
24 </field-validator>
25 </field>
26 </validators>
27 -->
28 <validators>
29 <field name="user"> <!-- The corresponding action class must have user as a member variable-->
30 <field-validator type="visitor">
31 <param name="context">registercontext</param> <!-- must have User-registercontext-validation.xml in com.ssh.bean -->
32 <param name="appendPrefix">true</param>
33 <message>Missing information, </message>
34 </field-validator>
35 </field>
36 <field name="repassword">
37 <field-validator type="requiredstring">
38 <message>You must confirm your password</message>
39 </field-validator>
40 </field>
41 </validators>
LoginAction-validation.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
3 "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
4 <!--
5 <validators>
6 <field name="user.username">
7 <field-validator type="requiredstring">
8 <message>You must enter your username</message>
9 </field-validator>
10 </field>
11 <field name="user.password">
12 <field-validator type="requiredstring">
13 <message>You must enter your password</message>
14 </field-validator>
15 </field>
16 </validators>
17 -->
18 <validators>
19 <field name="user"> <!-- The corresponding action class must have user as a member variable-->
20 <field-validator type="visitor">
21 <param name="context">logincontext</param> <!-- must have User-logincontext-validation.xml in com.ssh.bean -->
22 <param name="appendPrefix">true</param>
23 <message>Missing information, </message>
24 </field-validator>
25 </field>
26 </validators>
Now, under package com.ssh.bean, create User-registercontext-validation.xml and User-logincontenxt-validation.xml.
Notice: registercontext is the param name in RegiserAction-validation.xml and logincontext is the param in LoginAction-validation.xml.
Meanewhile, field name is still a member variable in RegisterAction.java and LoginAction.java, which needs to be validated.
User-registercontext-validation.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
3 "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
4 <!-- validator method 2: -->
5
6 <validators>
7 <field name="username">
8 <field-validator type="requiredstring">
9 <message>Your username:</message>
10 </field-validator>
11 </field>
12 <field name="password">
13 <field-validator type="requiredstring">
14 <message>Your password:</message>
15 </field-validator>
16 </field>
17 <field name="email">
18 <field-validator type="requiredstring">
19 <message>Your email:</message>
20 </field-validator>
21 </field>
22 </validators>
User-logincontext-validation.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
3 "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
4 <!-- validator method 2: -->
5
6 <validators>
7 <field name="username">
8 <field-validator type="requiredstring">
9 <message>your username:</message>
10 </field-validator>
11 </field>
12 <field name="password">
13 <field-validator type="requiredstring">
14 <message>your password:</message>
15 </field-validator>
16 </field>
17 </validators>
Now check the file structure which should follow this way:
Now, re-edit register.jsp and login.jsp which have the corresponding fielderrors:
register.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib prefix="s" uri="/struts-tags"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>New User Registration</title>
9 </head>
10 <body>
11 <s:form action="register" theme="simple">
12 <table style="border-collapse: collapse" align="left"
13 bordercolor=#3f8805 cellspacing=0 cellpadding=0 width="20%" border=1>
14 <tr>
15 <td>username</td>
16 <td>
17 <s:fielderror name="user" cssStyle="color:red">
18 <s:param>user.username</s:param>
19 </s:fielderror>
20 <s:textfield name="user.username"></s:textfield>
21 </td>
22 </tr>
23 <tr>
24 <td>password</td>
25 <td>
26 <s:fielderror name="user" cssStyle="color:red">
27 <s:param>user.password</s:param>
28 </s:fielderror>
29 <s:password name="user.password"></s:password>
30 </td>
31 </tr>
32 <tr>
33 <td>re-password</td>
34 <td>
35 <s:fielderror cssStyle="color:red">
36 <s:param>repassword</s:param>
37 </s:fielderror>
38 <s:password name="repassword"></s:password>
39 </td>
40 </tr>
41 <tr>
42 <td>firstname</td>
43 <td><s:textfield name="user.firstname"></s:textfield></td>
44 </tr>
45 <tr>
46 <td>lastname</td>
47 <td><s:textfield name="user.lastname"></s:textfield></td>
48 </tr>
49 <tr>
50 <td>email</td>
51 <td>
52 <s:fielderror name="user" cssStyle="color:red">
53 <s:param>user.email</s:param>
54 </s:fielderror>
55 <s:textfield name="user.email"></s:textfield>
56 </td>
57 </tr>
58 <tr>
59 <td>street address</td>
60 <td><s:textfield name="user.street"></s:textfield></td>
61 </tr>
62 <tr>
63 <td>city</td>
64 <td><s:textfield name="user.city"></s:textfield></td>
65 </tr>
66 <tr>
67 <td>state</td>
68 <td><s:textfield name="user.state"></s:textfield></td>
69 </tr>
70 <tr>
71 <td>zip code</td>
72 <td><s:textfield name="user.zip"></s:textfield></td>
73 </tr>
74 <tr>
75 <td></td>
76 <td><s:submit></s:submit> <s:reset></s:reset></td>
77 </tr>
78 </table>
79 </s:form>
80 </body>
81 </html>
login.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib prefix="s" uri="/struts-tags"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>Login</title>
9 </head>
10 <body>
11 <%-- action="login" actually can work with this error. --%>
12 <s:form action="login" theme="simple">
13 <table style="border-collapse: collapse" align="left"
14 bordercolor=#3f8805 cellspacing=0 cellpadding=0 width="20%" border=1>
15 <tr>
16 <td>username</td>
17 <td>
18 <s:fielderror name="user" cssStyle="color:red">
19 <s:param>user.username</s:param>
20 </s:fielderror>
21 <s:textfield name="user.username"></s:textfield>
22 </td>
23 </tr>
24
25 <tr>
26 <td>password</td>
27 <td>
28 <s:fielderror name="user" cssStyle="color:red">
29 <s:param>user.password</s:param>
30 </s:fielderror>
31 <s:password name="user.password"></s:password>
32 </td>
33 </tr>
34 <tr>
35 <td></td>
36 <td>
37 <s:submit></s:submit>
38 <s:reset></s:reset>
39 </td>
40 </tr>
41 </table>
42 </s:form>
43 </body>
44 </html>
Be careful about fielderror name and s:param's text.
The result are like these 2:
Now I have finished all the detail configurations. There're 3 kinkds of servier side validators.
About the validator type, such as 'required', 'requiredstring', 'data' and their value scope will be introduced later.