I have implemented a Filter that will check all the patterns - '/*' using the below code..
Here is my filter code:-
First, it checks for session attribute, if its null it sets a session attribute.
If a user tries to access any URL directly, I check the referrer and redirect to accessblocked.jsp page. This works but it does not redirect to the page..Instead it runs the same check to all URL's within the same page(CSS/image files) and does not load anything..How to stop my filter running once a condition is satisfied?
if (session.getAttribute(CHECK_TOKEN) == null) {
if (referer == null) {
session.setAttribute(CHECK_TOKEN, CHECK_TOKEN);
} else if (referer
.equals("http://p4-vsa.com/gui/banana/index.html")) {
httpResponse.sendRedirect(httpRequest.getContextPath()
+ "/accessblocked.jsp");
}
}
Related
The requirement is this: When a user session is expired, call expired.htm page, but on the first connection to the web site, show login.htm.
I tried using a filter but it doesn't work, I'm not able to tell to filter how to understand if it's a new request or an old request expired. This is the code I used:
if (session.getAttribute("userProfile") == null) {
logger.debug("Session: " + ( session.isNew() ? "true" : "false"));
logger.debug(request.getSession().isNew());
if ( request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid() ) {
return new ModelAndView("redirect:expired.htm");
} else {
return new ModelAndView("redirect:login.htm");
}
}
I tried different solutions proposed here on Stack Overflow and on the general internet, but nothing has worked and every request goes to expired.htm.
How do you get the session object? Before doing that, use
if (request.getSession(false)==null) {
// no session present (expired or new visitor)
[... do something ...]
} else {
// active session present
}
You need to use the validation above before use any attribute in the session. Because if the session don't exists you can't get an attribute of it.
You need to put false inside parentesis.
if(request.getSession(false) == null) { //Session don't exists
...
}
Java explain:
public HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
Parameters:
create - true to create a new session for this request if necessary; false to return null if there's no current session
Returns:
the HttpSession associated with this request or null if create is false and the request has no valid session
I have a Portal that combines Spring controllers with a couple of regular servlets.
In the screen the user has a list from which he/she selects a credit card in order to see a report of the transactions of that card. As an extra security measure, I avoid sending the credit card in any request to the client so I have a list of credit cards numbers masked that I send to the user and in the request sent by the user I receive a record id which I use to determine which credit card is querying.
In a controller (ReportController), I have a method that process this input and call (locally) the servlet in charge of processing the report (ReportServlet). If there is any error in the processing it should return it to the screen using the model param "error". This last part isn't working.
If there is an error in the ReportServlet it is not returned to the screen. If I comment the forward line (and force an error) it works, but after doing the forwarding it doesn't. What I'm doing wrong?
Here's the code:
ReportController
try {
...
if (cardholders == null || cardholders.size() < 2 || id <= 0) {
model.put("error","there's an error");
return CARDTRANSACTIONS_PATH;
} else {
...
HttpUpdatetableRequestWrapper customRequest = new HttpUpdatetableRequestWrapper(request);
customRequest.setParameter("cardnumber", cardholder.getCardnumber());
request.getRequestDispatcher(config.getProperty("reportservlet")).forward((HttpServletRequest) customRequest, response);
String error = (String) session.getAttribute("error");
if(!(error == null || "".equals(error))){
throw new RuntimeException(error);
}
}
} catch (Exception ex) {
model.put("error", "there's an error");
} finally{ return CARDTRANSACTIONS_PATH;}
When your controller returns, Spring will give the model to an AbstractView which will decompose it and transfer the attributes over to the request. So when you are adding attributes to the model object in your controller, you're only adding them to a map with no relationship to the request. If you want those attributes to be available to the resource you forward to, you should add them directly to the request.
When you forward, you're expecting the resource you're forwarding to to handle the response, so you should make your controller return null in that situation, so that it doesn't do any further processing.
I am trying to write my first app on Google App Engine, I was trying to maintain a session, I created a login page on submit, it call to a servlet, servlet validates the user and create a new session using the following code.
void createSession(String Username) {
getThreadLocalRequest().getSession(true).setAttribute("Username", Username);
}
login page after calling the servlet redirects to some page i.e. abc.jsp, my abc.jsp page contains
<body><%
try {
if (request.getSession(false) == null) {
} else {
%>
Welcome to
<%=session.getAttribute("Username")%>
<%
if (session.getAttribute("Username").equals("")) {
%>
<b>Login </b>
<%
} else {
%>
<b>Logout</b>
<%
}
}
} catch (Exception e) {
}
%></body>
it works fine, but when I access abc.jsp without creating a session it is throwing an exception at this if (session.getAttribute("Username").equals("")) line, I dunno why kindly help me. I think it dont detect if session exists. but I have read so many threads like this It gave me this solution, I dunno what I am doing wrong.
As far as I remember
session.getAttribute("xyz")
returns null if the attribute does not exist...
so your NullPointerException occurs because you try to call equals on null.
I suggest to do a check on your attribute itself before validating its content:
if (session.getAttribute("Username") == null || session.getAttribute("Username").equals(""))
<%
if (session.getAttribute("Username") != null) {
…
}
%>
Before to check session's attributes, you have to see the session itself.
So, first:
HttpSession session = request.getSession(false);
if(session != null){...}
and then,
if(session.getAttribute("xyz") != null){...}
Better solution might be both in one line:
if(session != null && session.getAttribute("xyz") != null)
returns null if the attribute does not exist... so your
NullPointerException occurs because you try to call equals on null.
Obviously, it's strictly recommended to check your attribute, before validating its content (as above).
It Worked For me. Try This
String userName;
userName = (String)session.getAttribute("uname");
if (session.getAttribute("userName").equals(""))
Basically, I have a login.jsp page and a filter that checks if a session is valid or not. If the session is valid then continue, if not it will redirect to login.jsp.
The filter performs the redirection. However, after being redirected to login.jsp, nothing is shown on webpage. I am sure it's a problem with the filter, because after removing the filter from web.xml, the login.jsp displays webpage.
The filter is very simple and I got it from here. I don't know where the problem is in this case. Any suggestions?
if(request.getRequestURI().compareToIgnoreCase("/login.jsp")!=0)
{
if (session != null)
{
if(!session.isNew())
{
chain.doFilter(req, res);
}
}
else
{
System.out.println("Directed");
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
}
else
{
System.out.println("not directed");
}
You need to continue the filter chain for URI's matching the login.jsp string. Now all you do is print.
Like this:
{
System.out.println("not directed");
chain.doFilter(req,res);
}
In the outer else.
How can you access the REQUEST_URI from within a Struts 2 Action? In perl/php/ruby it is readily available via ENV["REQUEST_URI"] and the like. In java it seems that the PageContext.getErrorData().getRequestURI() is what I'm looking for, but sadly, the PageContext does not appear to be defined within the action, either because the ErrorDocument redirection makes the request not look like an error, or because it is defined later.
A particular example
Given an apache fronted (mod_jk/ajp) struts 2 app on tomcat reached via the ErrorDocument 404 configuration in apache. With the following details:
-- Original request url (which triggers the 404) --
http://server/totally/bogus/path
-- http.conf --
ErrorDocument 404 /struts2app/lookup.action
-- struts action --
public String bogusUrlLookup() {
HttpServletRequest request = ServletActionContext.getRequest();
// contains /lookup.action as does request.getRequestURI();
String url = RequestUtils.getServletPath(request);
// PageContext is null, so I cannot reach ErrorData from it.
log.info("pageContext="+ServletActionContext.getPageContext());
// Not in the ENV
// Map env = System.getenv();
// Not in the ATTRIBUTES
// request.getAttributeNames()
// Not in HEADER
// request.getHeaderNames()
return ERROR;
}
Again all I need is the string "/totally/bogus/path", but in the above action the only url string that I can find is "/struts2app/lookup.action". I'm tied to the ErrorDocument because the totally/bogus/path is not likely to be within the namespace of my application because apache serves other non-tomcat resources.
request.getAttribute("javax.servlet.forward.request_uri")
baseUri = (String)request.getAttribute("struts.request_uri");
Use:
JkEnvVar REDIRECT_URL ""
in your httpd.conf file. Then use request.getAttribute("REDIRECT_URL"); to get the variable in your jsp/servlets.
If you don't wanna miss the query string part, this is better:
final String referrer = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
if(referrer != null) {
final String query = (String) request.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING);
if(query != null && query.length() > 0) {
url = referrer+ "?" + query;
}
else {
url = referrer;
}
// do something
}