Cannot redirect with the response.sendRedirect - java

I googled and googled for hours on how to make a redirect in jsp or servlets.
However when i try to apply it, it doesn't work.
Code that i have inside jsp page:
<%
String articleId = request.getParameter("article_id").toString();
if(!articleId.matches("^[0-9]+$"))
{
response.sendRedirect("index.jsp");
}
%>
I know from debugging that regexp works and if any time, articleId is not number, the if goes inside, however when it reaches response.sendRedirect it doesn't actually makes redirect.
Do I miss something very fundamental in this case ?
Thanks in advance.

You should return after redirecting:
response.sendRedirect("index.jsp");
return;

Is there content before this scriptlet? If so, the redirect wouldn't work.
Also, the common practice is to have such logic inside a servlet or other class serving as controller, and leaving the JSP to only handle the rendering of the HTML. It may also solve your problem. For example, see here

Related

Return with a 500 error from inside a JSP include

Is there a way to, from inside of a jsp:include page, get its requesting page to respond with an HTTP 500 error? I've tried using the response.sendError(418, "I'm a teapot.");, but that only works in the JSP that contains the jsp:include, and only if it is the first line because you can't call it after the response has been committed. What I have is this:
Index.jsp:
// other HTML
<jsp:include page="Exapmle.jsp">
<jsp:param name="aVariable" value="aValue" />
</jsp:include>
// other HTML
Example.jsp:
<%
String aVariable = request.getParameter("aVariable");
if (aVariable != null && !aVariable.trim().isEmpty) {
// code to generate content
%><%=someContent%><%
} else {
response.sendError(418, "I'm a teapot");
}
%>
So is there any way to do this? I'm doubtful based on how JSP's work, but hoping somewhere here can help. Also, servlets aren't an option (right now, at least).
If you get it to work, you shouldn't rely on it to always work on all platforms and future updates. As you state correctly: Once the response has been committed (e.g. all the HTTP headers are on the way to the client) there's no more way for the server to add any other HTTP headers. Let alone change the status code.
That's the reason why JSPs are considered the VIEW layer of an application, not the CONTROLLER. The times when all application logic was written in JSPs are long over and you should have proper request handling somewhere (if only in a servlet, but probably rather in a more powerful abstraction/framework) - decide about the result and either redirect to an error message or the proper visualization in that code.
JSP is good to render the content that you send along with the proper status code. Not to decide which status code to send.

Refeshring JSP page in Javascript

I am trying to refresh the JSP page after certain operations, I am using DWR to be able to use my classes in Javascripts in the JSP files so I have this code:
function removeDN(numplanindex){
DBOps.removeDN(numplanindex);
relaod(true);
}
the above code will break the removeDN() and it would not refresh the page, I have also tried window.location.reload(true) and document.location.reload(true).
I am not sure about the difference as I barely know any Javascript but according to everything on google this should work. I am wondering if anybody know what is wrong with what I am doing wrong.
Thanks
It should be reload(true) instead of relaod(true)
Also see http://www.w3schools.com/jsref/met_loc_reload.asp

Redirect pages in JSP?

I have to design several pages in jsp.
After clicking on the submit button on the first page, the page should be automatically redirected to the second page.
Can you help with a quick example or a link to a tutorial that demonstrates how to implement this?
<%
String redirectURL = "http://whatever.com/myJSPFile.jsp";
response.sendRedirect(redirectURL);
%>
This answer also contains a standard solution using only the jstl redirect tag:
<c:redirect url="/home.html"/>
Just define the target page in the action attribute of the <form> containing the submit button.
So, in page1.jsp:
<form action="page2.jsp">
<input type="submit">
</form>
Unrelated to the problem, a JSP is not the best place to do business stuff, if you need to do any. Consider learning servlets.
Hello there: If you need more control on where the link should redirect to, you could use this solution.
Ie. If the user is clicking in the CHECKOUT link, but you want to send him/her to checkout page if its registered(logged in) or registration page if he/she isn't.
You could use JSTL core LIKE:
<!--include the library-->
<%# taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%--create a var to store link--%>
<core:set var="linkToRedirect">
<%--test the condition you need--%>
<core:choose>
<core:when test="${USER IS REGISTER}">
checkout.jsp
</core:when>
<core:otherwise>
registration.jsp
</core:otherwise>
</core:choose>
</core:set>
EXPLAINING: is the same as...
//pseudo code
if(condition == true)
set linkToRedirect = checkout.jsp
else
set linkToRedirect = registration.jsp
THEN: in simple HTML...
CHECKOUT
Extending #oopbase's answer with return; statement.
Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,
/* Some Import Statements here. */
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
}
// ....
session.getAttribute("user_id");
// ....
/* Some More JSP+Java+HTML code here */
It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch block or handled if(null != session.getAttribute("attr_name")) everytime.
So by putting a return; statement I stopped further execution and forced to redirect page to certain location.
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
return;
}
Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).

JSP renders weird HTML

I'm getting a very strange behaviour in one of my JSP pages. It looks like it doesn't render the complete HTML. It looks like this:
<html>
...
<table>
...
</table>
<div id=
So the last line is exactly what you get when the page is rendered. Furthermore, when you do a view source you get exactly the same. This page doesn't have any fancy logic ... there are no javascript erros, no missing closing tags, etc ...
Is there any sort of page limit for a jsp page?
A bit more background: This page works just fine in a WIN2K server running Tomcat 5.5. I'm upgrading this app to run under a server with WIN2008 + Tomcat 6.0. That's where I get the error ...
Any help is appreciated.
Is there any sort of page limit for a jsp page?
AFAIK, no.
I think that the most likely cause is that your JSP is throwing an exception. Check the Tomcat logs, and look at the JSP at the point after the last HTML that was output.
EDIT
#Adam Crume says: "The exception may be thrown at a point further down from where the output stops, due to buffering."
True. As a temporary hack to get around this, you could surround the JSP's content with a try / finally, and flush the output stream in the finally block.
Is there any sort of page limit for a jsp page?
Yes, there is. It's about 64KB. JSP's are basically compiled into a large try statement. In Java, there's a 64KB limit for try statement. But if you exceed this, it would have prouced a different exception.
This problem at least indicates that you're using scriptlets in the JSP. This is a bad practice. Whenever an exception occurs halfway a JSP page, you'll get a blank or halfbaked page without information about the problem. Don't execute business stuff in JSP, but in a preprocessing Servlet.

JSP: How can I still get the code on my error page to run, even if I can't display it?

I've defined an error-page in my web.xml:
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
In that error page, I have a custom tag that I created. The tag handler for this tag e-mails me the stacktrace of whatever error occurred. For the most part this works great.
Where it doesn't work great is if the output has already begun being sent to the client at the time the error occurs. In that case, we get this:
SEVERE: Exception Processing ErrorPage[exceptionType=java.lang.Exception, location=/error.jsp]
java.lang.IllegalStateException
I believe this error happens because we can't redirect a request to the error page after output has already started. The work-around I've used is to increase the buffer size on particularly large JSP pages. But I'm trying to write a generic error handler that I can apply to existing applications, and I'm not sure it's feasible to go through hundreds of JSP pages making sure their buffers are big enough.
Is there a way to still allow my stack trace e-mail code to execute in this case, even if I can't actually display the error page to the client?
The errorPage isn't going to be used if you've already started sending data to the client.
What I do is use a JavaScript callback to check for an incomplete page and then redirect to the error page. At the beginning of your page in an includes header or something, initialize a boolean javascript variable to false, and register an onload handler to check the state and redirect to an error page.
<script type="text/javascript">
var pageLoadSuccessful = false;//set to true in footer.jsp
dojo.addOnLoad(function(){
if (!pageLoadSuccessful) window.location = "<c:url value="/error.do" />";
});
</script>
Then in a footer jsp, be sure to set this variable to true:
<script type="text/javascript">
pageLoadSuccessful = true;//declared in header.jsp
</script>
Have you tried using the <%# page errorPage="/myerrorpage.jsp" %> directive?
You also need to use <% page isErrorPage="true" $> in myerrorpage.jsp, then.
I think that may solve your problem. The only problem with that is that you need to include it in every JSP somehow.
In fact, this particular problem indicates that you were using scriptlets in JSP. This is a bad practice and this particular problem is one of the major reasons for that. You need to move all your business logic to a real java class so that you end up with only taglibs/EL in JSP. In a servlet/filter you can perfectly handle exceptions before forwarding the request to a JSP.

Categories

Resources