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


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

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

    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) {
    chain.doFilter(req, resp);

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

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

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.


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:when test="${sessionStore.user.loggedIn}">
        <!-- Not shown: Display welcome message -->
        <script src="/path/to/persistentAuth.js"></script>
        <script type="text/javascript">
        <!-- Not shown: Click here to log in -->

Inside persistentAuth.js:

function checkPersistentAuthAndRefresh() {
    var refreshPage = function () {
        url: "http://example.com/path/checkPersistentAuth.do",
        dataType: "json",
        success: function (data) {
            if (data.isLoggedIn) {
                setTimeout(refreshPage, 100);


Sending text file to client through Spring MVC web application

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

html form action not working when using eclipse

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

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

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

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

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

How to use button instead input, style input?

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

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

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

MySQLSyntaxErrorException in SQL syntax

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 trigger a doGet before displaying a jsp page

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

Login page filter problems

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

JAX-RS @FormParam one time for all methods

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

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

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

Servlet to jsp on button click - whats the error?

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

EJB injection not working in different classes

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

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

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

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

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

Initialize class with constructor in

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

Java Servlet - get parameters with same name

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 exclude one textbox from the others that are using isNumeric validation with jQuery?

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

Persistence.xml overridden in Arquillian tests

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

Show and hide select input which is created dynamically

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

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

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

JSP form sending data including files in servlet

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

filter mapping to last path segment

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

JSP - issue with custom Taglib

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

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

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

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

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

Set default value for struts 2 autocompleter

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

@InterceptorBinding / CDI/ EJB 3.2 - problems with injection

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({...

How to open a new page when button is clicked on

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

Print and println aren't executed in the same time

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

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

I cannot instantiate my bean using @Inject and Vaadin CDI

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

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

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

Vector : References to generic type Vector should be parameterized

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

Wildfly Kafka clients module javax/management/JMException not found

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-"/> <resource-root path="lz4-1.2.0.jar"/> <resource-root path="snappy-java-"/> </resources> <dependencies> <module name="org.slf4j"/> </dependencies> </module> Wildfly (8.2.0-Final) gives this error on boot:...

Why paging query does not work

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

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

/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 call MySQL view in Struts2 or Hibernate

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

Error while including jsp with angular inside non angular 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...

Radio button group name

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

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

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

Form submit portlet with Spring MVC

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

How to get current jsp file path in war?

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

How to access application data in a session .jsp file

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 compile and run a JSP Beans project using Eclipse

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

Java Struts2 (Action class not found)

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

Hibernate criteria accepting %% value

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

Jsp list output [email protected]?

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

Can't insert or update record to database jsp

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