This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

java.lang.IllegalStateException: Cannot forward after response has been committed  RSS feed

 
Anu katoch
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey I am new to Jsp/Servlets i am getting following Exception
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:349)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at servlets.Controller.doGet(Controller.java:89)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

and my Servlet Code is

package servlets;

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

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;





import Beans.Registry;


/**
* Servlet implementation class Controller
*/
@WebServlet("/Controller" )
public class Controller extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;

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



protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();

String services = request.getParameter("Services");
String username = request.getParameter("UserName");
String password = request.getParameter("Password");
System.out.println("username>>>>>>>>>>>>>>>>>>>>>>"+username);
System.out.println("Services>>>>>>>>>>>>>>>>>>>>>>"+services);
System.out.println("Password>>>>>>>>>>>>>>>>>>>>>>"+password);
System.out.println("Requested Services:"+services);
Registry reg = new Registry();

//String user =(String)request.getSession().getAttribute("UserName");

request.getSession().setAttribute("UserName", username);
request.setAttribute("Password", password);


if(username==null&&(services==null|| (!services.equals("login")))){
String err ="Unauthorized Access";
request.setAttribute("errormsg", err);
RequestDispatcher disp =getServletContext().getRequestDispatcher("/error.jsp");
disp.forward(request, response);
return;


}else{
try{
if(!reg.find(services)){
String err ="Unreconized Services";
request.setAttribute("errormsg", err);
RequestDispatcher disp = getServletContext().getRequestDispatcher("/error.jsp");
disp.forward(request,response);
return;


}else{
System.out.println("Service Class:"+reg.getsClass());
String cl="Beans."+reg.getsClass();
Class cls = Class.forName(cl);
Object obj = cls.newInstance();
Method mth = cls.getMethod(reg.getsMethod(), HttpServletRequest.class,HttpServletResponse.class);
String redirectPage = (String)mth.invoke(obj, request,response);
System.out.println("Return Page:"+redirectPage);

RequestDispatcher disp =getServletContext().getRequestDispatcher(redirectPage);
disp.forward(request, response);
//on this foward request i am getting the above exception;
return;

}

}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
out.close();

}
}

}

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

It is properly excuting viewUser method
the following code
/**
*
*/
package Beans;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.RequestDispatcher;
import javax.xml.ws.Response;

import org.apache.catalina.connector.Request;

import connection.Database;

