Tuesday 12 May 2015

Struts2 : Get HttpServletRequest object

If you want to access, HttpServletRequest object from your action class, you can do this by implementing ServletRequestAware interface.

Step 1: Create new maven project “struts_tutorial”. Follow first 3 steps from the following link to make the project setup.


Step 2: Create new jsp file “register.jsp”.

register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!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>
 <form method="post" action="registration">
  User Name : <input type="text" name="userName" /><br /> passowrd : <input
   type="password" name="password" /><br /> mailId : <input
   type="text" name="mailId" /><br /> <input type="submit"
   value="submit" />
 </form>
</body>
</html>

Step 3: create struts.xml. Since Struts 2 requires struts.xml to be present in classes folder. So create struts.xml file under the WebContent/WEB-INF/classes folder. Eclipse does not create the "classes" folder by default, so you need to do this yourself. To do this, right click on the WEB-INF folder in the project explorer and select New > Folder.

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="registration" class="learn.struts.RegisterAction">
   <result name="hello">/helloWorld.jsp</result>
  </action>
 </package>
</struts>


Step 4: Create a package “learn.struts”. Create class RegisterAction.java inside this package.

package learn.struts;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

public class RegisterAction implements ServletRequestAware {

 private HttpServletRequest request;

 public String execute() {
  System.out.println(request.getParameter("userName"));
  System.out.println(request.getParameter("password"));
  System.out.println(request.getParameter("mailId"));
  return "hello";

 }

 @Override
 public void setServletRequest(HttpServletRequest request) {
  this.request = request;
 }

}
Run register.jsp, with some inputs, you will get the input data in console.

Final project structure looks like following.




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment