When I run this code, I get an IllegalStateException: Cannot forward after respons has been committed. I apologize, I am new to servlets. What should I do to fix this problem? This occurs at this line:
RequestDispatcher rd = request.getRequestDispatcher("/displayjobs.jsp");
rd.forward(request, response);
Here is the stack trace of the exception:
java.lang.IllegalStateException: Cannot forward after response has been committed
schedule.doGet(schedule.java:71)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
Here is the rest of my servlet code.
EDIT: I have also included my jsp code, as I am now experiencing a NPE at line 2:
1 List data = (List)request.getAttribute("jobsData);
2 for(itr = data.iterator(); itr.hasNext();)
This means that for some reason data is null rather than having the information of JobsData.
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://10.11.1.246;databaseName=Test;integratedSecurity=false;user=sa;password=S0l1dConcepts";
Connection con = DriverManager.getConnection(connectionUrl);
String query = "select * from jobs";
stmt = con.createStatement();
res = stmt.executeQuery(query);
while(res.next()){
list.add(res.getString(1));
list.add(res.getString(2));
list.add(res.getString(3));
list.add(res.getString(4));
list.add(res.getString(5));
list.add(res.getString(6));
list.add(res.getString(7));
list.add(res.getString(8));
list.add(res.getString(9));
list.add(res.getString(10));
}
res.close();
}
catch(Exception e){
RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
finally{
request.setAttribute("jData", list);
RequestDispatcher rd = request.getRequestDispatcher("/displayjobs.jsp");
rd.forward(request, response);
list.clear();
out.close();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://10.11.1.246;databaseName=Test;integratedSecurity=false;user=sa;password=S0l1dConcepts";
Connection con = DriverManager.getConnection(connectionUrl);
String query = "select * from jobs";
stmt = con.createStatement();
res = stmt.executeQuery(query);
while(res.next()){
list.add(res.getString(1));
list.add(res.getString(2));
list.add(res.getString(3));
list.add(res.getString(4));
list.add(res.getString(5));
list.add(res.getString(6));
list.add(res.getString(7));
list.add(res.getString(8));
list.add(res.getString(9));
list.add(res.getString(10));
}
res.close();
}
catch(Exception e){
RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
finally{
request.setAttribute("jData", list);
RequestDispatcher rd = request.getRequestDispatcher("/displayjobs.jsp");
rd.forward(request, response);
list.clear();
out.close();
}
}
}
Here is the JSP code:
<%#page import="java.util.List" %>
<%#page import="java.util.Iterator" %>
<%# 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>Scheduling</title>
</head>
<body>
<table>
<%Iterator itr;%>
<%List data = (List)request.getAttribute("jobsData");
for(itr = data.iterator(); itr.hasNext();){
%>
<tr>
<% String s = (String) itr.next();%>
<td><%=s%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><input type="submit" value="Edit" name="edit" onclick ="editRecord(<%=s%> %>);"></td>
<td><input type="submit" value="Delete" name="delete" onclick ="deleteRecord(<%=s%> %>);"></td>
<%} %>
</tr>
</table>
The problem is simple.The exception is caught,response is delegated from catch block and again from the finally block.
What you should do is have a single place for delegating your response
please note :- A response can be committed only once
boolean exceptionOcured =false;
try{
// your code
}
catch(Exception e){
exceptionOcured =true;
}
finally{
// your code to release resources
}
if(exceptionOcured){
RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}else{
RequestDispatcher rd = request.getRequestDispatcher("/displayjobs.jsp");
rd.forward(request, response);
}
There are a number of problems with your code... in particular, in the case of an error, you will try to forward twice (once in the catch block and once in the finally block). You should probably add server side logging when you get an exception so that you know there's a problem rather than just tossing the error to the user.
You also have code duplicated between doGet and doPost and a resource leak (you aren't closing the database connection or the statement).
Select * is also a bad idea.
And where is list defined? If it's defined at the servet class level, your code isn't thread safe.
Related
Here is the Servlet
public class displayServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Connection con = dbConnection.getConnection();
String query = "SELECT theaterNames, FROM thtrname where id in(11,12)";
try{
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
String str = null;
while(rs.next()){
str = rs.getString(1);
}
out.print(str);
HttpSession session = request.getSession();
session.setAttribute("thtr", str);
RequestDispatcher rd = request.getRequestDispatcher("success.jsp");
rd.forward(request, response);
rs.close();
ps.close();
con.close();
}catch(Exception ex){
}
}
}
Here is the success.jsp
<%#page contentType="text/html" pageEncoding="UTF-8" session="true"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<font color="green">
<%= request.getAttribute("thtr") %>
<h1><c:out value="${sessionScope.thtr}" /></h1>
</font>
</body>
</html>
I just don't get it where I am going wrong. I am using both JSTL and Scriptlet but all I am getting on the success.jsp page is null.
You need to set the value to request instead of session
from
session.setAttribute("thtr", str);
to
request.setAttribute("thtr", str);
a then to show just use ${thtr} in jsp
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.
Simply change request.getSession().getAttribute("data") to request.getAttribute("data") and it will work fine.
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.
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") %>
I have a jsp page containing a form where a user fills in some value. Now i pass these values into a servlet which processes it and retieves a related set of data. Now, i am able to retrieve the data in the servlet page, but am not able to display it on the same jsp page at which i fetched the request.
I do not want to use java code inside jsp. I wish to do the same using servlets only. I do not want to do something like this
<% if(rollno==null)
// then display the form
else
// process the request on the jsp page itself
%>
I want to process all my reults in a servlet file and then dispaly the result on the jsp page by passing data from servlet to jsp. I am posting my code below :
<form id="form" method="post" action="searchServlet">
Student Roll No :<br><input type="text" value="" name="rollno"><br><br>
<input type="submit" value="SHOW DETAILS" />
</form>
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String rollno=request.getParameter("rollno");
ResultSet rs=null;
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/schooldatabase";
Connection con = DriverManager.getConnection(url,"root","passwd");
Statement st= (Statement) con.createStatement();
String strquery="SELECT name,regno FROM `schooldatabase`.`student_info` WHERE rollno="+ rollno+ ";";
if(!con.isClosed()) {
rs=st.executeQuery(strquery);
while(rs.next())
{
out.println(rs.getString("name"));
out.println(rs.getString("regno"));
}
}
else
{ // The connection is closed
}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
You shouldn't be doing the presentation in the servlet. You should not have any of those lines in the servlet.
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// ...
out.println(rs.getString("name"));
out.println(rs.getString("regno"));
// ...
out.println(e);
You should instead be storing the data in a sensible collection and be setting it as a request attribute and finally forward the request/response to a JSP which in turn generates the proper HTML around all those data. Something like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Student> students = studentDAO.find(request.getParameter("rollno"));
request.setAttribute("students", students); // Will be available as ${students} in JSP
request.getRequestDispatcher("/WEB-INF/students.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain students from DB", e);
}
}
with this in the students.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${students}" var="student">
<tr>
<td>${student.name}</td>
<td>${student.regno}</td>
</tr>
</c:forEach>
</table>
For a more concrete example, see also this answer: Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
See also:
Our Servlets wiki page - Contains several Hello World examples
I have an index.jsp page with buttons named "refresh", "forward" and "edit". If I click on the refresh button then it call a Servlet and values are displayed on the index.jsp page.
When I click on the "forward" button it calls another servlet and goes to another page forward_call_log.jsp. In this page when I click on the "forward" button it calls another servlet and that servlet displays the index.jsp page. The index.jsp page is displayed but the values from the data base are not available.
How can i fix this problem?
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Pager Example - www.javaworkspace.com</title>
</head>
<body>
<form method="post" action="./Problem_retrive" >
<input type="submit" value="Refresh">
</form>
<form action="./edit_call_log" method="post">
<%
ResultSet rs=null;
try
{
rs=(ResultSet)request.getAttribute("rs");
//request.setAttribute("rs",rs);
if(rs.next())
{
%>
<table border=1 cellspacing=1 cellpadding=1>
<tr>
<th>check box</th>
<th>Problem ID</th>
<th>user ID</th>
</tr>
<%
do
{
%>
<tr>
<td><input type="checkbox" name="checkbox" value="<%=rs.getString(1) %>"></td>
<td><%=rs.getString(1) %></td>
<td><%=rs.getString(2) %></td>
</tr>
<%
}
while(rs.next());
%>
</table>
<%
}
else
{
out.println("hiiiiiiii");
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<input type="submit" name="act" value="EditCall"/>
<input type="submit" name="act" value="Forward"/>
</form>
</body>
</html>
After click on the Refresh button call Edit_call_servlet.java
import database.problemdesc.Problem_retrive_class;
import database.user_master.User_master;
import java.sql.*;
public class Edit_call extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
HttpSession session = request.getSession(true);
ResultSet rs=null;
Problem_retrive_class prc=new Problem_retrive_class();
int checkbox=Integer.parseInt(request.getParameter("checkbox"));
session.setAttribute("problem_id", checkbox);
String act=request.getParameter("act");
if(act.equals("EditCall"))
{
try
{
rs=prc.select_table(checkbox);
RequestDispatcher rd = request.getRequestDispatcher("edit_call_log.jsp");
request.setAttribute("rs", rs);
rd.forward(request, response);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else if(act.equals("Forward"))
{
System.out.println("Forward page");
try
{
ResultSet rs1=null;
User_master um=new User_master();
rs=prc.select_table(checkbox);
if(rs.next())
{
System.out.println("Value retrieve from PRC select_table");
rs1=um.select_table(rs.getString(7));
System.out.println("Value retrieve from PRC select_table"+rs.getString(7));
RequestDispatcher rd = request.getRequestDispatcher("forward_call_log.jsp");
request.setAttribute("rs1", rs1);
request.setAttribute("user_type", rs.getString(7));
rd.forward(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
}
catch(Exception e)
{
}
}
}
}
After clicking on the Forward button call Problem_retrive_servlet.java
import database.problemdesc.Problem_retrive_class;
public class Problem_retrive extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
Connection con=null;
ResultSet rs=null;
try
{
Problem_retrive_class prc=new Problem_retrive_class();
DBBean db=new DBBean();
con=db.getDBConnection();
rs=prc.select_table();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
It looks like you're not attaching any data to the request object so index.jsp has nothing to display. I'm assuming this is the code that is executing when the problem occurs.
public class Edit_call extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
...
else if(act.equals("Forward"))
{
try
{
...
{
...
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
/ *** YOUR PROBLEM IS HERE ***/
rd.forward(request, response);
}
[EDIT]
From your question I assume that the "refresh" button on your JSP works as expected (i.e. the data from the database is displayed as expected). From the following JSP code ...
<form method="post" action="./Problem_retrive" >
<input type="submit" value="Refresh">
</form>
the method being executed on the server is Problem_retrive.doPost()
Based on this we then need to understand what code is being exectued when the "forward" button is being clicked on forward_call_log.jsp. You have described that this "forward" button displays index.jsp but does not include the data from the database. Let's assume its calling Edit_call.doPost()*.
*I suggest you place debugger breakpoints in all of your doPost() methods to confirm this assumption, or just refer to your System.out.println() statements if you can't debug.
Therefore you need to compare what is happening in Problem_retrive.doPost() to what is not happening in Edit_call.doPost() when no data is being displayed. I suspect that you are not calling request.setAttribute()
rs=prc.select_table();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
request.setAttribute("rs", rs);
rd.forward(request, response);
A side note about good design
You can read about the MVC Design Pattern for a better way of designing your code.
This question already has answers here:
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
(9 answers)
Closed 6 years ago.
In my project, I prohibit a user every page only if he is already logged on. That is why I wrote the below code. When I type in browser, for example, http://localhost:8080/JSP1/Students, I come to the login.jsp page. But after I input the loginid and password, only blank page http://localhost:8080/JSP1/Logged appears and GlassFish says there is an exception in
if (userPath.equals("/Students")){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Students.jsp");
requestDispatcher.forward(request, response);
}
java.lang.IllegalStateException: PWC1227: Cannot forward after response has been committed
Complete code for doGet and doPost:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession ses = request.getSession();
String login = (String)ses.getAttribute("login");
String password = (String)ses.getAttribute("password");
if ((login==null)|(password==null)){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login.jsp");
requestDispatcher.forward(request, response);
}
//Now we think that we are successfully logged in
String userPath = request.getServletPath();
// System.out.println(userPath);
if (userPath.equals("/Login")){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login.jsp");
requestDispatcher.forward(request, response);
}
if (userPath.equals("/Students")){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Students.jsp");
requestDispatcher.forward(request, response);
}
if (userPath.equals("/Student")){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Student.jspx");
requestDispatcher.forward(request, response);
}
if (userPath.equals("/StudentEdit")){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/StudentEdit.jsp");
requestDispatcher.forward(request, response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
PrintWriter out = response.getWriter();
String userPath = request.getServletPath();
System.out.println(userPath);
if (request.getRequestURI().equals("/Logged")){
String Login = request.getParameter("login");
String Password = request.getParameter("password");
request.getSession().setAttribute("login", Login);
request.getSession().setAttribute("password", Password);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Students.jsp");
requestDispatcher.forward(request, response);
}
if (userPath.equals("/addStudent")) {
// System.out.println(request.getContextPath());
String Name = request.getParameter("name");
String Surname = request.getParameter("surname");
String Login = request.getParameter("login");
String Password = request.getParameter("password");
Student student = new Student(Name,Surname,Login,Password);
if (student != null) {
dao.insertStudent(student);
} else {
System.out.println("Not valid parameter!!!");
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Students.jsp");
requestDispatcher.forward(request, response);
}
if (request.getRequestURI().equals("/Edit")) {
System.out.println("We work with students!!!");
String delete = request.getParameter("Add_new_student");
if (delete != null){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Student.jspx");
requestDispatcher.forward(request, response);
}
Enumeration parameters = request.getParameterNames();
while (parameters.hasMoreElements()) {
String parameterName = (String) parameters.nextElement();
String parameterValue = request.getParameter(parameterName);
String norder = parameterName.substring(parameterName.indexOf("_")+1);
ArrayList<Student> curStudents = dao.getAllStudents();
int norderint = Integer.parseInt(norder);
Student studentToWork = curStudents.get(norderint);
String actionToDo = parameterName.substring(0, parameterName.indexOf("_"));
if (actionToDo.equals("Edit")){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/StudentEdit.jsp");
ServletContext cont = request.getServletContext();
cont.setAttribute("studentToEdit", studentToWork);
requestDispatcher.forward(request, response);
} else {
boolean attemp = dao.deleteStudent(studentToWork);
if (attemp){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Students.jsp");
requestDispatcher.forward(request, response);
} else {
out.println("Unsuccessfull attemp to delete a Student");
}
}
}
}
if (userPath.equals("/EditStudent")){
System.out.println("We work with StudentEdit!");
Student studentToEdit = (Student)request.getSession().getAttribute("studentToEdit");
String newName = request.getParameter("name");
String newSurname = request.getParameter("surname");
String newLogin = request.getParameter("login");
String newPassword = request.getParameter("password");
Student newStudent = new Student(newName, newSurname,newLogin,newPassword);
boolean update = dao.updateStudent(studentToEdit, newStudent);
if (update){
out.println("<p>You have successfully edited a Student=" + studentToEdit.toString() + " to Student="+ newStudent.toString());
} else {
out.println("<p>Unsuccessful attempt to edit!</p>" );
}
}
}
The login.jsp is simple:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="/JSP1/Logged" method="POST">
<table>
<tr>
<td>Login:</td>
<td><input type="text" name="login" value=""/> </td>
</tr>
<tr>
<td>Password </td>
<td><input type="password" name="password"/> ></td>
</tr>
<tr>
<td><input type="submit" name="OK" value="OK" /> </td>
</tr>
</table>
</form>
</body>
I can't figure out what's happening.
You aren't returning after the forward when the login and/or password is not been supplied. It's a common misconception among starters that the forward() method magically terminates the code execution and jumps out of the method somehow. This is thus not true. You have to return from the method and stop the execution of the remnant of the code yourself.
You need to either add a return;
if ((login==null)|(password==null)){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login.jsp");
requestDispatcher.forward(request, response);
return;
}
Or to add an else
if ((login==null)|(password==null)){
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login.jsp");
requestDispatcher.forward(request, response);
} else {
// Now we think that we are successfully logged in.
// Yes, that above comment is now finally true.
// Put your bunch of non-DRY if-else code here.
}
See also:
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed