Struts <html:text> textbox example

Download this Struts text box example – Struts-TextBox-Example.zip

In this Struts example, you will learn how to create a HTML text box input field with Struts <html:text> tag, validate the text box with ActionForm, display the error message with ActionErrors, and also message resource in JSP page.

1. Folder Structure

This is the final project structure created by Maven. Please create the corresponding folders.

Struts-text-box-folder

2. Action class

Create an Action class, do nothing but forward the request.

UserAction.java


package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class UserAction extends Action{
	
	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {
		
		return mapping.findForward("success");
	}
	
}

3. Properties file

Create a properties file, and declare the error and label messages.

Common.properties


#common module error message
error.common.name.required = Name is required.

#common module label message
label.common.name = UserName
label.common.button.submit = Submit
label.common.button.reset = Reset

4. ActionForm

Create a ActionForm, accept a username and validate it in validate() method. If the username is empty, get a error message from the above properties file, and add it as key “common.name.err” in ActionErrors, later will use this name “common.name.err” to display the error message in JSP.

UserForm.java


package com.mkyong.common.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class UserForm extends ActionForm{
	
	String username;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
	HttpServletRequest request) {
		
	   ActionErrors errors = new ActionErrors();
	      
	    if( getUsername() == null || ("".equals(getUsername()))) {
	       errors.add("common.name.err",
                         new ActionMessage("error.common.name.required"));
	    }
	      
	    return errors;
	}
	
	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// reset properties
		username = "";
	}
	
}

5. JSP Page

Use the Struts’s HTML tag <html:text> to create a HTML text box input field. The label message is declared in above properties file, you can get it via <bean:message key=”label_name” /> directly.

The error message can display in two ways :

  1. Display all error messages
    
    
  2. Display specified error message by specify the error message key which declared in ActionErrors.
    
    	
    
    

login.jsp

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





Struts html:text example

:

Display the text box input.
welcome.jsp

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





Welcome

6. struts-config.xml

Create a Struts configuration file and link all together.

In action tag attributes :

  • path = web path you access
  • type = your action class
  • name = your action form
  • validate = true will cause ActionForm to validate() method for the form validation
  • input = if the validation false, where to forward?

You have to include your properties file in struts-config.xml file to make Struts aware of your custom resource message.


<message-resources
	parameter="com.mkyong.common.properties.Common" />

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

<struts-config>

	<form-beans>
		<form-bean
			name="userForm"
			type="com.mkyong.common.form.UserForm"/>
	
	</form-beans>

	<action-mappings>
	
	    <action
			path="/LoginPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/login.jsp"/>
	
		<action
			path="/Login"
			type="com.mkyong.common.action.UserAction"
			name="userForm"
			validate="true"
			input="/pages/login.jsp"
			>	
			
			<forward name="success" path="/pages/welcome.jsp"/>
		</action>
	</action-mappings>

	<message-resources
		parameter="com.mkyong.common.properties.Common" />

</struts-config>

7. web.xml

Final step, create a web.xml for the Strut framework integration.


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Maven Struts Examples</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>
    <load-on-startup>1</load-on-startup>
  </servlet>
    
  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app>

Access it

http://localhost:8080/StrutsExample/LoginPage.do

Struts-text-box-example1

If user didn’t fill in the text box and press the submit button, it will display a error message.

Struts-text-box-example2

If user fill in the text box and press the submit button.

Struts-text-box-example3

It will pass the text box input value to the welcome page and display it.

Struts-text-box-example4

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Goutam kumar Giri
Guest
Goutam kumar Giri

Hi mkyong,

When page contain some html structure its not showing in the page.. Please see ur above welcome.jsp and login.jsp, but when i will inspect it its showing.. may be missing of ur span tags with css.

Thanks,
….

fiky yuvita
Guest
fiky yuvita

Can we replace the message with dialog box?

Mike
Guest
Mike
You need the following in the dependencies in pom.xml, no? javax.servlet servlet-api 2.4 provided Then $ mvn package and voila! Also it always takes me several hours to remember that I need a welcome in web.xml. Otherwise the first thing you get is a 404 when you do this: http://localhost:8080/StrutsExample/
Luu Tien Dat
Guest
Luu Tien Dat

Open web.xml and try to adding the following :

pageslogin.jsp

amar
Guest
amar

it is showing errors when deploying it into eclipse

Ronnie She Chien Wei
Guest
Ronnie She Chien Wei

Hi Mkyong,

Thanks for sharing this example which i think is good for my study on STRUT. When i try to execute access the log in page, i have the following error:-

org.apache.jasper.JasperException: The absolute uri: http://struts.apache.org/tags-bean cannot be resolved in either web.xml or the jar files deployed with this application
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:50)
org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:114)
org.apache.jasper.compiler.TagLibraryInfoImpl.generateTLDLocation(TagLibraryInfoImpl.java:316)
org.apache.jasper.compiler.TagLibraryInfoImpl.(TagLibraryInfoImpl.java:147)
org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:423)
org.apache.jasper.compiler.Parser.parseDirective(Parser.java:492)
org.apache.jasper.compiler.Parser.parseElements(Parser.java:1552)
org.apache.jasper.compiler.Parser.parse(Parser.java:126)
org.apache.jasper.compiler.ParserController.doParse(ParserController.java:211)
org.apache.jasper.compiler.ParserController.parse(ParserController.java:100)
org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:146)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:286)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:267)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:255)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:563)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:293)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

I follow this step by step solution provided in your site — http://www.mkyong.com/struts/the-absolute-uri-httpstruts-apache-orgtags-bean-cannot-be-resolved-in-either-web-xml-or-the-jar-files-deployed-with-this-application/

still i get the same error. Kindly advice, thanks!

tuyentv
Guest
tuyentv

Thank’s you for share, it is excellent.
But, i don’t know, when i click button submit then it is show messages error:cannot be cast to org.apache.struts.action.Action.
I very hope help from you.

Thank’s verry much.

tuyentv
Guest
tuyentv

Oh, I see and fix success. :)

tuyentv
Guest
tuyentv

Thank’s for share.It is excellent
but, I don’t know, when i click submit then it show messages error: cannot be cast to org.apache.struts.action.Action.
I hope get help from you.
Thank’s you very much.

Cyril
Guest
Cyril

Nice tutorial…:) Thanx…!

Ganesh
Guest
Ganesh

Reset is not working .

SPBalamurugan
Guest
SPBalamurugan

Useful tutorial. Thanks.

vaishali
Guest
vaishali

Does this do encoding bydefault?

vaishali
Guest
vaishali

html:text tag encode string?

jeevan reddy
Guest
jeevan reddy

how to genarate calendar component in jsp page by usig struts

ammu
Guest
ammu

good…

trackback
How To Start Your Career As A Notary Public | national-notary-publics.com

[…] Struts textbox example […]

Pradeep
Guest
Pradeep

good tutorial for beginners..
Thank you.

vijay Gupta
Guest
vijay Gupta

very nice tutorial :)

trackback
Struts DynaActionForm example | Struts

[…] Struts <html:text> textbox example will be refactor to use the “DynaActionForm” instead of normal […]

trackback
Cainan At his PET SHOW | Pet Name Tags | Dog Tags | Pet ID Tags

[…] Struts <html:text> textbox example | struts […]