Showing posts with label Struts. Show all posts
Showing posts with label Struts. Show all posts

September 30, 2011

Accessing request headers in a Struts 2 action

1) Create an action class - HeaderReader.java - in the src folder of the web application

package info.icontraining.struts2;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class HeaderReader extends ActionSupport implements ServletRequestAware {

   private HttpServletRequest request;
 
   public void setServletRequest(HttpServletRequest request) {
      this.request = request;
   }
 
   public String execute() {

      Enumeration e = request.getHeaderNames();
      String headerName = null;

      while(e.hasMoreElements()) {
         headerName = (String) e.nextElement();
         System.out.println(headerName + ": "); 
         System.out.println(request.getHeader(headerName) + "\n");
      }

      return SUCCESS;
   } 
}

2) Add a headers.html file to the WebContent folder of the web application

<html>
<body>
Check Server console log for Header names and values
</body>
</html>

3) Configure the action class in the struts.xml configuration file

<action name="headerReader" class="info.icontraining.struts2.HeaderReader">
   <result>headers.html</result> 
</action>

4) Test the example by accessing the following URL,

http://localhost:8080/WebAppName/headerReader.action

Setting a cookie in the response in Struts 2

1) Create an action class - CookieWriter.java - in the src folder of the web application

package info.icontraining.struts2;

import javax.servlet.http.Cookie;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CookieWriter extends ActionSupport {

   public String execute() throws Exception {
      ServletActionContext.getResponse()
                    .addCookie(new Cookie("firstName", "Dinesh"));
      return SUCCESS;
   }
}

2) Create the result JSP - cookieWrite.jsp - in the WebContent folder of the web application. The JSP displays the cookie sent in the response

<html>
<head>
<script type="text/javascript">

function readCookie(name) {
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') 
         c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) 
         alert("value of " + name + " cookie is " 
                    +  c.substring(nameEQ.length,c.length));
   }
   return null;
}
</script>
</head>
<body>
Setting cookie that came with the response.<br/><br/>
<a href="javascript:readCookie('firstName')" href="#">Read cookie</a>

</body>
</html>

3) Configure the action in the struts.xml configuration file

<action name="cookieWrite" class="info.icontraining.struts2.CookieWriter">
   <result>/cookieWrite.jsp</result>
</action>

4) Test the code by accessing the URL in the browser,

http://localhost:8080/WebAppName/cookieWrite.action

Reading a cookie from the request in Struts2

1) Create an action class - CookieReader.java - in the src folder of the Struts 2 enabled Web Application

package info.icontraining.struts2;

public class CookieReader {
 
   private String message;
   private String userName;
   public static final String SUCCESS = "success";

   public String getUserName() {
      return userName;
   }

   public void setUserName(String userName) {
      this.userName = userName;
   }

   public void setMessage(String message) {
      this.message = message;
   }
   
   public String getMessage() {
      return this.message;
   }
   
   public String execute() throws Exception {
      setMessage("Hello " + getUserName());
      return SUCCESS;
   }
}

2) Create the result JSP - cookieRead.jsp - in the WebContent folder of the web application

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Cookie Read Example</title>
</head>
<body>
   <h1><s:property value="message"/></h1>
</body>
</html>

3) Configure the action in the struts.xml, along with the configuration for the cookie interceptor. The <param> element indicates the name of the cookie that to be read from the request,

<action name="cookieRead" class="info.icontraining.struts2.CookieReader">
   <result>/cookieRead.jsp</result>
   <interceptor-ref name="cookie">
      <param name="cookiesName">userName</param>
   </interceptor-ref>
</action>

4) Create an .html file to set the cookie on the browser - cookieTest.html - add the file to the WebCon tent folder of the web application

<html>
<head>
<script type="text/javascript">
   document.cookie="userName=dinipc";
</script>
</head>
<body>
Cookie userName set.
</body>
</html>

5) Test the example by first accessing the cookieTest.html from the browser. This will set the cookie.

http://localhost:8080/WebAppName/cookieTest.html

Next, access the cookieRead.jsp from the browser

http://localhost:8080/WebAppName/cookieRead.jsp

September 28, 2011

Changing the Struts2 default .action extension

In order to change the default extension, which is .action, in Struts 2 to something else, configure the <constant> element in the struts.xml configuration file as follows,

<struts>
   
   <constant name="struts.action.extension" value="dud"/>

   <package name="myPackage" extends="struts-default">
   
   ...

   </package>
</struts>

Test the Hello World - Struts 2 example with the following URL in the browser,

http://localhost:8080/WebAppName/Name.dud

Session Management Example in Struts2

0|) Implement the Hello World Example for the Struts 2 framework as explained in this example

1) Modify the execute() method within the HelloWorld.java action class to set a session attribute on the SessionMap object as follows,

public String execute()  {

   ActionContext context = ActionContext.getContext();
     
   ((SessionMap) context.getSession()).put("username", getName());
     
   setCustomGreeting( GREETING + getName() );
   return Action.SUCCESS;
}

2) Modify the Hello.jsp result JSP to add an additional link as follows,

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
  <title>HelloWorld</title>
</head>
<body>

  <h1><s:property value="customGreeting"/></h1>
  <br/><br/>

  <s:a action="Linked">Click here</s:a>
</body>
</html>

3) Add a JSP - linkedPage.jsp - in the WebContent folder of the Web application,

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
  <title>Linked Page</title>
</head>
<body>
   <h1>In Linked Page: <s:property value="%{#session.username}"/></h1>
</body>
</html>

4) Configure the new action in the struts.xml file as follows,

<action name="Linked">
   <result>/linkedPage.jsp</result>
</action>

5) Test the example with the following URL in the browser,

http://localhost:8080/WebAppName/Name.action

April 13, 2011

Struts 2 - Transferring data onto JavaBean objects

1) Create a Register.jsp page as shown in the code below,

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Register Page</title>
</head>
<body>
<h4>Enter Registration Information!</h4>
  
   <s:form action="doRegister">
      <s:textfield name="person.firstname" label="First Name"/>
      <s:textfield name="person.lastname" label="Last Name"/>
      <s:textfield name="person.age" label="Age"/>
      <s:submit/>
   </s:form>

</body>
</html>

2) Create the Register.java action class that contains the JavaBean object into the properties of which the incoming request data is to be transferred.


package info.icontraining.struts2;

import com.opensymphony.xwork2.*;

public class Register extends ActionSupport {

   public String execute() {
       return Action.SUCCESS;
   }
 
   private PersonBean person;

   public PersonBean getPerson() {
       return person;
   }
   public void setPerson(PersonBean person) {
       this.person = person;
   }
 
   public void validate() {
  
       if ( person.getFirstname().length() == 0 ){ 
            addFieldError( "person.firstname", "First name is required." );
       }
       if ( person.getLastname().length() == 0 ){ 
            addFieldError( "person.lastname", "Last name is required." );
       }
       if ( person.getAge() < 18 ){ 
            addFieldError( "person.age", "Age required & must be > 18" );
       }
   }  
}


3) Create the PersonBean.java class that is the JavaBean class in question,

package info.icontraining.struts2;

public class PersonBean {
 
   private String firstname;
   private String lastname;
   private int age;
 
   public String getFirstname() {
       return firstname;
   }
   public void setFirstname(String firstname) {
       this.firstname = firstname;
   }
   public String getLastname() {
       return lastname;
   }
   public void setLastname(String lastname) {
       this.lastname = lastname;
   }
   public int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }
}

4) Create the RegisterDone.jsp page that displays the incoming request data,

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Register Done</title>
</head>
<body>
<h1>Thank You</h1>
<h3>for Registering!</h3>
<s:property value="person.firstname"/>
<s:property value="person.lastname"/>
<s:property value="person.age"/>

</body>
</html>

5) Configure the struts2 actions in the struts.xml file,

<action name="Register">
     <result>/Register.jsp</result>
