jsp,java-ee,jstl,struts,servlet-filters , Persistent authentication filter logging in; not propagating to JSP


Persistent authentication filter logging in; not propagating to JSP

Question:

Tag: jsp,java-ee,jstl,struts,servlet-filters

I've been working on a "Remember Me?"-style persistent authentication system, but after successfully authenticating and logging in the user, my JSPs do not reflect that the user is logged in until the next page request or refresh is processed. The cookie used for this is being written, and the database is being updated. Checking the login state of the user object within the Filter method indicates that the user object is being properly loaded. After refreshing or navigating to a different page, the page shows that the user is logged in.

Why does the successful login not show up on the first page?

Is there something obvious that I'm not doing here, that would prevent changes to the session data from within a Filter from being propagated to the JSP? Is this a limitation that needs to be overcome by a forced refresh?

This is written for a Java EE 5 and Struts 1.x site rendering to JSPs, using a custom Java EE Filter class as the entry point for automatic login. The filter is installed first in the chain, and mapped to "/*" in my web.xml.

My filter method implementation looks like this:

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    if (!isPersistentAuthEnabled()) {
        chain.doFilter(req, resp);
        return;
    }
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    HttpSession session = request.getSession(false);

    SessionStore store = null;
    if (session != null) {
        store = (SessionStore)session.getAttribute("sessionStore");
    }

    User user = null;
    if (store != null) {
        user = store.getUser();
    }

    if (user == null || user.isLoggedIn()) {
        // Skip authentication if no user object in session, or if already logged in.
        chain.doFilter(req, resp);
        return;
    }

    PersistentAuthenticationManager manager = null;
    try {
        manager = new PersistentAuthenticationManager();
    } catch (Exception e) {
        LOG.warn("skipping");
        chain.doFilter(req, resp);
        return;
    }

    try {
        manager.authenticateUser(user, request, response); // Authenticates based on cookie and DB store
        if (user.isLoggedIn()) {
            LOG.debug("success"); // this is being logged correctly
        }
    } catch (Exception e) {
        LOG.warn("failure");
    }
    chain.doFilter(req, resp);
}

The relevant code in the JSP is as follows (mapping the taglib jstl-core.tld to the c prefix):

<c:choose>
    <c:when test="${sessionStore.user.loggedIn}">
        <!-- Not shown: Display welcome message -->
    </c:when>
    <c:otherwise>
        <!-- Not shown: Click here to log in -->
    </c:otherwise>
</c:choose>

I've tested this on Chrome and IE so far, and the same thing happens on both. My idea for a fix would be to force a refresh by redirecting the user to the same page, but I fear that might have some ill effects, such as if that were to hit the Struts action handlers for certain requests (ie. posting things) before submitting a redirect, among other doubts. Is there some other way to handle this scenario?

EDIT: Since I believe I can safely assume users won't be submitting any forms or processing delicate actions on their first access of the site, I'm going to go with an automatic refresh via AJAX verification from the JSP which sets up the login prompt. I've discovered that the filter in question doesn't run when a plain JSP (such as the index page) is requested; it only appears to run when a Struts action is invoked. I was confused because an AJAX action on the homepage of this particular site was authenticating the user, and NOT the index.jsp request; I determined this by logging the URL of the request from within the filter. I'll describe the process in an answer.


Answer:

As it turns out, the filter that I've set up for persistent authentication appears to only run when a Struts action is invoked; as such, it wasn't running on the index page of my site (among other pages), but in my case was instead authenticating when an AJAX call to a Struts action from the index page was processed. I've tested this for other non-Struts pages, and it appears that none of them pass through the filter I've implemented.

The way I've solved this was by placing code into my login check JSP which invokes a Struts action via AJAX (thus triggering the filter in the background); the action returns JSON which indicates whether or not the user is logged in. If logged in, the AJAX response handler then shows the user an overlaid notification for a brief time, then refreshes the page, showing the correct contents as if the user were logged in.

The relevant portion of the JSP which displays the login prompt (updated):