/**
*
*
*/
public class UserClass {

private Number User_ID;
private String User_Name;
private String Password;
private String User_Type;



public Number getUser_ID() {
return User_ID;
}
public void setUser_ID(Number user_ID) {
User_ID = user_ID;
}
public String getUser_Name() {
return User_Name;
}
public void setUser_Name(String user_Name) {
User_Name = user_Name;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getUser_Type() {
return User_Type;
}
public void setUser_Type(String user_Type) {
User_Type = user_Type;
}


public String viewUser(HttpServletRequest request, HttpServletResponse response)throws SQLException
{
String query="SELECT User_Name,Password FROM User";
Database cn= new Database();
cn.loadDriver();
cn.connect();

boolean chk =false;

String currentuser =(String) request.getSession().getAttribute("UserName");
String currentpassword = request.getParameter("Password");
String resultsetUser = null;
String resultsetPassword = null;
String redirectresponse = null;


ResultSet resultset = cn.result(query);
while(resultset.next()){
resultsetUser = resultset.getString("User_Name");
resultsetPassword = resultset.getString("Password");
resultset.close();
cn.disconnect();
if(currentuser.equals(resultsetUser) && currentpassword.equals(resultsetPassword)){

redirectresponse="/UserInput.jsp";

try {
response.sendRedirect("/UserInput.jsp");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;

}else{
System.out.println("Invalid username and password");
redirectresponse="/error.jsp";

try {
response.sendRedirect("/error.jsp");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
return redirectresponse;





}


}




}

Thanks for your help in Advance




 
prasad guna
Ranch Hand
Posts: 46
Java MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

Remove or comment the return keyword after the forward unless it will create the compile time exception.

thanks
 
Anu katoch
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Still facing exception
ava.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:349)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at servlets.Controller.doGet(Controller.java:89)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

after removing return statements after foward

package servlets;

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

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;





import Beans.Registry;


/**
* Servlet implementation class Controller
*/
@WebServlet("/Controller" )
public class Controller extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;

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



protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();

String services = request.getParameter("Services");
String username = request.getParameter("UserName");
String password = request.getParameter("Password");
System.out.println("username>>>>>>>>>>>>>>>>>>>>>>"+username);
System.out.println("Services>>>>>>>>>>>>>>>>>>>>>>"+services);
System.out.println("Password>>>>>>>>>>>>>>>>>>>>>>"+password);
System.out.println("Requested Services:"+services);
Registry reg = new Registry();

//String user =(String)request.getSession().getAttribute("UserName");

request.getSession().setAttribute("UserName", username);
request.setAttribute("Password", password);


if(username==null&&(services==null|| (!services.equals("login")))){
String err ="Unauthorized Access";
request.setAttribute("errormsg", err);
RequestDispatcher disp =this.getServletContext().getRequestDispatcher("/error.jsp");
disp.forward(request, response);



}else{
try{
if(!reg.find(services)){
String err ="Unreconized Services";
request.setAttribute("errormsg", err);
RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/error.jsp");
disp.forward(request,response);



}else{
System.out.println("Service Class:"+reg.getsClass());
String cl="Beans."+reg.getsClass();
Class cls = Class.forName(cl);
Object obj = cls.newInstance();
Method mth = cls.getMethod(reg.getsMethod(), HttpServletRequest.class,HttpServletResponse.class);
String redirectPage = (String)mth.invoke(obj, request,response);
System.out.println("Return Page:"+redirectPage);

RequestDispatcher disp =this.getServletContext().getRequestDispatcher(redirectPage);
disp.forward(request, response);
execption occur at this point only



}

}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
out.close();

}
}

}

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



}

Need help on this.. Problem Still persist, Please help.

 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


It means just what it says. Somehow, when you reach line 89 in your doGet method, the first batch of output to the response has already been sent.

Incidently, if you want people to review your code, make it easier to read:
1. use the code markup so it will be readable
2. don't include all the extraneous methods which clearly have nothing to do with the problem

Bill
 
prasad guna
Ranch Hand
Posts: 46
Java MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

remove the finally block which is used for closing the out object. remove and check let me know.
 
Anu katoch
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have removed finally block which used for closing .out object. But didn't help much . Still problem persist


exception i am facing

 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66204
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does line 37 even exist in your servlet?
 
Anu katoch
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is login.jsp through with i am sending the request


This is UserInput.jsp to which i am forwarding the request

This is UserClass.java which is Invoked through reflection and method viewUser


Please Help Thanks in advance.
 
Anu katoch
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry i have removed line number 37 which was unused PrintWriter Object but still have same issue.
 
prasad guna
Ranch Hand
Posts: 46
Java MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Anu,

Which method are you invoking from the servlet if the method is viewUser() then why you redirect the page there. if you want to forward or redirect do it in servlet itself. Don't do anything in viewUser() method.

better remove response.sendRedirect("/UserInput.jsp"); in viewUser() method or just comment the method calling and try once you can find the exact what happen.
 
Anu katoch
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Prasad;

when i am removing response.sendRedirect("/UserInput.jsp");from viewUser() method then my doget method is executing again and again in loop which is never ending loop and browser only have Login Page display.

Thanks and Looking for your response for the same.

 
prasad guna
Ranch Hand
Posts: 46
Java MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

Yes its working correctly but why its showing like this? because in userInput.jsp you are including the login.jsp so what it will be display.

If you want to check don't include the login.jsp just print the text and check it out.
 
Anu katoch
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

After removing response.sendRedirect("/UserInput.jsp");from viewUser() method my Servlet's doget method is getting excuting again and again in continues loop and brower is showing Login window in waiting state and i have removed <jsp:include page="/Login.jsp" flush="true" ></jsp:include> from UserInput .

Please help! Thanks in Advance
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!