Redirect pages in JSP? - java

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).

Related

Collect user input in Servlet and return at the same point to continue program: Java

I have a web application in Java that performs title matching.
The Servlet is the controller and in one of the methods of the Servlet, I am comparing two list of titles. The first list is in a HashMap and the second is from a query ResultSet.
What I want to do is to automatically match those with same title and give the user the option to confirm the ones with some similarities (business logic). Basically, I need to get user input and then return at the same point to continue.
I tried JOptionPane dialog box and it didn't work.
Now I am trying to forward to another HTML page to get user input and then return to the Servlet.
Below is the Servlet code:
while (Querylist.next()) {
String title = Querylist.getString(1).trim().toLowerCase();
if (MyMap.containsKey(title))
{
// confirm match
} else
{
//some title2 is like title
request.setAttribute("Title1", title);
request.setAttribute("Title2", title2);
RequestDispatcher view = request.getRequestDispatcher("TitleMatch.jsp");
view.forward(request, response);
ResultMatch= request.getParameter("ResultMatch");
if (ResultMatch.equals("YES"))
{
// confirm match
}
}
}
HTML Page:
<B> <%= request.getAttribute("Title1")%></B>
<B> <%= request.getAttribute("Title2")%></B>
<FORM method="get" action="DataMerge">
<input type = "radio" name="MatchResult" value="YES" /> YES
<input type = "radio" name="MatchResult" value="NO" checked/>NO
<button type = "submit" formaction="DataMerge" > <b>CONFIRM</b>
</FORM>
EDIT: the loop works and I'm having a java.lang.IllegalStateException Exception.
Does anyone can help to figure out how to do that efficiently in plain Java?
I searched all over SO and haven't found something similar. Thanks in advance.
You might want to reconsider your approach as there are number of fundamental problems with the code you have written. For example:
The while loop test it not correct. Assuming that you are using an Iterator then the test should be list.hasNext();
The if test is nested and incorrect. You cannot use the identifier Map as it is the name of the class, you should use the name of the map object.
If the loop worked the view.forward(request, response); would result in an java.lang.IllegalStateException exception, on the second cycle, as its not possible to resend a response.
I suggest that instead of trying to send each title pair one at a time, that you display them all (or some if there are too many) on one JSP with a yes button next to each pair and as the user clicks the yes button an AJAX call is made to another servlet that updates the database (or an array to latter be used to update the database).
There are some good tutorial about using AJAX and JSP here of SOF and in YouTube.

Simple logout implementation java

I've managed to create a secured web service which stores the hash of password with random salt
But now after the user has filled its correct username and password then he is redirected to index.html page.
and now my task is to create the same thing as you see here in stackoverflow in the left corner - I want the user to see his username and next to it to have an option for logout.
But as I have never done such thing can you recommend the steps I should follow
and some tutorial - or whatever you think I should read
What is the technology stack you are using ? JSP + Java ? JSF + Java ? Struts + Java ? or any-other ? Whatever you use. Most of the framework has a concept of session. When user hit the submit button post filling the form, store the "username" is session. On successful validation pull the "username" stored from session. http://www.javatpoint.com/cookies-in-session-tracking http://www.tutorialspoint.com/jsp/jsp_session_tracking.htm
Easiest way is to have link to page like
http://www.example.com/logout.jsp
Than in logout.jsp, you can logout user from DB (if you use that) and destroy SESSIONS and COOKIES. After that, you do redirect to index page of web. Doing redirect to last page is not always possible, because user coul have been in some logged only part of the web.
Good thing is also to check if user is logged before doing real logout, but all of this stuff is in logout.jsp. There is no need to doing it more complicated, than it is :-)
As you are using JSP you should be using HttpSession. So you only have to call invalidate method when you access the logout page (in this case, logout.jsp):
<% session.invalidate(); %>
<% response.sendRedirect("index.jsp"); %>
If you are using a servlet, you can process this there.
If you want to know more about JSP/servlet development I recommend you this series of videos, if you have little experience they are very easy to follow.

How to check user is logged in or not in Java EE

I use the Struts2 framework. In jsp, I show a login box in my project and when the user clicks on a login button, I set a cookie with the name "loggedin" and set its value to "true" in an Action Class.
Then returning "success" will load this login page again.
In login page:
<body>
<%
Cookie cookie[] = request.getCookies();
for( c : cookie )
{
if( c.getName().equals("loggedin") )
{
if( !c.getValue().equals("true") )
{
%>
//show login form here.
<%
}//end inner if
else //if cookie "loggedin" value is "true"
{
%>
//show username/profile picture/logout button here
<%
}//end else
}//end outer if
}/end for loop
%>
</body>
I got a problem. When I this click login button in the login form, a cookie is set and the page is reloaded. But instead of a username/profile picture, the login form is still being displayed until I reload the page manually.
How can I solve this?
I think it's not the correct way to check logged in or not. Can somebody please tell me how to check this in another way?
Please ! Please ! Do not use scriptlets. They are hard to maintain and every developer loathes them.
There are many ways to track sessions.
Using cookies
URL Rewriting
Hidden params
These are well documented around the web. The fastest way to generate a session is to execute HttpSession session = request.getSession(true);. You can proceed to attach session information to this object once it has been created.
Take a look at a JSTL primer and rants on why scriptlets are bad.
Using scriptlets in jsp is never-ever recommended. Why are you not using struts tags or JSTL tags.
Use session to set a session attribute upon each successful login and check for session and that particular attribute for checking against user login. Like:
//on successfull login...
Session session=request.getSession(true);
session.setAttribute("id",id); //here in place of id you can use something related to user, that can uniquely identify to each user.
// now to check for user logged in or not
Session session=request.getSession(false);
// by providing false value it will try to access a session already available, but it won't create a new session.
//now you can check like this..
if(session!=null)
{if(((String)session.getAttribute("id")).equals(id))
{
// do your stuffs here.........
}
else
{
// you can send the control to login page or to somewhere else as your requirement.
}
}
else{
// send the control to login page because session object is null...
}
And one most important thing, don't write all these logics in your jsp's. Jsp is supposed to put view logic only. In struts put all business/main logic in Action class.

Cannot redirect with the response.sendRedirect

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

Using request.setAttribute in a JSP page

Is it possible to use request.setAttribute on a JSP page and then on HTML Submit get the same request attribute in the Servlet?
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.
If you want to persist attributes through requests you need to either:
Have a hidden input in your form, such as <input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />. This will then be available in the servlet as a request parameter.
Put it in the session (see request.getSession() - in a JSP this is available as simply session)
I recommend using the Session as it's easier to manage.
The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.
You can do it using pageContext attributes, though:
In the JSP:
<form action="Enter.do">
<button type="SUBMIT" id="btnSubmit" name="btnSubmit">SUBMIT</button>
</form>
<% String s="opportunity";
pageContext.setAttribute("opp", s, PageContext.APPLICATION_SCOPE); %>
In the Servlet (linked to the "Enter.do" url-pattern):
String s=(String) request.getServletContext().getAttribute("opp");
There are other scopes besides APPLICATION_SCOPE like SESSION_SCOPE. APPLICATION_SCOPE is used for ServletContext attributes.
If you want your requests to persists try this:
example: on your JSP or servlet page
request.getSession().setAttribute("SUBFAMILY", subFam);
and on any receiving page use the below lines to retrieve your session and data:
SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");
Try
request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
i think phil is right request option is available till the page load. so if we want to sent value to another page we want to set the in the hidden tag or in side the session if you just need the value only on another page and not more than that then hidden tags are best option if you need that value on more than one page at that time session is the better option than hidden tags.

Categories

Resources