I have to design several pages in jsp. After clicking on the submit button on t开发者_Go百科he 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...
<a href="your.domain.com/${linkToRedirect}">CHECKOUT</a>
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).
精彩评论