</action>
  
<action name="doRegister" class="info.icontraining.struts2.Register">
     <result>/RegisterDone.jsp</result>
     <result name="input">/Register.jsp</result>
</action>

6) Test the code by typing the following URL in the browser,

http://localhost:8080/WebAppName/Register.action

Struts 2 - Externalizing String literals using Resource Bundles

Modify the example code at the following link - http://www.javaissues.com/2011/04/struts-2-basic-validation-with-validate.html

1) In the Login.java class modify the validate() method as follows:

public void validate() {
  
   boolean flag = false;
  
   if (getUsername().length() == 0) {
      addFieldError("username", getText("username.required"));
      flag = true;
   }
  
   if (getPassword().length() == 0) {
      addFieldError("password", getText("password.required"));
      flag = true;
   }
  
   if (!flag) 
      if (!getUsername().equals("dinesh") && !getPassword().equals("dinesh")) {
         addActionError(getText("username.password.incorrect"));
      }
   }

2) Add 2 resource bundles (.properties files) in the same package as the Login.java class. The details of the files are below,

Login.properties

username.required=Username is required
password.required=Password is required
username.password.incorrect=Username and/or Password is Incorrect

Login_hi.properties

username.required=Username is required in Hindi
password.required=Password is required in Hindi
username.password.incorrect=Username and/or Password is Incorrect in Hindi

3) Test the code by typing the following URL in the browser

http://localhost:8080/WebAppName/Login.action

Now, change the language setting in the browser to Hindi [hi] and type the above URL again in the browser.

April 12, 2011

Struts 2 Basic Validation with validate() method

1) Create a login.jsp page in the WebContent folder of the web application. The struts tag <s:actionerror> will display any validation error messages in the input.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h4>Enter your Username and Password!</h4>
<s:actionerror />
<s:form action="doLogin">
     <s:textfield name="username" label="Username"/>
     <s:password name="password" label="Password"/>
     <s:submit/>
</s:form>
</body>
</html>

2) Add a Login.java action class in the src folder - the action class must extend the ActionSupport class in order to avail of the basic (programmatic) validation support of Struts2.

package info.icontraining.struts2;

import com.opensymphony.xwork2.*;

public class Login extends ActionSupport {

   public String execute() {
      return Action.SUCCESS;
   }
 
   private String username;
   private String password;
 
   public String getUsername() {
      return username;
   }
   public void setUsername(String username) {
      this.username = username;
   }
   public String getPassword() {
      return password;
   }
   public void setPassword(String password) {
      this.password = password;
   }
 
   public void validate() {
  
      boolean flag = false;
  
      if (getUsername().length() == 0) {
         addFieldError("username", "Username is required");
         flag = true;
      }
  
      if (getPassword().length() == 0) {
         addFieldError("password", "Password is required");
         flag = true;
      }
  
      if (!flag) 
         if (!getUsername().equals("dinesh") && !getPassword().equals("dinesh")) {
            addActionError("Username and/or Password incorrect. Please try again!");
         }
      }
}

The validate() method within the action class contains the code to validate the incoming user data. If validation errors occur it invokes the addFieldError() or the addActionError() methods.

3) Configure the struts.xml for the 2 actions, as follows,

<action name="Login">
 <result>/login.jsp</result>
</action>
  
<action name="doLogin" class="info.icontraining.struts2.Login">
 <result>/welcome.jsp</result>
 <result name="input">/login.jsp</result>
</action>

4) Create the welcome.jsp page which will be displayed when the user data is successfully validated

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<h1>Welcome!</h1>
<h3>You have successfully logged in.</h3>
</body>
</html>

5) Test the code example by typing the following URL in the browser

http://localhost:8080/WebAppName/Login.action

- Press Submit without typing anything in the text fields
- Press Submit after typing in any one of the text fields
- Press Submit after typing something in both the text fields
- Press Submit after typing 'dinesh' in both the text fields

March 15, 2011

Struts 1.x - Validator Framework Example