<c:choose>
    <c:when test="${sessionStore.user.loggedIn}">
        <!-- Not shown: Display welcome message -->
    </c:when>
    <c:otherwise>
        <script src="/path/to/persistentAuth.js"></script>
        <script type="text/javascript">
            checkPersistentAuthAndRefresh();
        </script>
        <!-- Not shown: Click here to log in -->
    </c:otherwise>
</c:choose>

Inside persistentAuth.js:

function checkPersistentAuthAndRefresh() {
    var refreshPage = function () {
        window.location.reload(true);
    };
    $.ajax({
        url: "http://example.com/path/checkPersistentAuth.do",
        dataType: "json",
        success: function (data) {
            if (data.isLoggedIn) {
                showArbitraryDropDownMessage();
                setTimeout(refreshPage, 100);
            }
        }
    });
}

Related:


Why ${!blabla.blibli} returns true in JSTL even if blabla doesn't exist?


java,jsp,jstl
As mentionned in the title, I don't understand why when the variable blabla does not exist I have: ${blabla.blabla} which returns nothing and ${!blabla.blabla} which returns true I guess that there is an implicit exception catch in the jstl evaluation but I can't understand the inner process and why it...

Persistence.xml overridden in Arquillian tests


java,java-ee,integration-testing,wildfly,jboss-arquillian
Arquillian examples mainly show how to construct WarArchive, JavaArchive, etc. I can't find any good example how to override one of jar files which exists in already compile war file. The reason is that one of the jars contains persistence.xml which I wan't to override to defined for instance hbm2ddl.auto...

Intellij web application on tomcat server shows http://localhost:8080/index.jsp instead of http://localhost:8080/myapp/index.jsp


java,jsp,tomcat,servlets,intellij-idea
I'm following a tutorial on udemy. In the tutorial he is using eclipse. But i'm following the course with intellij. Every thing works fine but one thing i keep noticing is that when he runs the servlets or jsp pages it is always shows the project name before the servlet(http://localhost:8080/myapp/index.jsp)....

Java Servlet - get parameters with same name


java,java-ee,servlets,post
I know that I can get parameter like: HTML <input type="text" name="field" value="test"> Servlet String field = request.getParameter("field"); But what if I have multiple input with same name like: HTML <input type="text" name="line[]" value="test1"> <input type="text" name="line[]" value="test2"> <input type="text" name="line[]" value="test3"> In PHP I can just use name="line[]" to...

How to share the same email session between all instances of the application?


java,session,java-ee,javamail
Maybe this question is already answered, but I couldn't find the proper answer. I have a web application based in JSF, and I want to share the same email session between all the instances of the application, yet I haven't found how to do that. My questions are: a) What...

How to compile and run a JSP Beans project using Eclipse


java,html,eclipse,jsp
I am a noob trying to learn what I can about JSPs. I am using Eclipse as my ide and have run into a small problem that I hope someone can help me out with. I have a dynamic web project with the following files: index.html <!DOCTYPE html> <html> <head>...

Show and hide select input which is created dynamically


jquery,jsp,show-hide
I want to show a select form (which is hidden), when a checkbox is checked. I have coded this bootply which is working right. However, in my JSP page depending what an object contains, many checkboxes are printed, which all of them contain the .action-do class so, what is happening...

Print and println aren't executed in the same time


