Stack Exchange
Display database to user on a JSP
I am searching a jsp in which i can access data from servlet,but in that i have the request dipatcher problem,if i write in the block it throws exception,and in the block it loads forever.
There are total 4 files:
1)Servlet naming servlet.java
import java.io.*;
import java.sql.*;

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


public class servlet extends HttpServlet{

    private String username,password;

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException
    {
        res.setContentType("text/html");
        try{
            PrintWriter out = res.getWriter();
            Class.forName("com.mysql.jdbc.Driver");
            String url,user,pass,query,query1,u,p;
            url="jdbc:mysql://localhost:3306/test";
            user="root";
            pass="root";
            //for making Code 4-The best way to work..u have to make below a comment

            /*query="select * from student_data";
            Connection con=DriverManager.getConnection(url,user,pass);
            Statement stmt=con.createStatement();
            ResultSet rs=stmt.executeQuery(query);*/
            //NEW CODE 1-works partially

            /*while(rs.next())
            {
                if(req.getParameter("username").equals(rs.getString("Username")) && req.getParameter("password").equals(rs.getString("Password")))
                {
                    System.out.println("Yout have logged in");
                    PrintWriter out = res.getWriter();
                    out.println("U r succesfull");
                }

                else
                {
                    System.out.println("NOOOOOOOOOOOOOOOO");

                }

            }*/



            //NEW CODE 2-fail
            /*
            if(rs.getString("Username").equals(req.getParameter("username")))
            {
                if(req.getParameter("password").equals(rs.getString("Password")))
                {
                    System.out.println("Yout have logged in");
                    PrintWriter out = res.getWriter();
                    out.println("U r succesfull");
                }


            }

            else
            {
                System.out.println("NOOOOOOOOOOOOOOOO");

            }


            */





            //NEW CODE 3 works

            /*
            while(rs.next())
            {
              if(req.getParameter("username").equals(rs.getString("Username"))) 
               {          
                if(req.getParameter("password").equals(rs.getString("Password")))
                {
                    out.println("<h3>"+"U have logged in succesfully"+"</h3>");
                    break;
                }

                else
                {
                    out.println("<h3>"+"Username or password do not match !"+"</h3>");
                    break;
                }
               }    
              else
                {
                    out.println("<h3>"+"You r not a  registered user,want to register ??"+"</h3>");
                    out.println("<a href='registration.jsp'> Registration</a>");

                    break;

                }
            }*/

            //Code 4-The best way


            //query="select * from student_data where Username="+req.getParameter("username")+"AND Password="+req.getParameter("password");
            /*u=req.getParameter("username");
            p=req.getParameter("password");
            query="select * from student_data where Username='"+u+"' AND Password='"+p+"'";
            Connection con=DriverManager.getConnection(url,user,pass);
            Statement stmt=con.createStatement();
            ResultSet rs=stmt.executeQuery(query);
            if(rs.next())
            {
                RequestDispatcher r=req.getRequestDispatcher("/Jsp/LoggedIn.jsp");
                r.forward(req,res);

            }

            else
            {
                out.println("<h3>"+"Username or password do not match !"+"</h3>");
                out.println("<a href='registration.jsp'> Registration</a>");
            }*/



            /*//Code 5-Passing the user to another JSP after validation and using the data sent from servlet!

            u=req.getParameter("username");
            p=req.getParameter("password");
            query="select * from student_data where Username='"+u+"' AND Password='"+p+"'";
            Connection con=DriverManager.getConnection(url,user,pass);
            Statement stmt=con.createStatement();
            ResultSet rs=stmt.executeQuery(query);
            if(rs.next())
            {
                //by using setAttri and getAttru

                req.setAttribute("Name", u);

                // by using HTTPsession

                HttpSession sess=req.getSession(true);
                sess.setAttribute("Name", u);

                RequestDispatcher r=req.getRequestDispatcher("/Jsp/LoggedIn.jsp");
                r.forward(req,res);

            }

            else
            {
                out.println("<h3>"+"Username or password do not match !"+"</h3>");
                out.println("<a href='registration.jsp'> Registration</a>");
            }*/


//Code 6-Passing the user to another JSP after validation and display the database to logged user - diplaying just one row-UnderContruction!

            u=req.getParameter("username");
            p=req.getParameter("password");
            query="select * from student_data where Username='"+u+"' AND Password='"+p+"'";
            Connection con=DriverManager.getConnection(url,user,pass);
            Statement stmt=con.createStatement();
            ResultSet rs=stmt.executeQuery(query);
            if(rs.next())
                {
                    query1="select * from student_data";
                    Statement stmt1=con.createStatement();
                    ResultSet rs1=stmt1.executeQuery(query1);
                    String n,s;
                    RequestDispatcher r = null;
                    int i,row;
                    while(rs1.next())
                    {   
                    rs1.last();
                    row=rs1.getRow();
                    rs1.first();


                    i=rs1.getInt("Id");
                    req.setAttribute("Id", i);

                    n=rs1.getString("Name");
                    req.setAttribute("Name", n);

                    s=rs1.getString("Skill");
                    req.setAttribute("Skill", s);

                    req.setAttribute("Rows", row);

                    req.getRequestDispatcher("/Jsp/LoggedIn.jsp").forward(req,res);
                    }


                }





            else
            {
                out.println("<h3>"+"Username or password do not match !"+"</h3>");
                out.println("<a href='registration.jsp'> Registration</a>");
            }



        }

catch(Exception e)
{
    e.printStackTrace();
}
    }
}

