How to call servlet when jsp is load - java

I want to get latest data to my home page by calling servlet, means when user click on refresh button home page should fill with most recent data. For that i used
jsp:forward page="tests"/>.
But finally I end up with redirect loop. Soo how can I achieve this?
myservlet is this :
RequestDispatcher view = request.getRequestDispatcher("tt.jsp");
view.forward(request, response);
How I am going to do this with out getting into never ending loop?

I have solved this problem successfully by checking attribute is null.
code:
<%
if((request.getAttribute("vdata") == null) || request.getAttribute("ldata") == null ||
request.getAttribute("mdata") == null){
%>
jsp:forward page="intial_getdata"/>

Related

Perform an action on JSP if redirected from a servlet

I want to perform an action on a JSP if redirected from a specific servlet only else do nothing.Is it possible?
In my JSP there are different errors defined. This JSP calls a servlet (with contentType as application/pdf) which opens in a new tab and searches for a PDF for 25 seconds and then if PDF is not found redirects to same JSP which shows the error message "File not found". I want to show the error if called from servlet only else do nothing.
JSP Code:
<%}else if(hPP!=null && hPP.get("errorcode")!=null && hPP.get("errorcode").toString().equalsIgnoreCase("Issue")){%>
<c:if test="${cameFromServlet}">
<div class="SplInputField">
<label class="FontBlod">Download fail</label>
</div>
</c:if>
servlet code
if (content == null) {
request.setAttribute("cameFromServlet", true);
String redirectJspUrl = request.getParameter("homeRedirect");
String strReceiptPage =
redirectJspUrl.substring(0, redirectJspUrl.lastIndexOf("/")) +
"/GetQReceiptPage";
response.sendRedirect(strReceiptPage);
}
Add an attribute to the request in the servlet like this
httpservletRequest.setAttribute("cameFromServlet", true)
then in your JSP check for it
<c:if test="${cameFromServlet}">
DO STUFF HERE
</c:if>
EDIT:
What you have done in your edit will not work, since you are doing a redirect. Which means the browser is sent a 302 response to tell it to issue another request against the new url. Do you have a specific requirement to change the url for the user? If so you will need to add the cameFromServlet attribute to the session instead - like this:
req.getSession().setAttribute("cameFromServlet", true);
Bare in mind though, that cameFromServlet attribute will remain on the session until you unset it so if there was another time that jsp page is shown you will run into problems unless you do something to unset it - either by introducing another servlet in the middle and moving it from the session to the request - thus simulating Springs flash map behaviour or unset it in the JSP after you have used it - like this:
<c:remove var="cameFromServlet" scope="session" />
If you do not need the URL to change for the user, you can change your servlet code to make use of a request dispatcher (what I thought you were doing)
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/yourjsp.jsp");
requestDispatcher.forward(req, resp);

Redirecting the page with Servlets Java

I have a jsp page with a form that when it’s submitted goes to a Servlet that inserts the form data into the database.
When the data is inserted into the database, I’m trying to get the browser back to my jsp page and show a javascript alert saying that the data was inserted successfully, my code is the following:
RequestDispatcher rd;
if(dao.insertClient(client)) {
rd = getServletContext().getRequestDispatcher("/pages/clients.jsp");
rd.include(request, response);
out.print(
"<script type=\"text/javascript\">"
+ "alert("Client inserted successfully!");"+
"</script>"
);
}
This code is doing exactly what I want, but this method getRequestDispatcher() redirects the page to the servlet itself, and the URL is like http://localhost:8080/Servlet, this way I can’t access any intern link of the page, since the links to the other pages obviously are outside of the servlet context, and the glassfish returns the 404 error.
Instead of using getRequestDispatcher(), I’ve tried using the response.sendRedirect(), this way I can insert the data into the database and access the intern links, but the javascript alert isn’t shown.
Somebody has a suggestion on how I can redirect the page to the clients.jsp and display the javascript alert?
Thanks!
you can try another approach :
Set parameter from servlet like this :
RequestDispatcher rd;
if(dao.insertClient(client)) {
rd = getServletContext().getRequestDispatcher("/pages/clients.jsp");
request.setAttribute("isSuccess", "success");
rd.include(request, response);
}
access the parameter in jsp to check whether to show alert or not.
<%
String result = request.getParameter("isSucess");
if("success".equals(result)){
%>
<script type="text/javascript" >
alert("Client inserted successfully!");
</script>
<%
}
%>

JSF Phase Listener redirect form not iframe

I have this PhaseListener that checks whether the user is still logged in or not after restoring a view. If the session has expired, then I want the entire form to redirect to the /login.jsf page but instead it only redirects the iframe within.
Basically, this is my code in the afterPhase() method:
if (isWebUserLogonOk(session)) {
NavigationHandler nh = faces.getApplication.getNavigationHandler();
nh.handleNavigation(faces, null, "loggedoff");
}
Where loggedoff is a navigation case that takes you to login.jsp page.
The redirect is done as expected but in this particular case I want it to be done for the entire form and not the iframe (JSF rookie talking here).
If you do not want to have a page (e.g. the login page) shown in an iFrame, a javascript framekiller should solve this.
Add the following code into your login pages head and try again:
<script type="text/javascript">
if(top != self) top.location.replace(location);
</script>
It easily reloads the current page as top page.
Hope it helps...

adding security in Struts 2 spring application

I am developing an application with spring 3 struts 2 and hibernate. After login only i have to display the pages
It is working fine. when i testing i found the big mistake
that is i copy the url of the page which needs to display only to logged-in user
and paste it in other browser means it is displaying the page without login.
<%
String userId= (String)session.getAttribute("userId");
System.out.println(userId);
if(userId == null || userId.equals("") ){
response.sendRedirect("login.jsp");
}
%>
I have included this for all jsp. I know this is not a best practice. Is any better option available?
How would i overcome this error?
if(userId == null || userId.equals("") ){
response.sendRedirect("login.jsp");
}
should probably have a return in there to prevent rendering the page content:
if(userId == null || userId.equals("") ){
response.sendRedirect("login.jsp");
return;
}
Nothing in the javadoc suggests that sendRedirect causes abrupt exit or causes the response body to not be shipped to the client.
What is probably happening is that your response contains a redirect header, but also contains the page content which you might not have meant to send.
I am still at education so do know how good is my solution , but i did not crash so hope it is correct
and it is quite similar to #muthu 's code
I had used JPA-eclipselink and Struts2
Action Class
String checkLogin = "SELECT user FROM UserEntity user WHERE user.username = :username AND user.password = :password";
Query checkLoginQuery = em.createQuery(checkLogin);
checkLoginQuery.setParameter("username", loginUsername);
checkLoginQuery.setParameter("password", loginPassword);
userEntity = (UserEntity) checkLoginQuery.getSingleResult();
Map sessionMap = ActionContext.getContext().getSession();
sessionMap.put("userEntity", userEntity);
JSP -> all jsp pages have this(bug:affected if session is not killed when browser is not closed )
<%# taglib prefix="s" uri="/struts-tags" %>
<s:if test="%{#session.userEntity == null}">
<jsp:forward page="login.jsp"/>
</s:if>
Correct me if I am wrong
Quoting this page
Both and RequestDispatcher.forward() are what I refer to as "server-side" redirects
The response.sendRedirect() is what I call a "client-side" redirect.
so a server side forward looks more safe to me , maybe I am wrong (I am sorry if I am miss interpreting it ,not worked in real life projects yet)

call response.redirect from inner div of a page to load a new page onto the browser

I'm loading a some page content to an inner div called 'center_column' in my index.jsp using ajax load method.
$('#center_column').load('abc.jsp', function() { });
but while it is loading I want to check for the session time out and redirect the request to login page. This session time out code is in within the 'abc.jsp'
I used
response.sendRedirect("login.html");
method for it. But this will reload the login.html with in the #center_column div.
But I want to load login.html onto the browser instead of the existing page ( index.jsp) on the browser. And also I want to fix this without using javascript.
Can anyone guide me to solve this issue please
Thanks
You have to use javascript, but it's minimal. Try handling your session check on the server like this:
if (request.getSession(false) == null) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
Then in your callback function on the client side,
$('#center_column').load('abc.jsp', function(responseText, textStatus, xhr) {
if (xhr.status == 403)
window.location = '/login.html';
});

Categories