File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes JSP and the fly likes response.sendRedirect() error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "response.sendRedirect() error" Watch "response.sendRedirect() error" New topic
Author

response.sendRedirect() error

Aravind Prasad
Ranch Hand

Joined: Dec 28, 2005
Posts: 265
Hello Ranchers...
I'm using JSP and oracle.. for creating an application..
there is a problem with response.sendRedirect()..

i'm doing a user creation application..
After creating the user the page will redirect to index.jsp.. where the user can give the username and password.. All the files are int the same folder also

the code i used for redirecting is this..
----------------------------------------------------------------------------
Statement stmt2 = dbCon.createStatement();
int ins_q5 = stmt2.executeUpdate(query5);
stmt2.close();
dbCon.close();
response.sendRedirect("index.jsp");
--------------------------------------------------------------------------
and the error i'm getting is this
--------------------------------------------------------------------------

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Exception in JSP: /doadd_staff.jsp:93

90: int ins_q5 = stmt2.executeUpdate(query5);
91: stmt2.close();
92: dbCon.close();
93: response.sendRedirect("index.jsp");
94: }
95: catch(SQLException e)
96: {


Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:504)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:387)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)


root cause

java.lang.IllegalStateException
org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:432)
org.apache.jsp.doadd_005fstaff_jsp._jspService(doadd_005fstaff_jsp.java:138)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)


note The full stack trace of the root cause is available in the Apache Tomcat/5.5.17 logs.

----------------------------------------------------------------------------
I'm very much sure that the problem caused by response.sendRedirect() coz.. i can see the values inserted in the database..

may be the problem with the sendRedirect() or the dbCon.close()

please help me ranchers..
this is very urgent..

thanks in advance

regards
Aravind


[ June 14, 2006: Message edited by: Bear Bibeault ]
[ September 08, 2006: Message edited by: Bear Bibeault ]
narasimhaiah shekar
Greenhorn

Joined: May 31, 2006
Posts: 7
Hi Aravind,

You said that all the files are in the same folder right okay.

If it is within the same application, then why are u using

response.sendRedirect(jsp).Insted You should use requestdispatcher object.

Basically, sendRedirect is used to send the request to another web server.

Thanks,
shekar
pawank gupta
Ranch Hand

Joined: Jun 07, 2006
Posts: 34
look when u r using the sendredirect it means ur control not transfer completely at the time of redirection until the complete page is scanned so if in ur jsp from where u r redirected to other page has some other code which effects ur redirection like committing ur response or something else then i would create problem in ur redirection.
Aravind Prasad
Ranch Hand

Joined: Dec 28, 2005
Posts: 265
Thanks for replying me ranchers..
Any way i want to change the page.. for egs..
1)index.jsp (accepts userid and password)
2) validate_login.jps (validates the userid and password)
if the user id and password is true then redirect the user to main_pgm.jsp
else redirect the user to index.jsp?urlmsg="Invalid userid and pwd"

this is what i'm using in response.sendRedirect()

now.. can u please tell me if this is not a good idea.. which is the proper way to redirect the pages.. according to the ifcondition

please.. help me ranchers..

thanks in advance..
regards
Aravind
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Originally posted by pawank gupta:
look when u r using the sendredirect it means ur control not transfer completely at the time of redirection until the complete page is scanned so if in ur jsp from where u r redirected to other page has some other code which effects ur redirection like committing ur response or something else then i would create problem in ur redirection.


pawank gupta
Welcome to JavaRanch!

In an effort to help you get the most from our forums, we've compiled a
list of tips for asking questions here. You can find the list in our
FAQ section here. In particular, please see UseRealWords.

Using contractions such as "ur" instead of "you are" or "you're" confounds language translation software making it difficult or impossible for our non-English speaking members to read your posts.

Again, welcome to JavaRanch and thank you for helping out.
-Ben
[ June 14, 2006: Message edited by: Ben Souther ]

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Originally posted by narasimhaiah shekar:
.....
Basically, sendRedirect is used to send the request to another web server.


Not entirely true.
sendRedirect can be used to redirect to another web server but there are also plenty of reasons to use it within the same app. The Post-redirect-get pattern is one good example.
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Originally posted by Aravind Prasad:
....
root cause
java.lang.IllegalStateException


We've just recently added an entry for IllegalStateException to the JSP and Servlet FAQs.
http://faq.javaranch.com/view?IllegalStateException

Check it out and let us know if it helps.
Mark Kliethermes
Greenhorn

Joined: Jul 27, 2004
Posts: 1
hi,
I have a similar problem. Everything worked fine until I reinstalled Windows 2000 to overcome a virus problem.
Now the system hangs at the point of sendRedirect. I have researched and tried a lot of things but i just don't
understand what is happening and am looking for some assistance. I am currently using Tomca 5.5.12 and Crystal
Reports 9 RAS.

The application calls a servelet that validates the user logging (validateUser). However, the hangs and will not
process my jsp file "processRequest.jsp" which is supposed to resend a new url and display a report from Crystal
Reports.

response.sendRedirect("processRequest.jsp");

The wierd thing is that after the system 'hangs' at the sendRequest(), I can call the url with "processRequest.jsp"
manually from the browser and the report displays as it should.

Any help would be appreciated.

*************************************
My error from the tomcat log
Sep 8, 2006 8:13:25 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:432)
at org.apache.jsp.Adv_005fGoalsDx_jsp._jspService(Adv_005fGoalsDx_jsp.java:476)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)



********************************************
below is an example of one of my jsp files that calls "processRequest.jsp"

<%
/*****************************************************************************

This example can be used to log onto the main report as well as a subreport
if a subreport exists. This will also work for stored procedure parameters.
For stored procedure parameters, you will need to logon to the database first.

******************************************************************************/
%>

<%@ page session="true"%>
<%@ page contentType = "text/html; charset=UTF-8" %>
<%@ page import= "java.net.*,
java.util.*,
com.crystaldecisions.sdk.occa.report.data.*,
com.crystaldecisions.report.web.*,
com.crystaldecisions.sdk.occa.report.application.*,
com.crystaldecisions.sdk.occa.report.reportsource.*,
com.crystaldecisions.sdk.occa.report.application.ClientDocument.*,
com.crystaldecisions.report.web.viewer.*,
com.crystaldecisions.sdk.occa.report.lib.*"
%>
<jsp:useBean id="UserInfo" class="servletcp.ValidateUser" scope="session"/>

<%




// Get passed URL parameters
String CPUser = (String) request.getParameter("User");
String CPPass = (String) request.getParameter("Pass");
String Company = (String) request.getParameter("CompanyID");

// Validate user and get the database password
UserInfo.SetUserInfo(CPUser,CPPass,Company);

//----------------------------PROPERTIES-----------------------------
// ** Name of report to open **
//String reportName = (String) session.getAttribute("reportName");
String reportName = "adv_DxActive.rpt";


// ** Userid iof database if applicable **
String uid = UserInfo.GetDBUser();

// ** Password of database if applicable **
String pwd = UserInfo.GetDBPass();


// Declare the Server Control
ReportServerControl serverControl = new ReportServerControl();

// Declare the ReportClientDocument
ReportClientDocument clientDoc = new ReportClientDocument();

// Declare the Interactive Viewer
CrystalReportInteractiveViewer htmlViewer = new CrystalReportInteractiveViewer();

//-----------------------------METHODS---------------------------------
// Open the report and set it to the ReportClientDocument object
setReportClientDocument(clientDoc, reportName, request, out);


// Set server control properties
setServerControlProperties(serverControl, clientDoc, response, request, out);

// Set the viewer properties
htmlViewer = setViewerProperties(serverControl, reportName, out);

htmlViewer.setPageTitle(new String("Clinical Pharmacy Systems"));

/*
Uncomment out this part if your database has security. If you uncomment this code out, be
sure to uncomment line 220 of this jsp file as well. That is where you actually set the
database information you have just provided.
For stored procedures, you will need to logon to the database.

// Logon and get ConnectionInfos object. Pass in the userid and password.
*/
setDatabaseLogons(serverControl, htmlViewer, uid, pwd, out);

// Set the parameter values
setReportParameters(serverControl, htmlViewer, request, out);

// Store the viewer object in session so that it's retrievable from processRequest.jsp
session.setAttribute("viewer", htmlViewer);

//out.println("89 gets here?");

// Redirect to processing page
response.sendRedirect("processRequest.jsp");

