Transaction Mgmt. Code In Servlet Filter

Hi,
It it possible to write Transaction management code in the Servlet filter. I am confused on this isssue, as "Designing Enterprise Applications with the J2EETM Platform, Second Edition" under section "8.5 Web Tier Transaction Guidelines" says that you can not use transaction management code in the Servlet Filters. But if adventure builder sample has code which uses transaction management code inside the servlet filter named as "Transaction Filter".
Regards,
Manish

Hi,
The paragraph you quote just implies that it is not guaranteed to work under the 'standard' J2EE servers like your everyday appserver. This is because the specs just don't require it. But different products may have different ideas;-)
Best,
Guy
http://www.atomikos.com

Similar Messages

  • Is a Servlet-Filter which serializes requests in the same user session ok?

    The Servelt specification states that the Web-Application is itself responsible for synchronizing access to HttpSessions. It is from the serversite not possible to prevent multiple threads to access the same HttpSession (i.e. the user could always open a second window, retransmit a form etc). My assumption is that while this does not happen often it can happen and therefore I think each access to the HttpSession must be synchronized. For a further discussion see http://forum.java.sun.com/thread.jsp?forum=4&thread=169872 .
    Concurrent programming is generally complicated and errorprone. At least in developing JSPs it is inconvenient and easy to forget. My Web-App uses often HttpSession and it can be used in different not predefined places, so I had the idea to implement a ServletFilter which serializes threads which happen in the same session. This involves certainly some overhead. However for the advantages of easier code maintains and higher consistency I am ready to pay this overhead.
    My question is generally what you think of this approach and second whether the way I implemented the Filter works.
    The Filter actually generates for each Request an HttpServletRequestWrapper which intercepts calls to getSession and on call aquires a Lock so that other threads have to wait for the same Session. The lock is released when the doFilter method of the Filter returns. So threads run concurrently until the first access to the Session and from there they are serialized until the end of the Request.
    For the details I will give the code for the Filter and the Wrapper (that?s all the code needed except the ReentrantLock which is Doug Lea?s implementation http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html )
    the Filter
    public class SessionThreadFilter implements Filter
      public static final String MUTEXT_IN_SESSION_KEY = "org.jaul.filter.SessionThreadFilter.MUTEX";
      //constructor, init, destroy methods do nothing
      public void doFilter(ServletRequest reqIn,ServletResponse res,FilterChain filterChain)
        throws IOException, ServletException
        //if req not instanceof of HttpRequest don't do anything
        if (!(reqIn instanceof HttpServletRequest))
          filterChain.doFilter(reqIn, res);
        } else
          HttpServletRequest req = (HttpServletRequest) reqIn;
          //We use a HttpRequestWrapper each time a user accesses
          //through this
          //Wrapper a Session is Lock is aquired. The filter method returns
          //the lock if it exists is released
          //each thread needs it's own wrapper so the wrapper itself
          //doesn't have to be synchronized
          SessionThreadRequestWrapper wrapper = new SessionThreadRequestWrapper(req);
          try{
            filterChain.doFilter(wrapper, res);
          }finally{
            ReentrantLock lock = wrapper.getLock();
            if (lock != null && lock.holds() != 0)
                       lock.release(lock.holds());
    the Wrapper
    final public class SessionThreadRequestWrapper extends HttpServletRequestWrapper {
      private ReentrantLock lock = null;
       * Constructor for SessionThreadRequestWrapper.
       * @param arg0
      public SessionThreadRequestWrapper(HttpServletRequest req){
        super(req);
       * @see javax.servlet.http.HttpServletRequest#getSession()
      public HttpSession getSession(){
        return getSession(true);
       * @see javax.servlet.http.HttpServletRequest#getSession(boolean)
      public HttpSession getSession(boolean construct){
        //this will get the session an the lock
        HttpSession session = getLockFromSession(construct);
        if (session == null) return null;
        //get a lock on the mutex
        try{
          lock.acquire();
        } catch (InterruptedException e){
          throw new IllegalStateException("Interrupted while thread waiting for session");
        //now we check again if the session is still valid
        try{
          session.getAttribute(SessionThreadFilter.MUTEXT_IN_SESSION_KEY);
        } catch (IllegalStateException e){
          //again we go recusively but first release the lock
          lock.release();
          lock = null;
          return getSession(construct);
        //after you got the lock you can return the session
        return session;
       * gets the lock from the session
       * @param construct
       * @return HttpSession
      private HttpSession getLockFromSession(boolean construct){
        //test if it is a new Session
        HttpSession session = super.getSession(construct);
        //if is null no session was realy requested
        if (session == null) return null;
        //otherwise try to get the lock if necessery construct it
        //syncrhonized over session
        synchronized (session){
          //this migth throw an Exception if the session has been
          //invalidated in the mean time
          try{
            lock = (ReentrantLock) session.getAttribute(SessionThreadFilter.MUTEXT_IN_SESSION_KEY);
            if (lock == null){
              lock = new ReentrantLock();
              session.setAttribute (SessionThreadFilter.MUTEXT_IN_SESSION_KEY, lock);
            return session;
          } catch (IllegalStateException e){
            //the session has been invalidated before we tried to get the
            //lock we recursively call getLockFromSession
            //( assumption checked with Jetty: if the session is invalidated
            //and getSession is called on the thread a new valid session
            // should is returend)
            //I hope sometime you should get a valid session but I am not
            //sure. This is crucial for breaking of the recursion
            lock = null;
            return this.getLockFromSession(construct);
      /** used by the Filter to get the lock so that it can release it
      ReentrantLock getLock(){
         return this.lock;
    }As stated I would be very thankful if you could check the code and give some commends.

    synchronized (session){Are you sure that the session instance returned by two
    concurrent calls to getSession(...) are the same? I
    think that tomcat for instance may return different
    instances for the same "logical " session, which would
    break your scheme I think... Thank you (I did not know that on Tomcat). The same thing could also occur if another filter wrapped the Session.
    That's indeed a problem,which I have already adressed in another thread, but did not get an answer. ( http://forum.java.sun.com/thread.jsp?forum=33&thread=412380). The already cited thread http://forum.java.sun.com/thread.jsp?forum=4&thread=169872 adresses the same problem, but the discussion there ends with the recomandation that you should synchronize on HttpSession as I did it. Also in other forums I've read so.
    However like you I've at least strong doubts in this approach, so now my question is on what should I than generally for any access in any web-app syncrhonize the access to Http-Session as demanded by the Servlet specs.
    A few not realy satisfying answers:
    Synchronize on the HttpSession itself: I think still the best approach, but as you say is it guaranteed that the same instance of an HttpSession is given to each Request (in one Session)?
    Synchronized on the HttpServlet: This only works if no other servlet (or jsp) accesses in the session the value with the same key ( of course only if the session itself is threadsave). In case of ThingleThread it is not possible at all there can be multiple instances (you could use a static variable)
    Holding the object to synchronize on in applicaton scope or session scope: This obiously doesn't help, because somehow you have to obtain the lock and at least there you need another synchronize.Holding in application socpe is slow a static variable lock would be better there.
    Synchronize on some static variable: This will work, but is very slow (each request not only in the same session would synchronize on this).
    Hold a map in application scope, which holds for each Session-key a lock: Is probably faster than the static variable thing. However the access and the management of the Map (removing of unused locks etc.- Mabe you could use a WeakHashMap to collect the locks for not used keys anymore) is time consuming too and again the map must be accessed syncrhonasly by all requests.
    Syncrhonize on the Filter (only in my case): This is as slow as the static variable approach because each request will use the same lock the one instance of the Filter.
    So synchronizing on the session is propably the best approach if the same attribute name is accesed by different servlets. However if you say that some Web-Containers return different HttpSession instances for the same Session (which is legal according to the specification) this of course does not work.
    So I have realy no clue on what to syncrhonize than. Now help is not only neede on my Thread serialization filter but on my generally Servlet prgromming.
    May be you could help me for another synchronization aproach.

  • Servlet Filter - Reading Request Error

    I have a servlet filter that sits in front of a webservice servlet (AXIS) - what I want the filter to do is to look at the content of the ServletRequest and if a particular string is located in the request, I want to call another service. Everything works just fine except (isin't there always an execept) that when I execute the following code in the filter:
    BufferedReader inReader = request.getReader();
    String line = null;
    StringBuffer sbuf = new StringBuffer();
    // Read the current request into a buffer
    while((line = inReader.readLine()) != null) {
    sbuf.append(line);
    sbuf.append("\n\r");
    if (sbuf.toString().indexOf("mystring") > -1) {
    // I do some code
    } else {
    chain.doFilter(request, wrapper);
    When I execute this code, at the chain.doFilter I get an "java.lang.IllegalStateException: getReader() has already been called for this request"
    I know that this is because I obtained the Reader from the request. But my question is - How can I look at the request string so that I can evaluate it and not have this exception thrown..
    Thx in advance...

    My guess is that when you do the chain.doFilter you pass the request to another resource that then tries to access the request.getInputStream method.
    From the JavaDocs:
    getReader
    public java.io.BufferedReader getReader()
    throws java.io.IOException
    Retrieves the body of the request as character data using a BufferedReader. The reader translates the character data according to the character encoding used on the body. Either this method or getInputStream() may be called to read the body, not both.
    Returns:
    a BufferedReader containing the body of the request
    Throws:
    java.io.UnsupportedEncodingException - if the character set encoding used is not supported and the text cannot be decoded
    IllegalStateException - if getInputStream() method has been called on this request
    java.io.IOException - if an input or output exception occurred

  • Inject EJB using @EJB in Servlet Filter on Weblogic 11g

    Hi All,
    I want to inject the EJB (Local interface) into the Servlet Filter and the EAR is deployed on Weblogic 11g.
    My question is:
    Shall the @EJB Annotation work on Weblogic 11g or it will be ignored in case of Servlet or Servlet Filter?
    OR
    I have to do look up as below and mention the references in web.xml and weblogic xml file:
    I know below code should be used when you have remote interface.
    Hashtable env = new Hashtable();
    env.put( Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory" );
    Context ctx = new InitialContext( env );
    ctx.lookup( "myejb" );
    Thanks

    Hi,
    It should work in 11g.
    Regards,
    Kal

  • Managed session bean in servlet filter

    Hi,
    Is there a way to get hold of a managed bean with session scope in a servlet filter? The code below throws an error due to the fact that the faces context is null.
    FacesContext facesContext = FacesContext.getCurrentInstance();
    System.out.println("facesContext: " + facesContext); // shows that facesContext is null
    ApplicationFactory appFactory = ApplicationFactory)FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
    Application app = appFactory.getApplication();
    Object obj = app.createValueBinding("user").getValue(facesContext); //throws the error due to the null parameter
    Object obj2 = app.createValueBinding("user"); //results in a valid ValueBindingHere is the faces-config snippet for the managed bean:
    <managed-bean>
        <managed-bean-name>user</managed-bean-name>
        <managed-bean-class>biz.libereco.skemo.info.asl.beans.User</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>For the record, I am using JSF 1.0 Final.
    Thank you,
    Marcel

    wynton_0 wrote:
    Yes, there is a way to get hold of a managed bean with session scope in a servlet filter.
    See here:
    [http://wiki.apache.org/myfaces/AccessFacesContextFromServlet]
    and here:
    [how to access faces context and backing beans in a servlet filter|http://www.thoughtsabout.net/blog/archives/000033.html]
    This makes no utter sense. A JSF session scoped managed bean is under the hood just put as a HttpSession attribute with the managed bean name as key. Guess what, you can just access the HttpSession in Filter by ((HttpServletRequest) request).getSession() and then just call getAttribute() on it. If it isn't there yet, then just do a setAttribute() with a new instance.
    After I get User bean in my Servlet filter, I populate value to this bean, for example:
    user.setLanguage(request.getParameter("locale"));
    The User bean is in session scope. The User bean's language attribute suppose to be same in the whole session scope, but later on, I got null. My question is:
    how to keep this value in session scope?The the session was apparently invalidated/renewed or you manually removed the bean or replaced it by null.
    In the future, please don't resurrect old topics, just start a new topic for each independent problem/question.

  • Providing redirects in Servlet filter

    Hi,
    I need to provide serverside redirects in Servlet filter.O tried the below code, But unable to do it.
    Is it possible to do such a thing.
    public void doFilter(ServletRequest req, ServletResponse res,
                   FilterChain chain) throws IOException, ServletException {
              logger.info("Start of RedirectFilter ");
              HttpServletRequest request = (HttpServletRequest) req;
              HttpServletResponse response = (HttpServletResponse) res;
              String requestURI=request.getRequestURI();
              String domainURL=request.getServerName().toLowerCase();
              logger.info("domainName--"+domainName);
              String keywordToBeAppended=domainURL.replaceAll(domainName,"");
              logger.info("url--"+request.getRequestURI());
              logger.info("servername--"+request.getServerName());
              logger.info("keywordToBeAppended-"+keywordToBeAppended);
              String finalURL= request.getScheme()+"://"+domainURL+"/"+keywordToBeAppended+requestURI;
              logger.info("finalURL--"+finalURL);
              RequestDispatcher rd = request.getRequestDispatcher(finalURL);
              rd.forward(request, response);
              logger.info("End of RedirectFilter ");
              chain.doFilter(request, response);
         }

    There is technically a huge difference between "redirect" and "forward". You're doing here forwards. And because you continue the filter chain, you run into problems. You should do either a forward OR continuing the current request unchanged (through the filter chain) OR send a redirect. You cannot do one or more simultaneously.

  • How to embed servlet filter to an existing website

    I want to make an application using java servlet filters and I want to know the possibility of making this application as an add-on where anyone could take this application as it is and attach it to his website without knowing anything about servletes and with a very low programming or no programming effort, is it possible? If yes how and if no what is the alternative?

    836522 wrote:
    I really cant thank everyone enough for your help, thank you :)
    why not proxy? because I don't want the full functionalities of a proxy, so I thought why not to implement a servlet filter to do my task especially that all what I want to do could be easily implemented using the methods provided in servlets/filters. what I am thinking of now is to install servlet container and make it run in the proxy mode so any request to the website I want to protect will be directed first to the servlet then the servlet decide whether to pass this request to website or not, what do you think of this??I am afraid that will either not work or be overly complicated. The problem is with this
    so any request to the website I want to protect will be directed first to the servlet then the servlet decide whether to pass this request to website or notHow will the servlet pass on the request to the web site? Since it is not part of the other application, it cannot do a forward or include on the resource. Similarly a chain.doFilter() which is the normal way for the Filter to pass the request along to the end resource will not work.
    You can theorotically use a HttpClient from the Filter which will create a new http request to the underlying web site and flush the response received back to the browser. I think using a Proxy is the best bet. I would recommend an apache http server with some custom modules to implement your 'filter' code
    ram.

  • Can java servlet filter capture anchors in URL

    Hi I need to capture the anchor in the URL that is requested by user. For example, if some one clicks http://www.abc.com/somepage.html#intro, I would like to capture all the info in the URL including "intro". Is it possible through the java servlet filter architecture? If so, what API should I use? Some sample code would be very helpful as well. Thanks!!

    No, this is not possible. Anchors are handled by the client (i.e. web browser). The server never sees them.

  • Weblogic.utils.NestedRuntimeException when using javax.servlet.Filter

    IDE: JDev 10gR3.4 & JDev 11gR2.3
    ViewController technology: JSF/ADF Faces
    Example code flow:
    Run page2.jsf
    MyFilter intercepts request, checks for parameter on session.
    If parameter not null, goto page2.jsf
    Else redirect to page1.jsf
    page1.jsf has a button that sets the value on the session scope after clicking.
    In jdev 11gR2.3, I get an weblogic.utils.NestedRuntimeException after clicking the button on page1.jsf. This error does not occur in jdev 10gR3.5. Although the application continues to execute and proper info is displayed, I’m wondering why this occurs and also if I should be concerned. Has anyone experienced a similar issue when using javax.servlet.Filter in 11g?
    MyFilter code snipet:
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
            try {
                HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
                HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
                String redirect = httpRequest.getContextPath() + "/faces/page1.jsf"; //only difference here is 11g uses jsf, 10g uses jsp.
                String uri = httpRequest.getRequestURI().toString();
                Boolean mySessionAttribute = (Boolean)httpRequest.getSession().getAttribute("MYSESSIONATTRIBUTE");
                if (uri.endsWith(redirect) || mySessionAttribute != null) {
                    filterChain.doFilter(servletRequest, servletResponse);
                } else {
                    httpResponse.sendRedirect(redirect);
                    return;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServletException e) {
                e.printStackTrace();
    page1.jsf/jsp
    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <f:view xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html">
        <h:form id="f1">
            <h:commandButton value="Submit" id="cb1" action="#{Page1Bean.clicked}" type="submit"/>
        </h:form>
    </f:view>page2.jsf/jsp
    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <f:view xmlns:f="http://java.sun.com/jsf/core" xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
        <af:document title="main.jsf" id="d1">
            <af:form id="f1">
                <af:outputText value="This is the main content" id="ot1"/>
            </af:form>
        </af:document>
    </f:view>Page1Bean.java
    public class Page1Bean {
        public void clicked() {       
            FacesContext context = FacesContext.getCurrentInstance();
            ExternalContext externalContext = context.getExternalContext();
            externalContext.getSessionMap().put("MYSESSIONATTRIBUTE", Boolean.TRUE);
            try {
                externalContext.redirect("/11gFilterExample-ViewController-context-root/faces/page2.jsf");
            } catch (IOException e) {
                    e.printStackTrace();
    }Full exception
    weblogic.utils.NestedRuntimeException: Cannot parse POST parameters of request: '/11gFilterExample-ViewController-context-root/faces/page1.jsf'
         at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.mergePostParams(ServletRequestImpl.java:2144)
         at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.parseQueryParams(ServletRequestImpl.java:2024)
         at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.getQueryParams(ServletRequestImpl.java:1918)
         at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.getParameter(ServletRequestImpl.java:1995)
         at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.access$800(ServletRequestImpl.java:1817)
         at weblogic.servlet.internal.ServletRequestImpl.getParameter(ServletRequestImpl.java:804)
         at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:169)
         at org.apache.myfaces.trinidadinternal.context.external.ServletRequestParameterMap.getAttribute(ServletRequestParameterMap.java:43)
         at org.apache.myfaces.trinidadinternal.context.external.ServletRequestParameterMap.getAttribute(ServletRequestParameterMap.java:31)
         at org.apache.myfaces.trinidadinternal.context.external.AbstractAttributeMap.get(AbstractAttributeMap.java:73)
         at oracle.adfinternal.controller.state.ControllerState.getRootViewPortFromRequest(ControllerState.java:788)
         at oracle.adfinternal.controller.state.AdfcContext.initialize(AdfcContext.java:185)
         at oracle.adfinternal.controller.state.AdfcContext.initialize(AdfcContext.java:79)
         at oracle.adfinternal.controller.application.AdfcConfigurator.beginRequest(AdfcConfigurator.java:53)
         at org.apache.myfaces.trinidadinternal.config.GlobalConfiguratorImpl._startConfiguratorServiceRequest(GlobalConfiguratorImpl.java:562)
         at org.apache.myfaces.trinidadinternal.config.GlobalConfiguratorImpl.beginRequest(GlobalConfiguratorImpl.java:212)
         at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:174)
         at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:119)
         at java.security.AccessController.doPrivileged(Native Method)
         at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:315)
         at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:442)
         at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:103)
         at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:171)
         at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:139)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
         at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
         at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
         at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
         at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
         at weblogic.work.ExecuteThread.run(ExecuteThread.java:178)
    Caused by: java.net.SocketException: Connection reset
         at java.net.SocketInputStream.read(SocketInputStream.java:168)
         at weblogic.servlet.internal.PostInputStream.read(PostInputStream.java:177)
         at weblogic.servlet.internal.ServletInputStreamImpl.read(ServletInputStreamImpl.java:228)
         at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.mergePostParams(ServletRequestImpl.java:2118)
         ... 39 more
    <UIXEditableValue> <_isBeanValidationAvailable> A Bean Validation provider is not present, therefore bean validation is disabled

    I dont believe that solution pertains to my case. clicked() is invoked from standard jsf page and the adf controller is not acquired yet. i put a couple of print statements in the filter and it seems that the doFilter is called twice! This is not the case when running in 10g.
                if (uri.endsWith(redirect) || mySessionAttribute != null) {
                    System.out.println("URI dofilter: "+uri);
                    filterChain.doFilter(servletRequest, servletResponse);
                } else {
                    System.out.println("URI sendRedirect: "+uri);
                    httpResponse.sendRedirect(redirect);              
                }11g weblogic console log:
    URI sendRedirect: /11gFilterExample-ViewController-context-root/faces/page2
    URI dofilter: /11gFilterExample-ViewController-context-root/faces/page1.jsf
    URI dofilter: /11gFilterExample-ViewController-context-root/faces/page1.jsf
    10g oc4j console log:
    13/01/07 15:48:13 URI sendRedirect: /10gFilterExample-ViewController-context-root/faces/page2.jsp
    13/01/07 15:48:13 URI dofilter: /10gFilterExample-ViewController-context-root/faces/page1.jsp
    I believe whatever thats causing this occur could be why the exception is thrown...

  • Weblogic 7.0 and 6.1 javax.servlet.filter implementation

              Hi All,
              I was using weblogic 6.1 and as my organization wants to go for 7.0, we
              are in the process of evaluating 7.0 ver.
              WL6.1 javax.servlet.filter interface provides the methods doFilter(), setFilterConfig(),
              getFilterConfig(). We have an implementation for the Filter which also contains
              a private method init(FilterCongig filterConfig).
              In 7.0 javax.servlet.filter interface the methods are doFilter(), init(), destroy().
              Because of the obvious reason i have a private implementation of init(FilterConfig
              )in my code the build does not succeed. When i checked the java specifications
              from Sun site I found 1.3.1 and 1.4(beta) specs provide doFilter(), init() and
              destroy().
              Question is: Is weblogic 6.1, JDK 1.3.1 compliant, if so why there is not init()
              method in the filter interface??. (Otherwise its a bug)
              Because of this the porting has become a serious issue as in some cases we need
              to support both 6.1 and 7.0
              

    6.1 did not implement the final version of the Servlet 2.3 specification, that's
              why you see differences.
              http://edocs.bea.com/wls/docs61/notes/new.html#1064420
              Sanjeev <[email protected]> wrote:
              > Hi All,
              > I was using weblogic 6.1 and as my organization wants to go for 7.0, we
              > are in the process of evaluating 7.0 ver.
              > WL6.1 javax.servlet.filter interface provides the methods doFilter(), setFilterConfig(),
              > getFilterConfig(). We have an implementation for the Filter which also contains
              > a private method init(FilterCongig filterConfig).
              > In 7.0 javax.servlet.filter interface the methods are doFilter(), init(), destroy().
              > Because of the obvious reason i have a private implementation of init(FilterConfig
              > )in my code the build does not succeed. When i checked the java specifications
              > from Sun site I found 1.3.1 and 1.4(beta) specs provide doFilter(), init() and
              > destroy().
              > Question is: Is weblogic 6.1, JDK 1.3.1 compliant, if so why there is not init()
              > method in the filter interface??. (Otherwise its a bug)
              > Because of this the porting has become a serious issue as in some cases we need
              > to support both 6.1 and 7.0
              Dimitri
              

  • Strange behavior when using servlet filter with simple index.htm

    I am new to J2EE development so please tolerate my ignorance. I have a web application that starts with a simple index.htm file. I am using a servlet filter throughout the website to check for session timeout, redirecting the user to a session expiration page if the session has timed out. When I do something as simple as loading the index.htm page in the browser, the .css file and one image file that are associated, or referenced in the file are somehow corrupted and not being rendered. How do I get the filter to ignore css and image files??? Thank you!!
    The servlet filter:
    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class SessionTimeoutFilter implements Filter {
         String[] excludedPages = {"SessionExpired.jsp","index.htm","index.jsp"};
         String timeoutPage = "SessionExpired.jsp";
         public void destroy() {
         public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
              if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
                   HttpServletRequest httpServletRequest = (HttpServletRequest) request;
                   HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                   //httpServletResponse.setHeader("Cache-Control","no-cache");
                   //httpServletResponse.setHeader("Pragma","no-cache");
                   //httpServletResponse.setDateHeader ("Expires", 0);
                   String requestPath = httpServletRequest.getRequestURI();
                   boolean sessionInvalid = httpServletRequest.getSession().getAttribute("loginFlag") != "loggedIn";               
                   System.out.println(sessionInvalid);
                   boolean requestExcluded = false;
                   System.out.println(requestExcluded);
                   for (int i=0;i<excludedPages.length;i++){
                        if(requestPath.contains(excludedPages)){
                             requestExcluded = true;
                   if (sessionInvalid && !requestExcluded){
                        System.out.println("redirecting");
                        httpServletResponse.sendRedirect(timeoutPage);
              // pass the request along the filter chain
              chain.doFilter(request, response);
         public void init(FilterConfig arg0) throws ServletException {
              //System.out.println(arg0.getInitParameter("test-param"));
    The index.htm file (or the relevant portion)<HTML>
    <Head>
    <META http-equiv="Content-Style-Type" content="text/css">
    <LINK href="RTEStyleSheet.css" rel="stylesheet" type="text/css">
    <TITLE>Login</TITLE>
    </HEAD>
    <BODY>
    <FORM NAME="Login" METHOD="POST" ACTION="rte.ServletLDAP"><!-- Branding information -->
    <table width="100%" border="0" cellpadding="0" cellspacing="0">
         <tr>
              <td width="30%" align="left"><img src="images/top_logo_new2.gif">
              </td>
              <td width="37%" align="center"></td>
              <td width="33%" align="right"></td>
         </tr>
    </table>
    My web.xml entry for the filter:     <filter>
              <description>
              Checks for a session timeout on each user request, redirects to logout if the session has expired.</description>
              <display-name>
              SessionTimeoutFilter</display-name>
              <filter-name>SessionTimeoutFilter</filter-name>
              <filter-class>SessionTimeoutFilter</filter-class>
              <init-param>
                   <param-name>test-param</param-name>
                   <param-value>this is a test parameter</param-value>
              </init-param>
         </filter>
         <filter-mapping>
              <filter-name>SessionTimeoutFilter</filter-name>
              <url-pattern>/*</url-pattern>
              <dispatcher>REQUEST</dispatcher>
              <dispatcher>FORWARD</dispatcher>
         </filter-mapping>

    Hi,
    Try adding CSS files and images to the excluded Pages.

  • Not able to access the native c code from servlet

    I want to call c function from servlet using JNI . I created the .so file and gave the library path . But when i try to load the library it says "Unsatisfied link error ". I am using tomcat on linux .. any more setting has to be done in order to call native code from servlets ?

    You need to post a little bit of code. What does your LoadLibrary() call look like?

  • Set Roles in servlet filter

    How can I set the user's role in the request object in a servlet filter
    so that in my action class, i can query the role using
    request.isUserInRole() and request.getUserPrinciple() methods.
    Any ideas...
    Thanks,

    How can I set the user's role in the request object
    in a servlet filter
    so that in my action class, i can query the role
    using
    request.isUserInRole() and request.getUserPrinciple()
    methods.You may want to check out JAAS in the Creator tutorial:
    http://developers.sun.com/prodtech/javatools/jscreator/ea/jsc2/reference/sampleapps/

  • Can I use OLAP variable in ABAP Code of infoobject filter

    I have 0FISCPER infoobject in filter section of info-package while loading data.
    Below OLAP varaibles has below dynamic values that are being calculated at run time.
    0P_PRFP2 -  (Current fiscal period - 2)   ex: 2010010
    0P_PRFP1 -  (Current fiscal period - 1)   ex: 2010011
    0FPER    -    (Current fiscal period )        ex: 2010012
    I want to write ABAP CODE FOR using filter values from 0P_PRFP2 to 0FPER. (Last 3 fiscal periods - ex: 2010010 to 2010012).
    how to  use above standard OLAP variables in ABAP CODE to assign l_t_range (low or  high).

    try this using ABAP routine option (6)
    DATA: curryear(4)           type N,
                 currperiod(2)         type N,
                 prevper1(2)           type N,
                 prevyear1(4)         type N,
                 prevper2(2)           type N,
                 prevyear2(4)         type N,
                 prevfiscperYr1(7)   type N,
                 prevfiscperYr2(7)   type N,
                 prevfiscper1(3)      type N,
                 prevfiscper2(3)      type N,
                 w_length1              type i,
                 w_length2              type i.
      curryear = SY-DATUM+0(4).
      currperiod = SY-DATUM+4(2).
      If currperiod EQ '01'.
        prevyear1 = curryear - 1.
        prevper1   =  '12'.
        prevyear2 = curryear - 1.
        prevper2   = '11'.
      elseif currperiod EQ '02'.
        prevyear1 = curryear.
        prevper1   = '01'.
        prevyear2 = curryear - 1.
        prevper2   = '12'.
      else.
        prevyear1 = curryear.
        prevper1   =   currperiod - 1.
        prevyear2 = curryear.
        prevper2   = currperiod - 2.
      endif.
      w_length1 = STRLEN( prevper1 ).
      If w_length1 = 1.
        concatenate '0' prevper1 into prevper1.
      Endif.
      w_length2 = STRLEN( prevper1 ).
      If w_length2 = 1.
        concatenate '0' prevper2 into prevper2.
      Endif.
      concatenate '0' prevper1 into prevfiscper1.
      concatenate '0' prevper2 into prevfiscper2.
      concatenate prevyear1 prevfiscper1 into prevfiscperYr1.
      concatenate prevyear2 prevfiscper2 into prevfiscperYr2.
      l_t_range-low = prevfiscperYr2.
      l_t_range-high = prevfiscperYr1.
    *  modify l_t_range index l_idx from l_t_range.
    l_t_range-sign   = 'I'.
    l_t_range-option = 'BT'.
    modify l_t_range index l_idx.

  • Avoiding html codes and javascript codes in servlets

    Are there ways to avoid long html codes using out.println() and also javascript codes in servlets? Can I make a jsp and include that file somehow in the servlet and do the processing. Can I get reference to the fields or components declared in the jsp and also do conditional flow based on the buttons present in that jsp.
    Is it possible to include javascript files and instead call that javascript file and also the particular function in that file?
    Please also mention disadvantages if any.

    Javascript is for the client ONLY. Even if you could find a way to use it on the server side, DON'T.
    In my opinion, you should have ZERO logic (except for validation via JavaScript) in your JSP. Have a Servlet do all logic/business rules. The Servlet will create one or more Java Beans that hold ALL dynamic content for a page. Use the Servlets RequestDispatcher to forward the request to the JSP upon completion. The JSP should do nothing more than grab these beans (from the HttpSession object) and fill in the dynamic parts of the page.
    By doing it this way, you seperate the logic and presentation. You can add different 'flavors' (WML, XML) by simplying creating a new JSP page that looks for the same Java Beans, but has different template text.

Maybe you are looking for

  • SUBMIT issue in background

    Hi experts,        I am submitting the other program which is using the LDB in my program. When i execute the program in foreground it is working properly. But when i execute the same program in background, the job is getting cancelled by giving the

  • I am beginning to hate my Mac

    Pllleeaasse help! Since loading SL and Office 2008 I have had no end of problems with this iMAC. It crashes. wont empty pen drives, and Word closes its self so often its driving me nutts. Now I am not particularly techy but I have tried to look for a

  • PC Suite and MS Virtual PC

    I have XP Pro SP2 running in a Virtual PC under Windows Vista Business. Applications on the XP virtual machine need to access the internet. I am using PC Suite ver 6.83.14.1 with CA 42 USB cable, cable driver 6.83.9.0 and PC Connectivity Solution 7.7

  • OS User SID ADM  profile not loading in Windows 2008

    Hi Experts , We have installed Netweaver 7.o EHp1 BI 7.01 on windows 2008, MS SQL 2008 . After few days, we are not able to login with the SIDADM user. The error getting is "User profile cannot be loaded" 'The LoadUserProfile call failed with the fol

  • Guest users issue??

    Hello, I am expieriencing a weird behavior in the WLAN for guest users. I can create tipical guest users and it redirects me to the sign in web page (there is no web auth server, it's done by the WLC itself) and it works normally. But I am having sev