1.Custom Validation
2.Bundled validation
Custom Validation
Step 1: Add Required Jar files
Step 2: Create home.jsp
home.jsp<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form action="register">
<s:textfield name="name" label="Name"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:submit value="Register"></s:submit>
</s:form>
Step 3 : Create Action Class(src-->package-->Action name)
RegisterAction.java
package com.jeni;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private String name,password;
//create getter and setter here
public void validate() {
if(name.length()<1)
addFieldError("name","must be type some values");
if(password.length()<6)
addFieldError("password","Password must be greater than 5");
}
public String execute()
{return SUCCESS;}}
Step 4: Create struts.xml and web.xml
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts><package name="default" extends="struts-default">
<action name="register" class="com.jeni.RegisterAction">
<result name="success">welcome.jsp</result>
<result name="input">home.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://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>StrutsValidation</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>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
</web-app>
Step 5 Create Success and error page
welcome.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>Name:<s:property value="name"/><br/>
Password:<s:property value="password"/><br/>
Output
No comments:
Post a Comment