java,jsp,servlets,printing,println
I have a method in my servlet where I have some prints to the console.. private void collectingWorkPositions(HttpSession session, HttpServletRequest request) { System.out.println("Collecting1.."); //code... System.out.println("Collecting2.."); //code... System.out.print("printing p: "); for(Integer i:p) System.out.print(i + " "); } When this method iscalled, only Collecting1.. Collecting2.. are printed in the console. When I...

set focus to next input element after jsf's change value listener


javascript,jsp,jsf
in one of our front-end screens we have the following layout as follows <h:outputLabel for="firstName" value="first name" /> <h:inputText styleClass="required" id="firstName" size="30" maxlength="30" value="#{ownershipStoreInfoController.form.ownerFirstName}" onchange="submit()" valueChangeListener="#{ownershipStoreInfoController.useOwnerInfo}"> <e:validateRegExpr pattern="([A-Z,a-z,0-9,%@()#&amp;,.;:_\$\/\-\{\}\[\]\'\\s*]{1,30})?" /> </h:inputText> <h:outputLabel for="lastName" value="last name"...

filter mapping to last path segment


java,java-ee,web.xml,servlet-filters,servlet-mapping
I am trying to map a filter to a specific url in web.xml. The problem is that there is a dynamic path segment in the url and I need to map my filter only to URLs ending with a specific path. For given URLs: http://company.com/webApp/aaa/end http://company.com/webApp/bbb/end http://company.com/webApp/ccc/end I need to...

Open a properties file from a class in a Dynamic Web Project


java,eclipse,jsp,properties-file
I'm using Eclipse for EE Developer. I need to access to a properties file (db.properties) from a class's method (DBQuery.java). The class is located inside a package inside the src folder. For the properties file i tried almost everything that i could find over the net to make it work,...

Jsp list output [email protected]?


jsp,spring-mvc,spring-boot
I have a list of tweets inside a user and when I iterate through them all I get is the object but not the actual text <c:forEach items = "${tweets}" var="user" ></c:forEach> <h1><c:out value="${user.tweets}" /></h1> </div> how do I get the value of the tweets, they all save as text...

EJB injection not working in different classes


java-ee,netbeans,jersey,ejb,jax-rs
I have tried to inject an Entity EJB(Facade and entity from MySQL database) but it doesn't work depending on the class it is in. I use a Rest webService and it work in the webService class. I use a multi layered architecture and I don't want my EJB to be...

PropertyNotFoundException in jsp


java,jsp
Am getting this error in my application javax.el.PropertyNotFoundException: Property 'survey_id' not found on type com.moh.forms.MOH731 javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:229) javax.el.BeanELResolver$BeanProperties.access$400(BeanELResolver.java:206) javax.el.BeanELResolver.property(BeanELResolver.java:317) javax.el.BeanELResolver.getValue(BeanELResolver.java:85) This is my MOH731.java @Id @GeneratedValue(strategy = GenerationType.AUTO) private int survey_id; public MOH731 (int survey_id, String uname)...

Error while including jsp with angular inside non angular jsp


javascript,angularjs,jsp
I included a jsp with angular directives (A.jsp) inside a non-angular jsp(B.jsp). If I access A.jsp directly those models "{{X}} {{Y}}" are resolving correctly to Xvalue Yvalue But if I access A.jsp through B.jsp I am seeing unresolved ng-model s. {{X}} {{Y}} What could be the reason? My code: Inside...

I cannot instantiate my bean using @Inject and Vaadin CDI


java-ee,vaadin,cdi,vaadin7
I am trying to inject my components and beans using Vaadin-cdi. Note the code below is simplified a bit. @Theme("valo") @CDIUI("") public class MyUI extends UI { @Inject private CDIViewProvider provider; @Override protected void init(VaadinRequest request) { Navigator navigator = new Navigator(); navigator.addProvider(provider); navigator.navigateTo("mypanel"); } } And here goes MyPanel:...

Servlet to jsp on button click - whats the error?


java,jsp,servlets
I have a simple form on a jsp page, as given below. On clicking the button, it should take us to a servlet by the name of LoginValidation. But it doesn't work. <form name="login_form" action="LoginValidation" method="get" onsubmit="return func()" > <input type="text" placeholder="Username" id="username" class="style-4" /> <input type="password" placeholder="Password" id="pass" class="style-4"...

Login page filter problems


jsp,servlets,servlet-filters
I'm trying to apply a filter to my login page. I'm just not sure how it works, since I'm not too familiar with filters. I'm trying to redirect a user that logs in to different pages based on their user type. A user has either the user type 'Customer', 'Owner'...

Can't insert or update record to database jsp


java,jsp,jdbc
I am creating a form that is used to insert, update and delete data in a database, managed to do everything right but update and insert are not functioning. Delete works fine. Any help with solution will be highly appreciated FirstController package com.firstmohform.controller; import com.firstmohform.dao.FirstDAO; import java.io.IOException; import java.io.PrintWriter; import...

Vector : References to generic type Vector should be parameterized


jsp,generics,vector
I have this problem(yellow line) in my jsp file which often caused my eclipse program keep no responding. Although my program can run, but how can i get a rid of this following line of code. Vector vFieldName = (Vector) session.getAttribute("table_vFieldName_"+TABLE_TYPE); Vector vTable = session.getAttribute("table_vTable_"+TABLE_TYPE) == null ? new Vector():...

JSP - issue with custom Taglib


java,jsp
I just tried to add a custom taglib to my project, such that the testtaglib.tld file contains: <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>name</shortname> <tag> <name>test</name> <tagclass>taglib.TestTaglib</tagclass> <bodycontent>empty</bodycontent> <attribute> <name>testCode</name> <required>true</required> <rtexprvalue>true</rtexprvalue>...

Radio button group name


java,jsp
I have a radio button group in a jsp page populated from database as follows; <c:forEach var="attCat" items="${attCat}"> <input type="radio" name="rdCat_${iter.index}" value="${attCat.catId}"><span style="font-size: x-small;">${attCat.category}</span> </c:forEach> when I retrieve the values I get null point exception String[] cat = request.getParameterValues("rdCat_${iter.index}"); the radio button names appear in the html as rdCat_1, rdCat_2...

How to use button instead input, style input?


css,forms,jsp,servlets,post
My form: <form method="POST" action="AController"> <div class="userInput"> <table class="userInput"> <tr> <td><input type="text" id="username" name="login"></td> </tr> <tr> <td><input type="submit" id="submitRegInput" name="reg" value="Submit"></td> </tr> </table> </div> </form> I'm trying to style <input type="submit" id="submitRegInput" name="reg" value="Submit"> like this: #submitRegInput { background: no-repeat...

MySQLSyntaxErrorException in SQL syntax


java,mysql,jsp,mysql-connector
I am trying to select data from a table using prepared statement. But it seems like I am getting syntax error which I cannot solve alone. try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mydb"; String dbusername = "root"; String dbpassword = ""; // Change it to your Password // Setup the...

How to access application data in a session .jsp file


