I currently have the following includes at the top of all of my jsp files:
<%# include file="inc/inc_cookie_login.jsp"%>
<%# include file="inc/inc_protect_page.jsp"%>
<%# include file="inc/inc_log_access.jsp"%>
The jsps have scriptlets that check for cookie and set a user object in the session if cookie exists, prevents access to the jsp unless a session has been set, write to a text file the User IP, name, page accessed, etc.,respectively.
The scriptlet approach above has worked fine but now that I have a better server set up and can utilize a web.xml file, I have been refactoring my app to best practices. The above is screaming FIXME! Should I be investigating listeners, filters, ?, or is my current approach adequate?
=== inc_cookie_login.jsp ====
<%# page import="model.STKUser"%>
<%# page import="model.STKUserCookie"%>
<%# page import="data.STKUserDAO"%>
<%
if ( request.getSession().getAttribute("STKUserSession") == null) {
STKUserCookie userCookie = new STKUserCookie(request);
String userBadge = userCookie.getUserID();
STKUserDAO userDAO = new STKUserDAO();
STKUser user = userDAO.getUser(userBadge);
if (user != null) {
user.setIpAddress(request.getRemoteAddr());
userDAO.updateLoginCount(user);
request.getSession().setMaxInactiveInterval(36000); //set to 10 hours
request.getSession().setAttribute("STKUserSession", user);
}
}
%>
This looks like a good one to be replaced by a filter. Create the filter class and ref it with a pattern in your web.xml. Scriptlets should not be used unless all other options have been reasonably exhausted.
Related
i have multiple web pages jsp and i use for the resubmit in refresh response.sendredirect("blabla.jsp") but one page work good , another page wen i press submit it go to a blank page and the row added to database, any solution for this problem ? thank you
`
<% String UC1 = "INIT";
if (request.getParameter("add_spec") != null) {
UC1 = "ADD_SPEC";
}
if (UC1.equals("INIT")) {
List<Speciality> specs = SpecialityController.INSTANCE.findAll();
%>
<%#include file="./WEB-INF/Add_Spec.jspf" %>
<%#include file="./WEB-INF/view_all_specs.jspf" %>
<%}
if (UC1.equals("ADD_SPEC")) {
String spec = request.getParameter("speciality");
SpecialityController.INSTANCE.create(new Speciality(spec));
List<Speciality> specs = SpecialityController.INSTANCE.findAll();
response.sendRedirect("main_admin.jsp");
%>
<%#include file="./WEB-INF/Add_Spec.jspf" %>
<%#include file="./WEB-INF/view_all_specs.jspf" %>
<% }
%>
`
You can use the Post/Redirect/Get pattern.
When a web form is submitted to a server through an HTTP POST request,
a web user that attempts to refresh the server response in certain
user agents can cause the contents of the original POST request to be
resubmitted, possibly causing undesired results, such as a duplicate
web purchase.
To avoid this problem, many web developers use the PRG
pattern - instead of returning a web page directly, the POST operation returns a redirection command.
In other words, when you submit the data, you should redirect to the page on which you can view (get) the data you've just added.
That way, refreshing will not resubmit the data.
Alternatively, you could use a CSRF/XSRF-like token.
Though this example is in PHP, you should understand the gist of it.
Update
Even better, you can check out this example for CSRF https://services.teammentor.net/article/00000000-0000-0000-0000-000000040a2e
I wrote the below code to test the status of msgCode. If the msgCode is not Success it should redirect to error.jsp file. If it is a Success it should stay on the same page . When I ran the code the page always redirects to error.jsp although msgCode is Success. What mistake did I do in my code. Can you please help me if you can. Thank in advance.
<%# page import="com.siebel.SurveyWebService.SurveyTester" %>
<%
SurveyTester tc = new SurveyTester();
tc.getResult();
java.lang.String msgCode = tc.getResult2().getStatusCode();
%>
<%= msgCode%>
<%
if (msgCode.toString() != "Success")
{
response.sendRedirect("error.jsp");
}
%>
First of all, you should use equal method for string comparison. Secondly, even though it's not a problem at the moment but you are creating objects in your jsp and faking the response. tc.getResult2().getStatusCode() is not an actual HTTP response from server.
In my application I am using struts2 and hibernate. In one of my service classes I used struts2 session for set an attribute and got that attribute in my jsp like this.
here is the java class portion:
Map fileInformation = ActionContext.getContext().getSession();
fileInformation.put("checkFirstPart"," Hello ");
here is the jsp scriptlet:
<%
Map recordedData2=ActionContext.getContext().getSession();
String checkFirstPart = (String)recordedData2.get("checkFirstPart");
%>
<%
if (checkFirstPart != null)
out.println(checkFirstPart);
%>
the problem is by every time i run my project, session is not clear and shows all previous messages until I restart the application server.
I used this also but it was not useful:
fileInformation.clear;
please help.
put this code in your jsp page after getting the attribues:
recordedData2.clear();
I think this will solve your problem
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)
I have been using Jsoup for parsing my HTML files and so far it does a great job. However, it's not able to parse any server tags ( <% ... %> ). I decided to extend it but I cannot find an easy way to extend its Parser and all those private/package level classes (i.e. TreeBuilder, TransitionState ... etc)...
So I started looking at Jericho as it claims it can parse server tags - however, its documentation is so poor that I cannot even get started easily. And seems like its API is not as friendly as what Jsoup provides - it's not that straight forward to extract some nodes and move it around ...
I wonder if anyone has the similar situation before and how you get it solved? In short, I just want to parse JSP files in Java. (Well .. please don't ask me to implement one by myself ;p )
Lastly I get a workaround: put server code block in a HTML comment block so that 1) server code can get executed correctly; 2) Jsoup can process the whole block as a HTML comment node without touching anything inside.
e.g.
<!--
<%# page language="java" errorPage="/error.jsp" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" %>
<%# page import="com.systemcrossed.groupbuystart.webapp.display.DisplayHelper" %>
<%# page import="com.systemcrossed.groupbuystart.webapp.util.JsonUtil" %>
<%# page import="org.apache.commons.lang.StringEscapeUtils" %>
<%# include file="/_sys/pages/public/incl/jspCommon.jsp" %>
-->
<!--<%
// Java code here
%>-->
<html>
<head>
... html stuff
It works well for me now! Hope ppl who got the same problem could get some help ! ;)