user3441151 user3441151 - 2 months ago 9
Java Question

set Java class Object values into JSP Page

I want to set Java class Object values into JSP Page.
My Test_Object code

public class Test_Object {
public String email;
public String first_name;

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getFirst_name() {
return first_name;
}

public void setFirst_name(String first_name) {
this.first_name = first_name;
}
}


My test.jsp page

<%@page import="test.io.Test_Object"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>TEST</title>
</head>
<body>
<form action="loginServlet" method="post">
<table>
<tr>
<td>First Name :
<td><input type="text" value="" name="txtFirstname"
value='<%=((Test_Object) request.getAttribute("reqObj")).getFirst_name()%>' /></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="txtEmail"
value='<%=request.getParameter("email")%>' /></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>


My servlet code

String jb = "{\"email\":\"test@xyz.com\",\"fname\":\"test01\"}";
JSONObject jsonObject = new JSONObject(jb);
Test_Object obj = new Test_Object();
obj.email=jsonObject.getString("email");
obj.first_name=jsonObject.getString("fname");
request.setAttribute("reqObj", obj);
RequestDispatcher view = request.getRequestDispatcher("/test.jsp");
view.forward(request, response);


But when i redirect to test.jsp page there is no value display in TextBox.
I am using Eclipse Mars 2 with Java.

Answer

The problem might be in the way you are dispatching the request. In your Servlet you are dispatching the request to the /otn.jsp page. But you are trying to read the properties of the object you put in the request scope in the test.jsp page. So you have to do the following:

  • In the Servlet code:

    RequestDispatcher view = request.getRequestDispatcher("/test.jsp");
    
  • In the test.jsp page change the input elements as follows:

    <input type="text" value="${reqObj.first_name}" name="txtFirstname"/>
    <input type="text" value="${reqObj.email}" name="txtEmail" />
    

I am using here Expression Language with the assumption that you are using one of the current web containers such as Tomcat version 7 and later.

Some minor comments:

  1. Why are you creating the JSONObject eventhough you are not doing anything useful with it in your Servlet code?
  2. When you define Java types (classes, interfaces, ...) use camelcase instead of underscore in the names: use TestObject instead of Test_Object and firstName instead of first_name. Here you'll find naming conventions for Java.
Comments