Saturday 24 October 2015

Struts2: ServletActionContext

ServletActionContext is a sub class of ActionContext which provides access to things like the action name, value stack etc., ServletActionContext class provides static methods, by using these you can access HttpServletRequest, HttpServletResponse, ServletContext, PageContext, ActionContext, ActionMapping.

Following example explains you how to access request parameters using ServletActionContext.

Note:
Don't call the methods on the ServletActionContext from an action class's constructor because at this stage the underlying ActionContext object has not been passed to it. So you will get null response.

Following application takes employee information using jsp page and print them in console.

Define model class Employee
Employee class is used to hold request parameters.
package strutstutorial.model;

public class Employee {
  private String firstName;
  private String lastName;
  private int age;
  private String password;
  private String confPassword;
  private int id;

  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;
  }

  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 int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("Employee [firstName=").append(firstName)
        .append(", lastName=").append(lastName).append(", age=")
        .append(age).append(", password=").append(password)
        .append(", confPassword=").append(confPassword).append(", id=")
        .append(id).append("]");
    return builder.toString();
  }

}

Define action class
LoginAction class use Employee as model.
package strutstutorial.actions;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import strutstutorial.model.Employee;

import com.opensymphony.xwork2.ModelDriven;

public class LoginAction implements ModelDriven<Employee> {
  /* Must initialize this instance */
  private Employee employee = new Employee();

  public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    System.out.println("Hello");
    System.out.println(employee);

    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");
    String age = request.getParameter("age");
    String id = request.getParameter("id");

    System.out.println("Request parameters are");
    System.out
        .println(firstName + "\t" + lastName + "\t" + age + "\t" + id);

    return "success";
  }

  @Override
  public Employee getModel() {
    return employee;
  }
}


Define 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="login" method="post">
    <s:textfield name="id" label="id" size="20" />
    <s:textfield name="firstName" label="First Name" size="20" />
    <s:textfield name="lastName" label="Last Name" size="20" />
    <s:password name="password" label="password" size="20" />
    <s:password name="confPassword" label="confPassword" size="20" />
    <s:textfield name="age" label="age" size="3" />

    <s:submit name="submit" label="Submit" align="center" />
  </s:form>
</body>
</html>


Define success.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>
  <h1>Login successfull</h1>
</body>
</html>


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="login" class="strutstutorial.actions.LoginAction">
      <result name="success">/success.jsp</result>
      <result name="input">/login.jsp</result>
    </action>

  </package>
</struts>


web.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="login" class="strutstutorial.actions.LoginAction">
      <result name="success">/success.jsp</result>
      <result name="input">/login.jsp</result>
    </action>

  </package>
</struts>


Total project structure looks like below.


Run login.jsp and input some information, you will get employee details in console.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment