Session in the servlet

Hi!
A Netbeans web application use some servlets, not jsp, and tomcat, and postgre sql.
The big problem is executing some querry after the jdbc connection was closed, or can't open a new jdbc connection because too many are open, for example. And the session in some situations lost who is the logined user :) This was the application probem. If you have any idea to solve tham please anounce me.
My problem is I don't know how to check if the session is valid or not in the folowing function:
protected void processRequest(HttpServletRequest request, HttpServletResponse response){
request.getSession();
// how to check that session???
}

Thank's, how to do that? Where to find some samples, tutorial?

Similar Messages

  • Retrieve a session outside the servlet/JSP

    Hi,
    I know that we usually use the following code to retrieve the session:
    HttpSession session = request.getSession();
    but what if we don't have the request.
    In my case I want to access the session to save some information before going to my tierP (JSPs + Action beans, ...) to be able to retrieve them after.
    Is the only way to do so would be to pass the session in param to my TierB ?
    Thanks for your help!

    I guess I also have to mention that I don't have access to a database... our databases are on our old mainframe (Cobol), then we are only connecting to the mainframe to get all the info we need, but once on the Java side I need to keep some information in my TierB if possible.
    For more details, I receive 1-9 questions from the mainframe everytime I link to it, but I don't want the TierP to deal with all those questions, then I would like to save them in the session in the TierB and always pass only 1 question to the TierP. When I get back to the TierB, I have to check if there are questions left, if not, link back to the Cobol side, if so, just pass the next question.
    This is a very small summary, but I think that you should have the main idea.
    Thanks again!

  • Maintain session when calling servlet from form in a JSP

    I have the following set up:
    index.jsp calls login servlet from the action tag in a form.
    Login servlet handles the login, stores the user info and db connection in the session and uses forward(req,res) to call another jsp.
    That jsp has a form where user enters search info and in that form's action tag there is a search servlet. In the search servlet I am unable to access the session.
    Is there any way to pass the session to the servlet from that jsp using a form/action?

    I've read elsewhere that if you go from a jsp to a servlet that the >request object is cleared of any attributes from the previous request.which is correct. But arent we speaking about session object here? A request object is valid for a request - ie the phase from where the server receieves a hit for a resource upto the point it sends the output for that request.
    A session spans multiple requests.
    it doesn't retrieve the session info and gives me a null pointer >exception when I try to use the connection object stored in the session.Bad bad bad . Why do you store Connection objects in session? Create them when necessary or use a connection pool. Do you for example clean up the connections when the session expires. What if its a 30 minute session and the user hits every say 15 minutes with a request. Why do you need to hold on to the Connection in the intervening interval when the user's session is inactive?
    gives me a null pointer exception when I try to use the connection object stored in the session.which means that the Connection object is null - not the session object.
    That last line is where I get the null pointer exception. And that is
    Statement stmt = con.createStatement();?
    Same answer as above.
    If the session object was null,
    userSession.getAttribute("connection");would have thrown a NPE.
    ram.

  • Configuration of sessions for deployed servlet, jsp, wdp

    Hello,
    I wonder how to configure session for a specific servlet. As there are several locations where to deal with session management.
    I have found the Security Provider->SessionExpirationPeriod property which is fixed to ~27 hours, this is a general parameter for all security providers.
    I need to do it per application, I have then tried to set the session in the servlet descriptor it is not taken into account.
         <session-config>
              <session-timeout>10000</session-timeout>
         </session-config>
    The security provider of the servlet is set to SAML authentication.
    Thanks for your input on this topic,
    Tanguy Mezzano

    Finally, it was that parameter.

  • Session Rules from Servlet to JSP

    I'm getting a null pointer exception from the else statement in the JSP below when I check to see if a user has been authenticated by a servlet.
    Are there any problems with the else statement to cause an exception?
    <% /**Verify Authenticationt*/
    HttpSession mysession = request.getSession();
    String loginUrl = "/hr/servlet/SessionLoginServlet";
    if (mysession==null)
    response.sendRedirect(loginUrl);
    else {  //below code causing null pointer exception
    String loggedIn = (String) mysession.getAttribute("loggedIn");
    if (!loggedIn.equals("true"))
    response.sendRedirect(loginUrl);
    %>
    The Servlet's doPost:
    public void doPost(HttpServletRequest request, HttpServletResponse
    response)throws ServletException, IOException {
    String userName = request.getParameter("userName");
    String password = request.getParameter("password");
    if (login(userName, password, response)) {
    //send cookie to the browser
    HttpSession session = request.getSession(true);
    session.setAttribute("loggedIn", new String("true"));
    response.sendRedirect("/hr/jsp/PAStart.jsp");
    else {
    sendLoginForm(response, true);
    }

    Unfortunately, no. You'll need to say:
    if (loggedIn != null || !loggedIn.equals("true"))
    It's how the equals() works for String objects. You need two objects to check equality.

  • How do I lookup an EJB 3.0 Session bean from servlet or JSP?

    Does anyone knows how can I invoke an EJB from a servlet or JSP ?
    I deployed a simple EJB on a Oracle Application Server 10g release 10.1.3 and I'm working with JDeveloper 10.1.3. I deployed the files via JDeveloper, and I didn´t specify any orion-ejb-jar.xml or ejb-jar.xml file
    After deployment, the orion-ejb-jar.xml look like this in the server:
    <?xml version="1.0" encoding="utf-8"?>
    <orion-ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/orion-ejb-jar-10_0.xsd" deployment-version="10.1.3.0.0" deployment-time="10b49516c8f" schema-major-version="10" schema-minor-version="0" >
    <enterprise-beans>
    <session-deployment name="HolaMundoEJB" location="HolaMundoEJB" local-location="HolaMundoEJB_HolaMundoEJBLocal" local-wrapper-name="HolaMundoEJBLocal_StatelessSessionBeanWrapper6" remote-wrapper-name="HolaMundoEJB_StatelessSessionBeanWrapper7" persistence-filename="HolaMundoEJB.home_default_group_1">
    </session-deployment>
    </enterprise-beans>
    <assembly-descriptor>
    <default-method-access>
    <security-role-mapping name="<default-ejb-caller-role>" impliesAll="true" />
    </default-method-access>
    </assembly-descriptor>
    </orion-ejb-jar>
    I'm trying to invoke the ejb in a servlet by doing the following:
    public void doGet(HttpServletRequest request, ....
    Context context = new InitialContext();
    HolaMundoEJB helloWorld =
    (HolaMundoEJB)context.lookup("java:com/env/ejb/HolaMundoEJB");
    String respuesta = helloWorld.sayHello("David");
    When i invoke the servlet I catch a NamingException whose message says something
    like this ....java:com/env/ejb/HolaMundoEJB not found in webLlamaEJB
    I tried different paths for the lookup but nothing....
    Can anyone help me with this topic? Thank you.

    Please try the following code:
    HelloEJBBean.java:
    @Stateless(name="Hello")
    @Remote(value={Hello.class})
    public class HelloEJBBean implements Hello {  ... }
    hello.jsp:
    Context ctx = new InitialContext();
    Hello h = (Hello)ctx.lookup("ejb/Hello");
    web.xml:
    <ejb-ref>
    <ejb-ref-name>ejb/Hello</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <remote>fi.kronodoc.test.model.Hello</remote>
    </ejb-ref>
    i think you should also define jndi mappings for the references in orion-ejb-jar.xml and orion-web.xml but for some reason it seems to be working also without these.

  • Add or remove elements from a list attached to session duplicated the size

    Hi All,
    I have a jsp page that in there I'd like to show three columns in a table:
         <c:forEach var="thesaurus" items="${sessionScope.collection.thesaurusList}">
           <tr>
                        <td class="check"><input type="checkbox" name="word" value="${thesaurus.key}" ></td>
                        <td><c:out value="${thesaurus.key}"></c:out></td>
                        <td>${ts:getThesuaursRelationDescription(thesaurus.relation)}</td>
                        <td>${ts:getThesaurusSynonymsDescription(thesaurus.synonymsList)}</td>
              </tr>
           </c:forEach>thesuaurList is an ArrayList that holds object of type Thesaurus class ( a simple java bean). collection object is attached to session via a servlet.
    ts are tag that i have defined in my tag library.getThesuaursRelationDescription and getThesaurusSynonymsDescription are two static method and there's no problem with any of these classes.
    It all works ok but when I refresh the page, the list size gets duplicated each time and i can't see why? why items are added again to my list? Is that because i have collection object as an session attribute?
    If i replace the above code with jsp scriptlet it works fine:
    <%
                    Collection collection = (Collection) session.getAttribute("collection");
                    List< Thesaurus> thesauruses= collection.getThesaursList();
                    int i = 0;
                    for (Thesaurus thesaurus: thesauruses)
                    %>
                     <tr>
                        <td class="check"><input type="checkbox" name="word" value=<%=thesaurus.getKey()  %> ></td>
                        <td><%=thesaurus.getKey()%></td>
                        <td><%=ThesaurusUtil.getThesuaursRelationDescription(thesaurus.getRelation())%></td>
                        <td><%=ThesaurusUtil.getThesaurusSynonymsDescription(thesaurus.getSynonymsList())%></td>
                    </tr>
                    <%
                    %>Thanks in advance.

    Gr8 not a problem why do you use a composite view pattern.
    --->In that case make use of Proper patterns in your design before forwading it to a view.
    ---->Use a Public JSP Statically include JSP's in WEB-INF folder using static page include which happens at compile time.
    REGARDS,
    RaHuL

  • Cannot create a session after the response has been committed (Tomcat 6)

    I'm getting a rather annoying error when I try to open a pretty basic JSP page.
    I'm rather new to the whole JSP scene, so I'm following the example found on pages 287 and onwards in "JSF in Action - Manning" in case anyone wanted to check my code against the source.
    I've searched for about 4 hours now, coming back to this site a couple of times, once reading about writeouts and stuff. But I'm not really sure this is the issue in this case and if it is, where exactly the problem lies.
    I've already fixed a number of errors I got (jtsl.jar and standard.jar missing etc...) but this particular problem is driving me (and my co-workers for that matter :-) ) up the wall.
    Anyone willing to help me out here?
    Error:
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: Cannot create a session after the response has been committed
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:152)
    root cause
    java.lang.IllegalStateException: Cannot create a session after the response has been committed
         org.apache.catalina.connector.Request.doGetSession(Request.java:2301)
         org.apache.catalina.connector.Request.getSession(Request.java:2075)
         org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:833)
         org.apache.myfaces.context.servlet.SessionMap.setAttribute(SessionMap.java:53)
         org.apache.myfaces.util.AbstractAttributeMap.put(AbstractAttributeMap.java:103)
         org.apache.myfaces.util.AbstractAttributeMap.put(AbstractAttributeMap.java:35)
         org.apache.myfaces.application.jsp.JspStateManagerImpl.saveSerializedViewInServletSession(JspStateManagerImpl.java:523)
         org.apache.myfaces.application.jsp.JspStateManagerImpl.saveSerializedView(JspStateManagerImpl.java:358)
         javax.faces.application.StateManager.saveView(StateManager.java:47)
         org.apache.myfaces.application.jsp.JspViewHandlerImpl$StateMarkerAwareWriter.flushToWriter(JspViewHandlerImpl.java:387)
         org.apache.myfaces.application.jsp.JspViewHandlerImpl.renderView(JspViewHandlerImpl.java:322)
         org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:41)
         org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:132)
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:138)
    Source Code of login.jsp:
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
    <f:view>
    <html>
    <head>
         <title>
              <h:outputText value="ProjectTrack"/>
         </title>
    </head>
         <body>
              <table>
                   <tr>
                        <td>
                             <h:graphicImage url="/images/logo Skillteam.jpg"
                             alt="Welcome to ProjectTrack"
                             title="Welcome to ProjectTrack"
                             width="435" height="120"/>
                        </td>
                   <td>
                        <font face="Arial, sans-serif"
                        size="6">
                        <h:outputText value="ProjectTrack"/>
                        </font>
                   </td>
                   </tr>
         http://forum.java.sun.com/post!default.jspa?forumID=45#
    Click for bold     </table>
         </body>
    </html>
    </f:view>
    web.xml & faces-config
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
         <display-name>ProjectTrack</display-name>
         <welcome-file-list>
         <welcome-file>faces/login.jsp</welcome-file>
         <welcome-file>index.html</welcome-file>
         </welcome-file-list>
         <servlet>
         <servlet-name>Faces Servlet</servlet-name>
         <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
         <load-on-startup>1</load-on-startup>
         </servlet>
         <servlet-mapping>
         <servlet-name>Faces Servlet</servlet-name>
         <url-pattern>/faces/*</url-pattern>
         </servlet-mapping>
    </web-app>
    <?xml version="1.0"?>
    <!DOCTYPE faces-config PUBLIC
    "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
    "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
    <faces-config>
         <navigation-rule>
              <from-view-id>/login.jsp</from-view-id>
              <navigation-case>
                   <from-outcome>success</from-outcome>
                   <to-view-id>/inbox.jsp</to-view-id>
              </navigation-case>
              <navigation-case>
                   <from-outcome>failure</from-outcome>
                   <to-view-id>/login.jsp</to-view-id>
              </navigation-case>
         </navigation-rule>
    </faces-config>Setup:
    Eclipse Europe 3.3.0
    Tomcat 6.0.13
    MyFaces 1.2
    JRE 1.6.0_02

    When searching for this error, this was the first page google gave me. I found the answer and just in case anyone else stumbles in here with the same question I thought I'd share my findings.
    Unfortunately, if your problem is the same as mine, you're going to feel pretty silly. I was navigating to the wrong page. If MyFaces(when running tomcat) tries to resolve to a page that doesn't exist, the error given above is what happens.
    In my case I accidentally put my .jsp page into the wrong directory and ended up banging my head against the wall for an hour figuring that out. Hope this helps someone.

  • Session management in servlet

    Hi,
    I am using OC4J Server.
    I know the session in servlet can be managed with cookies. In addition, the session can be managed in HTTP session of OC4J. And How about the URL rewriting? Does it mean there are 3 methods to keep track of the servlet session. What are the difference of them. I am quite confused.
    Thanks in advance

    I see. Thanks.
    So it means there are two kinds of cookies, permanent cookies and session cookies.
    session cookies are used to store the session information.
    I have another question. I want to write a permanent cookies to the browser and get it again even if the browser is closed.
    The source code is like:
    Cookie cookie = new Cookie(cookieName, cookieValue);
    response.addCookie(cookie);
    Then I try to write some cookies in the browser, close the browser and open the browser again and I try to retreive the cookies using the following codes but the cookies disappear.
    Cookie[] cookies = request.getCookies()
    if (cookies != null && cookies.length > 0) {
    for (int i = 0; i < cookies.length; i++) {
    Cookie cookie = cookies;
    Is this the correct way to store and retrieve permanent cookies?
    thanks in advance

  • Getting session information in servlet?

    In Apache SOAP, org.apache.soap.rpc.SOAPContext can be used as a parameter to get at session data in your servlet. The JDeveloper web services publishing wizard won't expose a method with this parameter, saying that the XML Schema mapping and/or serializer is not specified. Is there an OC4J equivalent to get at session information?

    Hi.
    Most definitely possible. A few months ago I coded something very similar - jsp
    form, submit to a servlet. I needed to get and set session info in both the
    servlet and jsp. The code was very basic (ie no tricks involved) and worked
    well. FWIW both my servlet and jsp were in the same webapp.
    Good luck,
    Michael
    PeterH wrote:
    Howdy.
    re meant something else
    That's what I'm trying to figure out. :>
    re what do I mean by...
    I have one jsp page, that has a an html form on it with elements that get
    passed to a servlet through a submit button on the form. I would like to be
    able to get information about the session from within the servlet. Is that
    possible?
    Let me know if I'm not explaining myself properly and you need more info.
    I'm relatively new to this stuff. But I'm learning! :>>>>
    Thanks for your reply.
    <[email protected]> wrote in message news:[email protected]..
    Hrm. Whoever told you this probably meant something else. What do you mean
    by a 'servlet being called from a jsp' ?
    PeterH <!REMOVEBeforeSending![email protected]> wrote:
    I was told today when using a servlet within a web app (being called
    from a
    jsp), you do not have access to the session object. Is that true?Short of
    passing session attributes via the servlet call, how can you access the
    session information?
    Thanks for any ideas.--
    Dimitri
    Michael Young
    Developer Relations Engineer
    BEA Support

  • Best Practice: Keeping business logic out of the servlet

    In servlet programming, is it considered best practice keep business logic in the helper classes and only have session-related logic in the servlet?

    Yes, it is best to keep your business logic separate from your servlet class, to prevent coupling between your servlet and business logic. Consider using EJB's or the DAO pattern for your business logic.

  • How can I distinguish between applets from the servlet end??

    What I'm looking for is just a way to distiguish between one applet from another on the servlet side. I know the session name and id will be helpful in this case. I was wondering, can I get the name of the client applet(Ex: appletClientOne or appletClientTwo) so that I can keep track of which messages to send to specific applet.

    Yes. Store the name of the applet in a cookie or HTML hidden input tag. Your other option is to connect to different URL's on your Servlet. Finally, you could use a combination of the above, and then set which applet a user is using in his/her HttpSession.
    - Saish

  • Implementing session handling in servlet controller

    how to implementing session handling in servlet controller.
    instead of writing isNew() in every jsp page i wanted to write in my central controller ,where each request is passing through controller. can any body give me the solution

    i tried it it is failed because first time the request is coming to the controller.it checks for new since of it is a first request it is forwarded to the login page.how to avoid or skip the condition checking when the request is first time.

  • Maintaining Sessions through Multiple Servlets and Contexts

    Hi,
    I have a webapplication that works like this:
    * User connects to a login servlet on HTTPS
    * Users information is authenticated on HTTPS
    * An object is stored in the session for other servlets to validate the users access
    * Authenticated users are forwarded to an HTTP page where the session is used to make sure they were granted access
    My problem is this....Since I create the session in an HTTPS context, when I am in the HTTP context, I am unable to access the session and constantly get NULL. Is there any way that I can access the session from an HTTP context?

    What you can do is, just login using HTTPS and switch over to HTTP
    and then store data in session.That is true, but what I want in the session is basically a flag on whether or not the user was granted access. I would much rather set all that up on the secure line, and then just access it from the unsecure ones...
    For example, you are creating session using the
    http://testdev:port/index.jsp page.
    If access the same page(with hostname)
    http://10.300.20.18:8080/index.jsp, you can't get the session even
    though both are same web server and same web application. Because the
    browser treats it different sessionI think if you use my above solution with the explicit passing of the jsessionid, you can move from one domain to another and still maintain session. Not positive on that though...

  • Help: access right session context in servlet

    Hello,
    I've an master detail table in an adf app working fine. I've a servlet accessing the View of the detail Table woking fine (getBindingContext, ApplicationModule, findViewObject, and going thru the details Table wit a RowSetIterator).
    BUT if i change the "detail" in the details View in the faces app, the servlet still get's only the first "detail" of the detail table. It looks like the servlet is on a different instance of the ViewObject although in the same browser session.
    Do I have somehow to "tell" the servlet which "session" to use??
    Ognian

    Hello,
    Jdev is 11.1.1.2
    ADF Business Components     11.1.1.55.36
    Java(TM) Platform     1.6.0_14
    Oracle IDE     11.1.1.2.36.55.36
    Versioning Support     11.1.1.2.36.55.36
    I have 2 tables MA and MAPO
    MA has a column name and contans 3 rows AA, BB, CC
    MAPO has 2 columns name and value and rows: AA 1, AA 2, BB 4 BB 5, CC 6, CC 7
    The ADF model has 2 Views MAView1 and MAPOView1.
    The ADF Faces UI has 2 Tables and when you select AA ind MA yiou see AA 1 and AA 2 in MAPO
    so far so good.
    Now I have a servlet GENO accesing MAPOView1
    BindingContext bc=DCUtil.getBindingContext(request);
    DCDataControl dc = bc.findDataControl("AppModuleDataControl"); //see DataBindings.cpx
    ApplicationModule am=(ApplicationModule)dc.getDataProvider();
    ViewObject vo = am.findViewObject("MAPOView1");
    RowSetIterator iter = vo.createRowSetIterator(null);
    while (iter.hasNext()) {
    Row r = iter.next();
    I've also added the servlet to the adfBindings Filter
    This servlet is called from within the same session where the ADF Faces Master Detail Tables are displayed.
    I would expect, that the result of the servlet is dependent from the selection in the MA Table, since it should be bound to the same instance of MAPOView1.
    if MA has BB selected MAPOView1 should return BB 4, and BB 5, both in the ADF Faces Table AND in the Servlet, but it does so only in the ADF Faces Table.
    The servlet allways returns the AA rows of MAPO, it looks like it is bound to another instance of MAPOView1.
    I hope this clearifies the problem...
    Ognian

Maybe you are looking for

  • Transfer a UDF textfield from bill of materials to a PO via FMS

    Dear community, I really do need your help: for one of our costumers we created a UDF within the lines of the bill of materials in order to fill in some information concerning the components of the product (actually the lines are filled with producti

  • SD/SDHC/SDXC/MMC/MS/MS Pro card-reader slot not showing up in windows explorer.

    I have a Lenovo IdeaCentre, purchased only four weeks ago.  It product family is IdeaCentre k410, machine type 10089.  Anyhow, the problem is: I inserted a microSD / microSDHC, both of which seem to fit into the slot fine, though neither registers un

  • PowerMac 9500 System 9.1 keeps becoming "corrupted"

    HELP!!! (anybody) I have a Powermac 9500/200 with a Sonnett G3 466 upgrade card, but this problem also occurs with the original 200 MHz Apple card as well. This machine has 256 MB of ram and two 4GB SCSI drives... otherwise it is all original. This 9

  • Troubles to open After Effects CC

    Hi Everybody, I have some troubles to open After Effects and also Premiere pro CC actually. this is the error message : ALERTE AFTER EFFECTS last report: <140735212468576> <GPUManager> <2> Sniffer Result code 3 Here are some informations about my com

  • Define tax procedure issue

    Dear SAP Gurus.,                        When we define tax procedure TAXINN in t.code OBQ3 three option is there ,manual, required, statistical these are three check box option is there, when i was tick the check box of statistical indicator after i