0

I am beginner in JSP and Servlets. I have searched about the issue and couldn't found exactly what the solution is.

I am passing data from jsp to servlet and inserting in database and from there retrieving the same and passing to JSP for display

I was able to pass data from JSP and insert in database successfully but unable to retrieve and display in jsp again. Below is code.

jsp:

<!DOCTYPE HTML><%@page language="java"
    contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>loginform</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form name=loginform action=TestServlet method=post>


Input ID <input type=text name="id" size=10></input> <br><br>

<Input type="button" value=Retrive> <br>
<label for = "getdata" ></label> <br>

value is <%= request.getSession().getAttribute("data") %>
<input type=submit value=submit></input>
</form>

</body>
</html>

Servlet:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.sql.*;

/**
 * Servlet implementation class TestServlet
 */
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

         response.setContentType("text/html");

          // Actual logic goes here.
         try {

             String getvalue=request.getParameter("id");
             PrintWriter out = response.getWriter();
             out.println(getvalue);
             out.println("attempting to read from table");

             Class.forName("oracle.jdbc.driver.OracleDriver");              
            // Open a connection
             Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@IP:Port:ServiceName, UN, Pass);
                             // Execute SQL query
             Statement stmt = conn.createStatement();
             String sqlinsert, sqlselect;
             sqlinsert = "Insert into abc(abc) values("+getvalue+")";
             sqlselect="Select abc from abc";

             ResultSet rs = stmt.executeQuery(sqlinsert);
             ResultSet rs1 = stmt.executeQuery(sqlselect);
             int id=0 ;
             // Extract data from result set
             while(rs1.next()){
                //Retrieve by column name
                id  = rs1.getInt("ABC");

                //Display values

                out.println("ID: " + id + "<br>");

             }
             HttpSession session = request.getSession(false); 
             request.setAttribute("data",  "0");
                request.getRequestDispatcher("/loginform.jsp").forward(request, response);
            // out.println("</body></html>");

             // Clean-up environment
             rs.close();
             stmt.close();
             conn.close();
          }catch(SQLException se){
             //Handle errors for JDBC
             se.printStackTrace();
          }catch(Exception e){
             //Handle errors for Class.forName
             e.printStackTrace();
          }

    }

}

I am unable to understand where is the problem. Every time I run the code I am able to see only null in JSP.

0

3 Answers 3

2

Simply change request.getSession().getAttribute("data") to request.getAttribute("data") and it will work fine.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked.. can you please explain what is the exact problem with the syntax.
you have set the data into your request, so definitely you will be getting it from there. :)
2

In your Java code you use request.setAttribute("data", "0"); ,but in you JSP page you use request.getSession().getAttribute("data") ,so you will not get the data.

2 Comments

Thanks for your reply.. Can you please explain more and what should I edit to get data
In your servlet you set data in your request scope ,but in jsp page you get it from your session scope. you should get from request too. in jsp page you can change it to request.getAttribute("data");
1

you are actually storing your data in session and try to fetch it from request scope so i think you are getting null value.

in jsp remove <%= request.getSession().getAttribute("data") %> line and use this line <%= request.getAttribute("data") %>

2 Comments

Thanks for your answer
@Siva I think you are confused with scope. You were storing data in session scope and try to fetch it from request scope. You can do vice versa too. Means if you don't want to change your jsp code than in servlet store data in session scope but after using data you have to invalidate session or remove that attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.