Thursday 23 July 2015

Struts2 validation example

In this post, I am going to explain how to validate simple login form using struts2. You can perform client side validation using java script, some times, you need to perform server side validation also, you can achieve this by using Struts2.

Create a simple login page

login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <s:form action="LoginAction" method="post">
    <s:textfield name="name" label="name" size="20" />
    <s:password name="password" label="password" size="20" />
    <s:password name="confPassword" label="password" size="20" />
    <s:submit name="submit" label="Submit" align="center" />
  </s:form>
</body>
</html>

create view

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <h1>Login successfull</h1>
</body>
</html>


Create action class

package strutstutorial.actions;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
  private String name;
  private String password;
  private String confPassword;

  public String execute() {
    return SUCCESS;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getConfPassword() {
    return confPassword;
  }

  public void setConfPassword(String confPassword) {
    this.confPassword = confPassword;
  }

  public void validate() {
    if (name == null || name.length() < 5) {
      addFieldError("name", "The name is required");
    }

    if (password == null || password.length() < 5) {
      addFieldError("password",
          "Password must contains atleast 5 characters");
    }

    if (!(password.equals(confPassword))) {
      addFieldError("confPassword",
          "Password and confPassword must equal");
    }
  }
}


As shown above, validate method checks
1.   Whether name field has a value of minimum 5 characters or not
2.   Whether password field has minimum 5 characters in length
3.   Whether password and confPassword are equal or not.

Configuration files
struts.xml

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

<struts>
  <package name="default" extends="struts-default">
    <action name="LoginAction" class="strutstutorial.actions.LoginAction">
      <result name="success">/success.jsp</result>
      <result name="input">/login.jsp</result>
    </action>
  </package>
</struts>


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>struts_tutorial</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <display-name>Struts2 Demo App</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Now run login.jsp file on server, You will get following screen.



Now submit the form, without entering any data, you will get following screen.



How validation works?
Once the action submitted, before execution of action, validate method is called. Struts 2 will call its addFieldError method for invalid conditions. If any errors have been added then Struts 2 will not proceed to call the execute method.

So when validation fails, Struts 2 returns input, the Struts 2 framework will redisplay the login.jsp file. Since we used Struts 2 form tags, Struts 2 will automatically add the error messages just above the form filed.
Complete project structure looks like following.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment