user3441151 user3441151 - 1 year ago 103
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) { = 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=""%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<form action="loginServlet" method="post">
<td>First Name :
<td><input type="text" value="" name="txtFirstname"
value='<%=((Test_Object) request.getAttribute("reqObj")).getFirst_name()%>' /></td>
<td>Email :</td>
<td><input type="text" name="txtEmail"
value='<%=request.getParameter("email")%>' /></td>
<tr align="center">
<td colspan="2"><input type="submit" value="Submit" /></td>

My servlet code

String jb = "{\"email\":\"\",\"fname\":\"test01\"}";
JSONObject jsonObject = new JSONObject(jb);
Test_Object obj = new Test_Object();"email");
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 Source

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="${}" 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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download