java,html,jsp,session,user
I am new to the javaservice page session environment, and I am executing the following loop to view all my session attributes: <% for (Enumeration e = session.getAttributeNames(); e.hasMoreElements(); ) { String attribName = (String) e.nextElement(); Object attribValue = session.getAttribute(attribName); %> <BR> <%= attribName %> - <%= attribValue %> Which...

How to call MySQL view in Struts2 or Hibernate


java,mysql,hibernate,java-ee,struts2
I have a view in MySQL database CREATE VIEW CustInfo AS SELECT a.custName, a.custMobile, b.profession, b.companyName, b.annualIncome FROM customer a INNER JOIN cust_proffessional_info b ON a.cust_id=b.cust_id Is there any way that i can call this view using Struts2 or in Hibernate. I have tried to search it but could not...

JAX-RS @FormParam one time for all methods


java,web-services,java-ee,jax-rs,java-ee-6
I am developing Java "JAX-RS" Web Services for books and contents. There will be 100s of URLs something similar ... https://api.example.com/v1.3/book1/chapter/1 https://api.example.com/v1.3/book1/chapter/2 ... https://api.example.com/v1.3/book1/chapterN To fetch the chapter content user needed to POST authToken, which I validate in server and return content or error. The sample code ... @Path("/book1") public...

Wildfly Kafka clients module javax/management/JMException not found


java-ee,jboss,wildfly,kafka
I'm try to create Kafka clients module for Wildfly. Here is module.xml: <?xml version="1.0" encoding="UTF-8"?> <module xmlns="urn:jboss:module:1.0" name="org.apache.kafka.clients"> <resources> <resource-root path="kafka-clients-0.8.2.0.jar"/> <resource-root path="lz4-1.2.0.jar"/> <resource-root path="snappy-java-1.1.1.6.jar"/> </resources> <dependencies> <module name="org.slf4j"/> </dependencies> </module> Wildfly (8.2.0-Final) gives this error on boot:...

Debugging service test client: Netbeans debugger won't recognize Glassfish server


java,debugging,java-ee,netbeans,glassfish
Here's what I've done so far: Did a fresh build of project (web service project). Redeployed project war file to Glassfish server. Restarted server with --debug=true. Attached debugger from Netbeans. Debugger attaches to the server without an error (responds "User Program Running"), however the Debug tab (in the Projects/Files/Services window)...

How to exclude one textbox from the others that are using isNumeric validation with jQuery?


jquery,jsp
I'm using jQuery 1.11x in a jsp page with textboxes. I'm working with five text boxes and I need to make sure they all have numeric entries, however, I want to exclude the first one as it has a string representation of a date in it and I validate that...

What are the techniques to manage “session” or invocation context for Stateless EJBs during Remote calls?


session,java-ee,ejb,rmi,java-ee-6
I am writing an application that uses RMI to invoke EJBs. The EJBs are Stateless; the business requirements do not require conversational state with the client. One of the parameters to the EJB method calls is a "User" object used to determine if the user associated with the call has...

@InterceptorBinding / CDI/ EJB 3.2 - problems with injection


java,java-ee,cdi,wildfly-8,java-ee-7
My dev environment is: WildFly 8.1, CDI, EJB 3.2, JDK 1.7. App is packed as an ear archive (one ejb + one war) because probably it gonna have other web modules in the future. I'm struggling with a custom @InterceptorBinding type used inside my EJB stateless bean. @Inherited @InterceptorBinding @Target({...

Initialize class with constructor in


jsp,servlets,usebean
I am trying to initialize a class by passing a parameter to the constructor. I need the scope to be "page". I know I have one argument in my constructor, but how do I have one that accepts parameter using <jsp:useBean>, and can be called from a JSP page? public...

HTTP GET request get HTML page code instead of expected json Response


java,java-ee
/Here is the code/ <html><head><meta http-equiv="Refresh" content="0; URL=http://www.fifacoinservice.com/api/v1"></head><body></body></html> HTTP/1.1 400 Bad Request Server: PipeGuard Date: Mon, 15 Jun 2015 10:29:32 GMT Content-Type: text/html Content-Length: 605 Connection: close <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html> <head><title>400 Bad Request</title></head> <body bgcolor="white"> <h1>400 Bad Request</h1> <p>Your...

How to trigger a doGet before displaying a jsp page


jsp,java-ee,web.xml
I have a webpage which is named export.jsp, when the user acces domain/export.jsp, I want him to automatically download a csv file via the doGet method of a servlet. Afterwards I want to display the actual jsp file, which is export.jsp My doGet method is as follows: protected void doGet(HttpServletRequest...

Java Struts2 (Action class not found)


java,xml,jsp,struts2
The error which I am getting. It was running all fine a day before but when open it today I get the following errors. Action class [com.tutorialspoint.struts2.HelloWorldAction] not found - action - file:/C:/Users/sai/Struts2/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/HelloWorldStruts2/WEB-INF/classes/struts.xml:10:30 at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyAction(XmlConfigurationProvider.java:374) at...

html form action not working when using eclipse


java,eclipse,jsp,servlets
I am new to JSP and Java Servlet. I was going through this tutorial by Java Brains. In this tutorial get and post method is handled. I wrote my html code under web-content. </head> <body> <form action="http://localhost:8080/SimpleServletProject/hello" method="post"> <input name="userName" /> <input type="submit" /> </form> </body> Following is the hello.java...

Set default value for struts 2 autocompleter


jquery,jsp,struts2,struts2-jquery,struts2-jquery-plugin
I have implemented a struts 2 autocompleter in which i have used a list of String like this - <sj:autocompleter id="cityId" cssClass="txtfield8" name="outlet.cityName" list="cityList" autoComplete="true" forceValidOption="false" /> How can I set a default value for this, so that every time it loads, a default value will be shown ?...

Hibernate criteria accepting %% value


java,hibernate,java-ee,orm,hibernate-criteria
I am using the below Hibernate code to filter workFlowName. crt.add(Restrictions.like("workFlowName", workFlow, MatchMode.ANYWHERE)); // crt is the criteria The problem is when I pass the value to workFlow from web (TextBox).it fetching the value correctly (I am passing sym in text box if fetch 10 records.if i pass the same...

References of objects in Java EE. Difference for remote and local interfaces?


java,java-ee,call-by-value
As far as I know, Java is only call-by-reference. If an entity has to go through a remote interface, can it still have a reference? Now the entity is basically in another container, how can it still have the reference of the object? In other words: Is it possible that...

How to get current jsp file path in war?


java,jsp
Due to lot of forward request, it is hard to identify the current showing jsp file. Is it possible to get the current jsp file path in war? How to achieve? For an example: URL: http://localhost:8080/controller/action File Path: /view/dev/test.jsp <%= getServletContext().getRealPath("/") %> The above statement doesn't work, it show C:\Projects\test\build\web\...

Form submit portlet with Spring MVC


java,jsp,spring-mvc,liferay,portlet
I'm trying to achieve a Liferay portlet of submit form using spring MVC. The model: package com.model; public class Person { String firstName; String middleName; public String getFirstName() { return this.firstName; } public String getMiddleName() { return this.middleName; } public void setFirstName(String firstName) { this.firstName=firstName; } public void setMiddleName(String middleName)...

Why paging query does not work


java,jsp,java-ee,servlets,jdbc
The main function of this program is to write a page displays the contents of the database and can achieve Pagination When you first visit the page can display the contents of the database,But when you click on the link below when the page is not able to properly display...

Need to add elements of an array to a variable of JavaScript in JSP


javascript,arrays,jsp,jstl
I am creating an array for a list of markers of google map. The code works for one forEach loop but I need to add elements of a new array to the list as well. My current code shows following error message on var of result2. Syntax error on token...

JSP form sending data including files in servlet


java,jsp,servlets,post,get
I am tryig to send some data from jsp form to a servlet. All my data are type="text" except from one that is type="file". I know that if i want to send the data to my servlet, i have to use request.getParameter(...). (My data) In order not to be null...

Sending text file to client through Spring MVC web application


java,spring,jsp,spring-mvc,servlets
After doing some research online on the subject I currently managed to get things working with this code: @RequestMapping(value = "/report040Generated", method = RequestMethod.GET) public String index(Model model, HttpServletResponse response, HttpServletRequest request) throws IOException { String myString = "Hello"; response.setContentType("text/plain"); response.setHeader("Content-Disposition","attachment;filename=myFile.txt"); ServletOutputStream out = response.getOutputStream(); out.println(myString); out.flush(); out.close(); return...

How to open a new page when button is clicked on


java,html,jsp,servlets,web-applications
The question is vague so allow me to clarify. I am developing a web app locally on eclipse and using Servlets, JSP, and an html document to design a web page. I have a home page which has two buttons, signup and login. I have one file, called index.jsp, which...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring


java,spring,jsp,spring-mvc
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- avoid '???' --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"/> </bean> if i create other subfolders under jsp , for instance /WEB-INF/jsp/reports , /WEB-INF/jsp/insertions how should i configure now the viewResolver to can resolve these new sub folders??...

How to display text in browsers tab bar in a javaserver page [closed]


html,jsp,browser,text,tabs
I have heard of being able to display images in a browsers tab bar here: http://stackoverflow.com/questions/120420/image-icon-beside-the-site-url But I was wondering if there might be an easier way to do this for just some simple text? I am trying to display just two lines, last login and IP address in this...