2)Login.jsp
<%@page import="java.sql.*"%>
<%@ 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>Login Page</title>
</head>
<body>
<form action="servlet" method="post"><fieldset>
  <legend>Login</legend>
<hr>
Username: <input type="text" size=10 name="username">
<br>
Password: <input type="text" size=10 name="password">
<br>
<input type="submit" value="Submit"></input>
</fieldset>

<a href='registration.jsp'>New User ??Register </a>

</form>

</body>
</html>

3)LoggedIn.jsp
<%@ 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>LoggedIn</title>
</head>
<body>

<h2>Welcome <%String s=request.getAttribute("Name").toString();
out.println(s); %></h2>
<table border="5" bordercolor="brown" background="yellow">
<tr>
<th>Id</th><th>Name</th><th>Skill</th>

</tr>

<!-- It is just for normal fetching values -->

 <tr><td>
<% //by using setAttri and getAttru

//String s=request.getAttribute("Name").toString();
out.println(s); 

//by using HttpSession

/* HttpSession sess=request.getSession(false);
String s=sess.getAttribute("Name").toString();
out.println(s);
 */

%></td></tr>

<%--This is for fetching the complete database and creating rows dynamically --%>

<%
int rows=Integer.parseInt(request.getAttribute("Rows").toString());

for(int j=1;j<=rows;j++ )
{
    %>
    <tr>
    <td>
    <% 
        out.println(s);
    %>
    </td>






    </tr>


    <%
    }

%>
</table>


</body>
</html>

4)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JspServlet1</display-name>
  <welcome-file-list>
        <welcome-file>Jsp/Login.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>servlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>/servlet</url-pattern>

  </servlet-mapping>




</web-app>

I wanted to do login check,if the user is valid he is shown the entire database of users,but 
1)i am having problem in .getRequestDispatcher() method in servlet.java as if i write it outside the while,it throws "java.lang.IllegalStateException: Cannot forward after response has been committed"
and if i write it outside the while it loads forever.
2) I have problem that how to display the database to user.

For your second problem, I'd recommend using JSTL.

I can not say the reason for problem 1 but you can use response.sendRedirect("/Jsp/LoggedIn.jsp") to redirect to this page after successful log in

@ABV Try using the return statement

@hd1 but using that.....i can pass values one by one to a JSP from servlet ?

@JqueryLearner i just dont wanna redirect to another page,but also pass req and res object to process to access its values in the JSP

@sankrish where shall i use ?pls elaborate

@ABV Please post the code where you face the problem alone?


Use PreparedStatement instead of Statement for Login to prevent SQL Injection.
rs1.last();
 row=rs1.getRow();
 rs1.first();
above code causes an infinite loop
Put dispatcher outside while loop

Why are you using 
row=rs1.getRow();

You can use ArrayList/LinkedHashmap to store all records and then forward to LoggedIn.jsp
ArrayList<Student> al = new ArrayList<Student>();
while(rs1.next())
{
  Student std= new Student();
  std.setName(n);
  ...
  al.add(std);
}

request.setAttribute("userList"  al);


sry but what is Student in this:
ArrayList al = new ArrayList();

So that you can set multiple property (one student information) in the object of that class and add that object to ArrayList

i mean is Student a class ??
Coz in my program i dont have Student class

Ya if you need to send multiple record(rows) to another page then you need ArrayList and have to Student class