We shall replace the validate() method in this example - http://www.javaissues.com/2011/03/struts-1x-reset-and-validate-methods-in.html with the Validator Framework

In addition to the Struts 1.3.8 jars and the Apache Commons jars, also add the Jakarta-Oro jar into the lib folder of your application. Download the oro jar from here

1) Change the LoginForm.java file to make the LoginForm class extend from the ValidatorForm class instead of the ActionForm class. Also remove the validate() method from the LoginForm class.

public class LoginForm extends ValidatorForm {
      ...
}


2) Modify the struts-config.xml file to add the <plug-in> element,

<struts-config>
   ...   
   <message-resources parameter="ApplicationResources" />

   <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
      <set-property property="pathnames" value="/org/apache/struts/validator/validator-rules.xml,/WEB-INF/validation.xml"/>
   </plug-in>
</struts-config>


3) Add a new validation.xml file to the WEB-INF folder of the web application, as below. This configuration will validate the username and password fields for required field validation and also for the form input to comply/match the regular expressions.

<!DOCTYPE form-validation PUBLIC
        "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"
        "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">

<form-validation>
 
   <global>
      <constant>
         <constant-name>id</constant-name>
         <constant-value>^([a-zA-Z_]{1}[a-zA-Z0-9_-]{7,14})$</constant-value>
      </constant>
      <constant>
         <constant-name>pass</constant-name>
         <constant-value>^([a-zA-Z0-9_-]{8,15})$</constant-value>
      </constant>
   </global>

   <formset>
      <form name="loginForm">
         <field property="username" depends="required,mask">
            <arg position="0" key="username.required"/>
            <var>
               <var-name>mask</var-name>
               <var-value>${id}</var-value>
            </var>
         </field>
         <field property="password" depends="required,mask">
            <arg position="0" key="password.required"/>
            <msg name="mask" key="password.maskmsg" />
            <var>
               <var-name>mask</var-name>
               <var-value>${pass}</var-value>
            </var>
         </field>
      </form>
   </formset>
 
</form-validation>


4) In the message resources bundle, the ApplicationResources.properties file, add the following messages,

# Struts Validator Error Messages
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.

username.required=Username
password.required=Password
password.maskmsg=Password should be of length between 8 and 15 characters


5) Open the following URL in the browser and test for required field validation as well as form field input validation that complies with the regular expressions in the validation.xml

http://localhost:8080/WebAppName/login.jsp

March 7, 2011

Struts 1.x - reset() and validate() methods in ActionForm

To setup the Struts Framework in your J2EE web application, visit the following post - http://www.javaissues.com/2011/03/struts-1x-hello-world-example.html

Create login.jsp

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<html>
<body>
   <html:errors />
   <form action="login.do" method="post">
      <input type="text" name="username" /> <br/>
      <input type="password" name="password" /> <br/>
      <input type="submit" value="Submit" />
   </form>
</body>
</html>


Create LoginForm.java

package info.icontraining.struts;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;

public class LoginForm extends ActionForm {

   private String username;
   private String password;
 
   public String getUsername() {
      return username;
   }
   
   public void setUsername(String username) {
      this.username = username;
   }
 
   public String getPassword() {
      return password;
   }
 
   public void setPassword(String password) {
      this.password = password;
   }
 
   public void reset(ActionMapping mapping, HttpServletRequest request) {
      username = null;
      password = null;
   }
 
   public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
      ActionErrors errors = new ActionErrors();
  
      if ((username == null) || (username.length() <= 0) ) {
          errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.username"));
      }
      if ((password == null) || (password.length() < 8)) {
          errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.password"));
      }
      return errors;
   }
}


Create LoginAction.java

package info.icontraining.struts;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.struts.action.*;

public class LoginAction extends Action {

   public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
  
      String username = ((LoginForm)form).getUsername();
      String password = ((LoginForm)form).getPassword();
  
      if (username.equals("abc") && password.equals("def")) {
          return mapping.findForward("success");
      } else {
          return mapping.findForward("failure");
      }  
   }
}


Create ApplicationResources.properties and place it in the src folder (in Eclipse) or in the default package

error.username=Username is required<br/>
error.password=Password must contain minimum 8 characters<br/>


Add the following configuration to struts-config.xml

<struts-config>
...
   <form-bean name="loginForm" type="info.icontraining.struts.LoginForm" />
   ...

   <action path="/login" type="info.icontraining.struts.LoginAction" name="loginForm" validate="true" input="/login.jsp"> 
      <forward name="success" path="/loginSuccess.jsp" />
      <forward name="failure" path="/loginFailure.jsp" /> 
   </action>

   ...
   <message-resources parameter="ApplicationResources" />
...
</struts-config>


Visit the following URL in the browser,

http://localhost:8080/WebAppName/login.jsp

javax.servlet.jsp.JspException: Cannot find message resources under key org.apache.struts.action.MESSAGE


Topic:  Struts 1.3.8

Application Server: JBoss 4.2.2GA

Exception:


ERROR [[jsp]] Servlet.service() for servlet jsp threw exception
javax.servlet.jsp.JspException: Cannot find message resources under key org.apache.struts.action.MESSAGE
at org.apache.struts.taglib.TagUtils.retrieveMessageResources(TagUtils.java:1112)
at org.apache.struts.taglib.TagUtils.present(TagUtils.java:1055)
at org.apache.struts.taglib.html.ErrorsTag.doStartTag(ErrorsTag.java:200)
at org.apache.jsp.login_jsp._jspx_meth_html_005ferrors_005f0(login_jsp.java:156)
at org.apache.jsp.login_jsp._jspx_meth_html_005fform_005f0(login_jsp.java:112)
at org.apache.jsp.login_jsp._jspService(login_jsp.java:77)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:373)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:336)



Resolution:

To resolve this error, first add a message resources bundle (a .properties file) to the Struts-enabled web application - the file should be placed in the classpath of the application.

Next, configure the file information in the struts-config.xml Struts configuration file, by adding the <message-resources> element as below,

<message-resources parameter="resources.ApplicationResources" />

where resources.ApplicationResources is the fully-qualified name (reflecting the package structure) of the file ApplicationResources.properties (the .properties extension is not required in the configuration).

March 6, 2011

Struts 1.x - Hello World Example

Download the Struts 1.3.8 jars from here, unzip and copy them to the lib folder of the web application

Download the Apache Commons jars (Struts dependencies) from here, unzip and also copy to the lib folder of the web application

Add the following Servlet configuration to the web.xml file of the web application:

<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>application</param-name>
      <param-value>resources.application</param-value>
    </init-param>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</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>


Create a struts-config.xml file in the WEB-INF folder of the web application and add the following content in it:

<?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="helloForm" type="info.icontraining.struts.HelloForm" /> 
  </form-beans>

  <action-mappings>
     <action path="/hello" type="info.icontraining.struts.HelloAction" name="helloForm"> 
   <forward name="success" path="/hello.jsp" /> 
     </action> 

  </action-mappings>

</struts-config>


Create a welcome.jsp page

<html>
<body>
<form action="hello.do" method="post">
<input type="text" name="user" />
<input type="submit" name="Submit" />
</form>
</body>
</html>


Create a HelloForm.java class

package info.icontraining.struts;

import org.apache.struts.action.ActionForm;

public class HelloForm extends ActionForm {
 
   private String user;

   public String getUser() {
      return user;
   }

   public void setUser(String user) {
      this.user = user;
   }
}


Create a HelloAction.java class

package info.icontraining.struts;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.struts.action.*;

public class HelloAction extends Action {
 
   public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    
      request.setAttribute("user", ((HelloForm)form).getUser()); 
      return mapping.findForward("success");
   }
}


Create a hello.jsp page

<%@ page isELIgnored="false" %>
<html>
<body>
Welcome, ${requestScope.user}
</body>
</html>


Enter the following URL in the browser to test:

http://localhost:8080/WebAppName/welcome.jsp