%>

<%!

/**
* Set the viewer's properties.
*/
public CrystalReportInteractiveViewer setViewerProperties(ReportServerControl serverControl, String reportName, JspWriter out) throws Exception {

/*********************************************************************************************
*Set the Viewer properties
*********************************************************************************************/
CrystalReportInteractiveViewer htmlViewer = new CrystalReportInteractiveViewer();

try {
// Set the viewer's report source
htmlViewer.setReportSource(serverControl.getReportSource());
} catch(ReportSDKException e) {
out.println("An error has occurred in setting the viewer's report source.");
} catch(ReportSDKExceptionBase ex) {
out.println("An error has occurred in setting the viewer's report source.");
}

// Set the viewer's name
htmlViewer.setName("Crystal Interactive Viewer");

// Set page title of viewer to the name of the report
htmlViewer.setPageTitle("Clinical Pharmacy Systems");

/**********************************************************************************************/
// Set the viewer to own the page it is on. If you set setOwnPage to false then you must set the charset and the content-type.
// Setting this to true enables the Export and Print button by default.
// If you do not have this set to true, then the export and print button will not be rendered regardless of other properties set.
// Refer to the javadocs for more information on this property.
htmlViewer.setOwnPage(true);
/**********************************************************************************************/

// Set the viewer to enable drill down
htmlViewer.setEnableDrillDown(false);

// Get rid of the Tree to help with the margin
htmlViewer.setDisplayGroupTree(false);

return htmlViewer;
}

/**
* Set the report's parameters' values.
* @paramsserverControl - ServerControl object
*request - Request object
*/
public void setReportParameters(ReportServerControl serverControl, CrystalReportInteractiveViewer htmlViewer, HttpServletRequest request, JspWriter out) throws Exception {

/*********************************************************************************************
*Set the report's parameters
*********************************************************************************************/
try {
// Declare the Fields collection for parameters
Fields parameterFields = new Fields();

// Retrieve parameter field collection from report
parameterFields = serverControl.getParameterFields();

int size = parameterFields.size();// Get size of parameter field collection
for (int x=0; x<size; x++) {

// Retrieve the parameter field located at the current index
IParameterField parameterField = (IParameterField) parameterFields.getField(x);
// Get the name of the parameter field
String paramName = parameterField.getName();
// New Discrete field value
IParameterFieldDiscreteValue paramValue = new ParameterFieldDiscreteValue();
// Get parameter value from the user form
String strValue = request.getParameter(paramName);
out.println("String Value:"+paramName);
out.println("String Value:"+strValue);

// Determine the data type of the parameter
switch(parameterFields.getField(x).getType().value()) {

case FieldValueType._numberField:// Number value
paramValue.setValue(strValue);
break;
case FieldValueType._dateField:// Date value
paramValue.setValue(ParseDatePrompt(strValue));
break;
case FieldValueType._dateTimeField:// Date Time value
paramValue.setValue(ParseDateTimePrompt(strValue));
break;
case FieldValueType._timeField:// Time value
paramValue.setValue(ParseTimePrompt(strValue));
break;
case FieldValueType._booleanField:// Boolean value
paramValue.setValue(Boolean.valueOf(strValue));
break;
case FieldValueType._stringField:// String value
paramValue.setValue(strValue);
break;
case FieldValueType._currencyField:// Currency value
paramValue.setValue(Float.valueOf(strValue));
break;
}
// Add this value to current value list
parameterField.getCurrentValues().add(paramValue);
// paramValue = new ParameterFieldDiscreteValue();
//paramValue.setValue(new String("22"));
//parameterField.getCurrentValues().add(paramValue);

}

/***** Set the Report parameters to the viewer object */
htmlViewer.setParameterFields(parameterFields);
/****************************************************/

} catch(ReportSDKExceptionBase e) {
out.println("Error occurred retrieving parameter collection from Report object.");
}
}

/**
* This method logs into the database and sets the resulting ConnectionInfos object to the viewer.
* @paramsserverControl - ServerControl object
*uid - Userid of report database
*pwd - Password of report database
*out - JspWriter object
*/
public void setDatabaseLogons(ReportServerControl serverControl, CrystalReportInteractiveViewer htmlViewer, String uid, String pwd, JspWriter out) throws Exception {

/********************************************************************************************
*Logging onto the database using the ConnectionInfos collection.
********************************************************************************************/
// Declare the Connection Infos object
ConnectionInfos connInfos = new ConnectionInfos();

// Declare the Connection info object
IConnectionInfo iConnInfo;

try {
// Retrieve all the different logon information from report including subreports' logons
connInfos = serverControl.getDatabaseLogonInfos();

int size = connInfos.size();// Get size of collection
for (int x=0; x<size; x++) {
iConnInfo = connInfos.getConnectionInfo(x);// Retrieve connection info at this index
iConnInfo.setUserName(uid);// Set the Username
iConnInfo.setPassword(pwd);// Set the password
}

/***** Set the Database Logons to the viewer object */
htmlViewer.setDatabaseLogonInfos(connInfos);
/****************************************************/

} catch(ReportSDKExceptionBase e) {
out.println("An error has occurred in retrieving the Database Logon information from the Report Source.<BR>");
out.println(e.toString());
}
}

/**
* This method sets the ReportServerControl object's properties.
* @paramsserverControl - ServerControl object
*clientDoc - The ReportClientDocument object
*response - Response object
*request - Request object
*out - JspWriter object
*/
public void setServerControlProperties(ReportServerControl serverControl, ReportClientDocument clientDoc, HttpServletResponse response, HttpServletRequest request, JspWriter out) throws Exception {

/********************************************************************************************
*Setting the Report Server Control properties
********************************************************************************************/
try {
// Set the Server Control's report source to the report client document object
serverControl.setReportSource(clientDoc.getReportSource());

} catch(ReportSDKExceptionBase e) {
out.println("An error has occurred in setting the Report Server Control's Report Source.<BR>");
out.println("Check to make sure that the report does exist in the directory specified and that it is also spelled correctly.<BR>");
out.println(e.toString());
}

// Set this to true or false depending on whether you want to be prompted for the database login or not
serverControl.setEnableLogonPrompt(false);
// Set it so we are not prompted for parameters
serverControl.setEnableParameterPrompt(false);

try {
// This method generates the HTML for the report and then writes the HTML directly to the response object
serverControl.processHttpRequest(request, response, getServletConfig().getServletContext(), out);
} catch(ReportSDKExceptionBase e) {
out.println("An error has occurred processing the HTTP request of the Server Control.<BR>" + e.toString());
}
}

/**
* This method creates the ReportClientDocument and opens the specified report.
* @paramsclientDoc - The ReportClientDocument object
*reportName - The name of the report as String
*request - Request object
*out - JspWriter object
*/
public void setReportClientDocument(ReportClientDocument clientDoc, String reportName, HttpServletRequest request, JspWriter out) throws Exception {
// Absolute physical path of the application directory
String path;

// Get physical application directory
String temp1 = (request.getRequestURI()).replace('/', '\\');// Replace the front slashes with back slashes
path = request.getRealPath("/") + temp1;// Get the physical path of the application dir
int lastIndex = path.lastIndexOf("\\");// Give us index of last occurring '\' in string
path = path.substring(0, lastIndex) + "\\";// Get substring beginning from first char to last index of '\'


/********************************************************************************************
*Opening the Report Client Document
********************************************************************************************/
// Here we set the ReportClientDocument's ReportAppServer. If you have installed your RAS and
// SDK on seperate machines, then you will need to manually enter in the RAS machine's name.
try {
// Create InetAddress object to acquire server's servername
InetAddress ip = InetAddress.getLocalHost();

// ReportAppServer machine name (Local server)
String rasServerName = ip.getHostName();

// Set the Report Application Server for the ReportClientDocument object
clientDoc.setReportAppServer(rasServerName);

} catch(UnknownHostException e) {
out.println("Hostname could not be verified.<BR>" + e.toString());
} catch(ReportSDKException e) {
out.println("An error has occurred setting the ReportClientDocument's ReportAppServer.<BR>" + e.toString());
}

try {
// Open the specified report.
// If your RAS and SDK server are installed on seperate machines, you will have to place "rassdk://" in front
// of your report path to specify that the report is being loaded from the machine with the SDK installed.
clientDoc.open(path + reportName, OpenReportOptions._openAsReadOnly);

} catch(ReportSDKException e) {
out.println("An error has occurred attempting to open the Report. Please make sure that the report is spelled correctly <BR>");
out.println("and that it is in the application's directory. The report you have selected needs to be accessible by the RAS <BR>");
out.println("server. Make sure that the report is in the Report Directory or is in a subdirectory of the Report Directory.<BR> ");
out.println("The Report Directory for RAS is set by the RAS Configuration Manager in the RAS Tools on the RAS server's Start menu.");
out.println("<BR><BR>" + e.toString());
}
}

/**
* This method takes in a java.lang.String in the format "Date(yyyy,mm,dd)" and returns a java.util.Date
* @Params- java.lang.String in the format "Date(yyyy,mm,dd)"
* @Returns- java.util.Date
*
*/
public Date ParseDatePrompt(String dateToParse) {
try {
String sDate = dateToParse.substring(dateToParse.indexOf("(") + 1); //move past "Date("
sDate = sDate.substring (0, sDate.lastIndexOf(")")); //remove trailing ")"
StringTokenizer st = new StringTokenizer(sDate, ",");
Calendar cal = Calendar.getInstance();
cal.set(Integer.valueOf(st.nextToken()).intValue(),
Integer.valueOf(st.nextToken()).intValue()-1,
Integer.valueOf(st.nextToken()).intValue());
Date _date = cal.getTime();
System.out.println(_date.toString());

return _date;
} catch(Exception e) {

}
return new Date();
}
%>

<%!
/**
* This method takes in a java.lang.String in the format "Time(hh,mm,ss)" and returns a java.util.Date
* @Params- java.lang.String in the format "Time(hh,mm,ss)"
* @Returns- java.util.Date
*
*/
public Date ParseTimePrompt(String timeToParse) {
try {
String sDate = timeToParse.substring(timeToParse.indexOf("(") + 1); //move past "Time("
sDate = sDate.substring (0, sDate.lastIndexOf(")")); //remove trailing ")"
StringTokenizer st = new StringTokenizer(sDate, ",");
Calendar cal = Calendar.getInstance();
cal.set(0,0,0,
Integer.valueOf(st.nextToken()).intValue(),
Integer.valueOf(st.nextToken()).intValue(),
Integer.valueOf(st.nextToken()).intValue());
Date _date = cal.getTime();
System.out.println(_date.toString());
return _date;
} catch(Exception e) {
e.printStackTrace();
}
return new Date();
}
%>

<%!
/**
* This method takes in a java.lang.String in the format "DateTime(yyyy,mm,dd,hh,mm,ss)" and returns a java.util.Date
* @Params- java.lang.String in the format "DateTime(yyyy,mm,dd,hh,mm,ss)"
* @Returns- java.util.Date
*
*/

public Date ParseDateTimePrompt(String dateToParse) {
try {
String sDate = dateToParse.substring(dateToParse.indexOf("(") + 1); //move past "DateTime("
sDate = sDate.substring (0, sDate.lastIndexOf(")")); //remove trailing ")"
StringTokenizer st = new StringTokenizer(sDate, ",");
Calendar cal = Calendar.getInstance();
cal.set(Integer.valueOf(st.nextToken()).intValue(),
Integer.valueOf(st.nextToken()).intValue()-1,
Integer.valueOf(st.nextToken()).intValue(),
Integer.valueOf(st.nextToken()).intValue(),
Integer.valueOf(st.nextToken()).intValue(),
Integer.valueOf(st.nextToken()).intValue());
Date _date = cal.getTime();
System.out.println(_date.toString());
return _date;
} catch(Exception e) {
e.printStackTrace();
}
return new Date();
}

%>
****************************************************************
tan kong sang
Greenhorn

Joined: Mar 14, 2005
Posts: 2
sometimes, the program will run for the whole page before it perform the necessary redirect. so in case of if your program have any errors after the redirect coding, it will have the error rather than redirect you to the page you wish. to force it redirect, use the "return;" after the response.sendredirect()
Baseet Ahmed
Ranch Hand

Joined: Dec 18, 2006
Posts: 224
Arvind/Mark,


Try to use fully qualified path inside sendRedirect() method.
Such as "http://hostname:port/path.."


Correct me if I am wrong.

Thank you.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: response.sendRedirect() error