Struts HTML Errors Tag ( < html:errors >)

Struts HTML Tag Library

Struts HTML tag library provides tags which are used to create input forms and HTML user interfaces. The tags in the Struts HTML library form a bridge between a JSP view and the other components of a Web application. Since a dynamic Web application often depends on gathering data from a user, input forms play an important role in the Struts framework. Consequently, the majority of the HTML tags involve HTML forms.

Syntax to use Struts HTML tag library

<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>

< html:errors >

< html:errors > -Displays a set of error messages prepared by a business logic component and stored as an ActionMessages object, an ActionErrors object, a String, or a String array in any scope. If such a bean is not found, nothing will be rendered. This tag displays the messages which are set in the Validate method of the ActioForm. ActionErrors object should be created to hold the error messages.String is passed to the constructor of ActionErrors object. The String is a key from the ApplicationResources.properties file.< html:errors/> Tag will extract the information from ActionErrors object and displays the errors.

Example Code for < html:errors >

Login Application is created with Struts HTML tags and Struts ActionForm which illustrates both the < html:errors/> tag and < html:password/> tag

1.Create an Jsp page and name it as login.jsp.It is the Welcome page for a user.

login.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="html" uri="http://jakarta.apache.org/struts/tags-html" %>
<%@taglib prefix="bean" uri="http://jakarta.apache.org/struts/tags-bean" %>


< html>
    < head>

        < title> HTML Errors example </title>
    < head>
     < body bgcolor="DDDDDD">

        < h1> Struts html:errors/html:password Tag < /h1>
        < html:form action="/login">
             < span style="color:red">
        < html:errors/>
        < /span>
        Enter User Name:< html:text name="loginform" property="uname"/>< br>
        Enter Password:< html:password name="loginform" property="password"/>< br>
        < html:submit/>< html:reset/>
        < /html:form>
    < /body>
</html>

2.Create a Form bean.Form bean is used to hold the properties of the submitted form which is a sub class of ActionForm.Here we have three properties “uname”,”password” and “message” to hold user name,password and message about login.In form bean we have validate method used to validate and if error occured set the error messages to < html:errors/> tag.
loginform.java

package com.myapp.struts;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class loginform extends org.apache.struts.action.ActionForm {

   private String uname;
   private String password;
   private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getPassword() {
        return password;
    }

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

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public loginform() {
        super();

    }


    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { // to check and set the error messages
        ActionErrors errors = new ActionErrors();
        if (uname== null || uname.length() < 1) {
            errors.add('uname', new ActionMessage('errors.uname.required'));


        }
        if (password== null || password.length() < 1) {
            errors.add('password', new ActionMessage('errors.password.required'));

        }
        return errors;
    }
}

3.ApplicationResource.properties file contains the error messages.The String keys (like “errors.uname.required”) are used in Validate function to add a new error.Since the error messages are configured in a seperate properties file they can be changed anytime without making any changes to the java files or the jsp pages.
ApplicationResource.properties

errors.uname.required= UserName Required
errors.password.required= Password Required

4.Simple Action class loginaction.java which is a sub class of Action class used to process the user’s request.In this class we validate for correct username and password is validated perfectly forwards to “success.jsp page” else “failure.jsp page” by setting the corresponding message values to be displayed.
loginaction.java

package com.myapp.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

public class formaction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private final static String SUCCESS = "success";
     private final static String FAILURE = "failure";

    public class loginaction extends org.apache.struts.action.Action {


    private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";


    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        loginform formBean=(loginform)form;
        if(formBean.getUname().equals("user"))
        {
            if(formBean.getPassword().equals("password"))
            {
                formBean.setMessage("Welcome User...");
                return mapping.findForward(SUCCESS);
            }
            else
            {
                formBean.setMessage("Wrong Password");
                return mapping.findForward(FAILURE);
            }
        }
        formBean.setMessage("User Name is Not Correct");
        return mapping.findForward(FAILURE);

    }
}


5.Create or modify struts config file struts-config.xml with action mappings.Struts-config file contains the information about the configuration of the struts framework to the application.It contains the action mappings which helps to select Action,ActionForm and other information for specific user’s request’s.

<?xml version="1.0" encoding="UTF-8" ?>

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

< struts-config>
    < form-beans>
        < form-bean name="loginform" type="com.myapp.struts.loginform"/>
    </form-beans>

< action-mappings>
        < action input="/login.jsp" name="loginform" path="/login" scope="request" type="com.myapp.struts.loginaction" validate="false">
        < forward name="success" path="/success.jsp"/>
		< forward name="failure" path="/failure.jsp"/>
		</action>
</action-mappings>

	</struts-config>

6.Create another simple Jsp page success.jspwhich is for displaying the output Message.If both the username and password are correct(username@user and password@password) the success page is displayed with welcome message.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>

< html>
    < head>
        < meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        < title> Login Success Page </title>
    </head>
    < body bgcolor="#DDDDDD">
	 < h1> Login Success </h1>
       < h2> < bean:write name="loginform" property="message" filter="false"/> < /h2>
       </body>
</html>

7.Create another simple Jsp page failure.jspwhich is for displaying the Failure output Message.If both the username and password are incorrect failure page is displayed along with error message.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>

< html>
    < head>
        < meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        < title> Login Failure Page </title>
    </head>
    < body bgcolor="#DDDDDD">
	 < h1> Login Failed </h1>
       < h2> < span style='color:red'>< bean:write name="loginform" property="message" filter="false"/> < span> < /h2>
       </body>
</html>

8.Building and running the application
Output

Access page:http://localhost:8084/login/

also read:

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*