If  else in JSP

I am trying to forward to different pages after checking some condition in JSP through if else but always the first page is called.
public boolean deviceType(){
          String flash = "flash";
          String img = "img";
          if(contentType.equals(flash)){
                    if(isFlash()){%>
                         <jsp:forward page="flashOK.jsp" />
                    <%!}else{%>
                         <jsp:forward page="flashNG.jsp" />
                    <%!}
               }else if(contentType.equals(img)){
                    if(isImg()){%>
                         <jsp:forward page="imgOK.jsp" />
                    <%!}else{%>
                         <jsp:forward page="imgNG.jsp" />
                    <%!}
               }%>
               <jsp:forward page="notSupported.jsp" />
               <%!return false;
     }

Thanks for your help I tried it that way but now the page coming is blank seems not forwarding to any page.
public boolean deviceType(){
          String flash = "flash";
          String img = "img";
          HttpServletRequest request = null;
          HttpServletResponse response = null;
          RequestDispatcher rd = request.getRequestDispatcher("");
       // rd.forward(request, response);
          if(contentType.equals(flash)){
                    if(isFlash()){
                              rd = request.getRequestDispatcher("flashOK.jsp");
                              try {
                                   rd.forward(request, response);
                              } catch (ServletException e) {
                                   e.printStackTrace();
                              } catch (IOException e) {
                                   e.printStackTrace();
                        }else{
                             rd = request.getRequestDispatcher("flashNG.jsp");
                             try {
                                   rd.forward(request, response);
                              } catch (ServletException e) {
                                   e.printStackTrace();
                              } catch (IOException e) {
                                   e.printStackTrace();
          }else if(contentType.equals(img)){
                    if(isImg()){
                         rd = request.getRequestDispatcher("imgOK.jsp");
                        try {
                              rd.forward(request, response);
                         } catch (ServletException e) {
                              e.printStackTrace();
                         } catch (IOException e) {
                              e.printStackTrace();
                    }else{
                         rd = request.getRequestDispatcher("imgNG.jsp");
                        try {
                              rd.forward(request, response);
                         } catch (ServletException e) {
                              e.printStackTrace();
                         } catch (IOException e) {
                              e.printStackTrace();
          }else{
                    rd = request.getRequestDispatcher("notSupported.jsp");
                   try {
                         rd.forward(request, response);
                    } catch (ServletException e) {
                         e.printStackTrace();
                    } catch (IOException e) {
                         e.printStackTrace();
                    return false;
          return false;
     }Want to ask one more things that how can I get a parameter from request and store it in a string.
I triedString contentType = request.getParameter("content");and by other ways also but failed.Thanks in advance.

Similar Messages

  • JSP/javascript question. Guru's please help.

    Need help.
    I know we can assign value of a JSP variable to a javascript variable. e.g. strJScriptvar = <%=strJSPvar%>;
    Is there a way we can go the other way, i.e. assigning a javascript variable value to a JSP variable?
    e.g. will it be valid <%strJSPvar=%>=strJScriptvar;
    If not, is there a direct way of assigning the value.
    Any help will be heavily appreciated.
    Thanks,
    Indrasish.

    Yeah, that's it. Remember that JSPs are compiled into servlets then sent as HTML to your browser. Once the page is sent to your browser, there is nothing else the "JSP" part of it can do. It's already been processed, done it's thing, and sent the results to your browser.
    Make sense?

  • JSP & MySQL

    Hi!
    I am Pranay. I want to connect my JSP with MySQL. Will you please help me? I want the detail-code and pre-coding instructions.....
    General Informations:
    1. JDK 1.5.0
    2. Apache Tomcat 4.1
    3. MySQL Server 5.0
    4. MySQL Connector/J 5.0.4
    5. JAVA_CLASSPATH
    C:\Program Files\Java\jdk1.5.0\bin
    6. CLASSPATH
    C:\Program Files\mysql-connector-java-5.0.4
    Plz consider that I have a table in my MySQL database name tab1 which has fields: name,roll,date_of_birth.
    Thanx...

    The error you are getting looks like a network (socket) error rather than a JDBC or MySQL problem. The error indicates that a connection cannot be negotiated from Tomcat to MySQL. Are you sure MySQL is running on your laptop? Try to telnet to the MySQL port:
    (on windows, from the command prompt)
    C:\>telnet localhost 3306
    If this connects (the command promt screen should clear) then the problem is elsewhere, but my bet is you won't be able to connect this way either.
    If you cannot connect using telnet:
    1. Verify that MySQL is running on your laptop
    2. Verify that it's listening on port 3306
    3. Check that you don't have any local firewall apps blocking this traffic
    4. Verify that you don't have any manual host configurations which mean "localhost" points somewhere else (unlikely)
    If you CAN connect using telnet:
    1. Verify that your connection string is correct as per the MySQL JDBC Driver documentation
    2. Verify that your authentication credentials are correct (don't think it's this)
    Now... for a few supplimentary notes:
    You appear to be using the connection.isClosed() method to test whether you have a connection. This serves no purpose in the context you are using it as it's just a boolean which gets set when close() is called on the connection. ergo you could quite easily have a broken connection which returns "false" on an isClosed() call.
    Also, it is (strictly speaking) considered a better architecture to limit your JSP code to "display logic" only. This means it is usually void of any business logic or database-related code. You should really look at something like the MVC architecture (model-view-controller). This will save you a lot of headaches in the long run. If nothing else, debugging JSPs can be a real nightmare. I recommend you look at the Struts project (Apache Jakarta). It has become the defacto standard implementation of MVC.
    Good luck :)

  • File download using jsp

    I am trying to download a file from the server using jsp but it always shows the file in the browser.I want a Save/Open dialog box to allow the user to save this file in the local system. any feedback is welcome.
    thanks in advance
    vinod

    Basically out frame work is in struts.........
    In struts for file down load I wrote the code as
    String fileName = <file name>;
    String filePath = <file path>;
    String fileType = fileName.substring(dotIndex+1,fileName.length());
    ServletOutputStream out = httpservletresponse.getOutputStream();
    if (fileType.trim().equalsIgnoreCase("doc"))
    httpservletresponse.setContentType( "application/msword" );
    else if (fileType.trim().equalsIgnoreCase("xls"))
    httpservletresponse.setContentType( "application/vnd.ms-excel" );
    else if (fileType.trim().equalsIgnoreCase("pdf"))
    httpservletresponse.setContentType( "application/pdf" );
    else if (fileType.trim().equalsIgnoreCase("ppt"))
    httpservletresponse.setContentType( "application/ppt" );
    else
    httpservletresponse.setContentType( "application/octet-stream" );
    httpservletresponse.setHeader("Content-disposition", "attachment; filename=" +actualName );
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
    BufferedOutputStream bos = new BufferedOutputStream(out);
    byte[] buff = new byte[2048];
    int bytesRead;
    while(-1 != (bytesRead = bis.read(buff, 0, buff.length)))
    bos.write(buff, 0, bytesRead);
    I hav written this in seperate function which returns boolean true If this works correctly otherwise fase.
    If it is 'true ' I am forwarding it to 'success.jsp' else'fail.jsp'....................
    Now problem is It is not forwarding to any other pages and giving error as "Illegal state .can not forward.Response already committed."
    I think this error is coming becos of 'response.setHeader()' and using out object.........
    Please give me any solution for this problem.........Since I am strucked here.It is urgent for me to do...................................
    I don't mind If u giv any alteernative code for this..............
    Thanx in advance..................
    Plz. respond quickly...................

  • Relatiive Path problem when using JSP:include in web portlet

    Hi
    I am using Oracle Portal 9.0.2, and thus OC4J as the J2EE platform.
    I have created a JSP web portlet that is supposed to inlude a specific static html file, which name is passed to it using a portlet parameter. It works, but I had to create a symbolic link from the applicable J2EE applications's htdocs directory in order to access the content:
    /j2ee/OC4J_Portal/applications/<application>/htdocs/<portlet>/content/
    where /content/ is a symbolic link to another directory altogether.
    I can then access the content from within the portlet with a JSP include tag that looks like :
    docPath = "/htdocs/<portlet>/html/"+doc_path;
    %>
    <br>Include:
    <jsp:include page="<%=docPath%>" flush="true"/>
    I would like to access the content using the JSP include without having to use the symbolic link. Is there a way to do this. I tried using an Apache alias, but that did not work.
    Regards
    Harry

    Hi
    Thanx
    In the end we build up a static URL to the document to be included using:
    String contentLocation="content/";
    docPath = contentLocation+getAdditionalDocPath();;
    out.println("docPath="+docPath);
    String docPathAndName = portletRequest.getParameter("doc_path");
    %>
    <!--
    This java script function calls the display content page with the
    page parameter doc_path (which is in return passes it to the display
    content portlet) in order to retrieve and display specific document
    with a JSP:include tag
    -->
    <script language="JavaScript">
    function generateSectionPath(docName) {
    this.location="http://<%=portletRequest.getServerName()%>:<%=portletRequest.getServerPort()%>/pls/portal/url/page/<%=getPageGroup()%>/content?doc_path="+"<%=docPath%>"+docName;
    <script language="JavaScript">
    function generateRelativePath(docName) {
    this.location="http://<%=portletRequest.getServerName()%>:<%=portletRequest.getServerPort()%>/pls/portal/url/page/<%=getPageGroup()%>/content?doc_path="+docName;
    </script>
    <br>Include:
    <%
    if (portletRequest.getParameter("doc_path") == null) {
    out.println("Error - no doc path specified");
    } else { 
    try { %>
    <jsp:include page="<%=docPathAndName%>" flush="true"/>
    <% } catch (Exception e) {
    out.println("Error retrieving document:"+e.toString());
    } // end if
    %>
    Each link from one included HTML file to another becomes a JS function that points the browser to the portal page that includes the portlet that includes thwe JSP that has the include tag to include the html document that is to be displayed.
    The current relative path the the html document (from a predefined root in the file system that is symbolically linked to the same directory as where the including JSP lives) is stored in a session variable, and appended to the document name that is passed to the page.
    If a full document path, as opposed to just the name, is stored, that no appending is done. However, the path is stripped out and stored in a session variable.
    Ths thing is, sometimes a document name, and sometimes a path is passed to the page. Therefore the requirement to know the path when it is not available. A name only will always be passed subsequent to a request for a document with the full path specified, therefore the session variable mechanism works.
    Thanx for the input
    Harry

  • Jsp (executing in one server not in other)

    hi,
    my jsp page is running in tomcat server but not in iplanet server, i am getting problem as below.can somebody help me. thanks in advance.
    There was some problem with the jsp as it was not running on the server. I kept on getting the error
    Server Error
    This server has encountered an internal error which prevents it from
    fulfilling the request. The most likely cause is a misconfiguration.
    In the log I could find this
    [30/Jun/2003:19:08:09] info ( 5253): JSP: JSP1x compiler threw exception
    org.apache.jasper.JasperException: Invalid jsp:include tag
    at java.lang.Throwable.fillInStackTrace(Native Method)
    at java.lang.Throwable.fillInStackTrace(Compiled Code)
    at java.lang.Throwable.<init>(Compiled Code)
    at java.lang.Exception.<init>(Compiled Code)
    at javax.servlet.ServletException.<init>(ServletException.java:68)
    at org.apache.jasper.JasperException.<init>(JasperException.java:73)
    at
    org.apache.jasper.compiler.IncludeGenerator.<init>(IncludeGenerator.java:95)
    at
    org.apache.jasper.compiler.JspParseEventListener.handleInclude(JspParseEventListener.java:879)
    at
    org.apache.jasper.compiler.DelegatingListener.handleInclude(Compiled Code)
    at org.apache.jasper.compiler.Parser$Include.accept(Compiled Code)
    at org.apache.jasper.compiler.Parser.parse(Compiled Code)
    at org.apache.jasper.compiler.Parser.parse(Compiled Code)
    at org.apache.jasper.compiler.Parser.parse(Compiled Code)
    at org.apache.jasper.compiler.Compiler.compile(Compiled Code)
    at com.netscape.server.http.servlet.NSServletEntity.load(Compiled
    Code)
    at com.netscape.server.http.servlet.NSServletEntity.update(Compiled
    Code)
    at com.netscape.server.http.servlet.NSServletRunner.Service(Compiled
    Code)
    [30/Jun/2003:19:08:09] warning ( 5253): Internal error: Failed to get
    GenericServlet.
    (uri=/crux/compute_300603.jsp,SCRIPT_NAME=/crux/compute_300603.jsp)
    my code is like this
    (compute_300603.jsp)
    <%@page contentType="text/html"%>
    <html>
    <head><title>JSP Page</title></head>
    <SCRIPT>
    </SCRIPT>
    <body >
    <%-- <jsp:useBean id="beanInstanceName" scope="session" class="package.class" /> --%>
    <%-- <jsp:getProperty name="beanInstanceName" property="propertyName" /> --%>
    <%boolean flag=true;%>
    <% if (request.getParameter("fno")==
    null && request.getParameter("sno")
    == null) { %>
    <CENTER>
    <jsp:include page='top.jsp' />
    <H2>Please enter two numbers</H2>
    <FORM METHOD="POST" ACTION="compute_300603.jsp">
    <table bgcolor='snow'>
    <P>
    Your First no: <input type="text" name=
    "fno" size=10>
    <P>
    Your Second no: <input type="text" name=
    "sno" size=10>
    <P>
    </TABLE>
    </FORM>
    </CENTER>
    <% } else { %>
    <CENTER><jsp:include page='top.jsp' /> </CENTER>
    <%! int fno, sno ,total; String opr;%>
    <%
    try{
    fno = Integer.parseInt(request.getParameter("fno"));
    sno= Integer.parseInt(request.getParameter("sno"));
    if(Integer.parseInt(request.getParameter("pro"))==1){
    opr="Addition";
    total= fno + sno;
    else if(Integer.parseInt(request.getParameter("pro"))==2){
    opr="Subtraction";
    total= fno - sno;
    else if(Integer.parseInt(request.getParameter("pro"))==3){
    opr="Multiplication";
    total= fno * sno;
    else if(Integer.parseInt(request.getParameter("pro"))==4){
    opr="Division";
    try{
    total= fno/sno;
    }catch(ArithmeticException e){flag=false;%>
    <center>
    <b> <%= "Invalid Data entered" %> </b> <br>
    <br> <b> Click here to reenter </b>
    </center>
    <%}
    }catch(NumberFormatException e) {
    System.out.println("NumberFormatException occured");
    flag=false;%>
    <center>
    <b> <%= "Invalid Data entered" %> </b> <br>
    <br> <b> Click here to reenter </b>
    </center>
    <%}%>
    <%if(flag){ %>
    <CENTER>
    <H2>Please enter two numbers</H2>
    <FORM>
    <table bgcolor='snow'>
    <P>
    Your First no: <input ="text" name=
    "fno" size=10 value="<%= fno %>">
    <P>
    Your Second no: <input type="text" name=
    "sno" size=10 value="<%= sno %>">
    <P>
    </TABLE>
    </FORM>
    </CENTER>
    <P>
    <B>You have provided the following info</B>:
    <P>
    <B>First</B>: <%= fno %><P>
    <B>Second</B>: <%= sno %><p>
    <B>Operation Done</B>: <%= opr %><p>
    <B>Your Total Is</B>:<%= total%>
    <% }} %>
    </body>
    </html>
    (top.jsp)
    <html>
    <head><title>JSP Page</title></head>
    <script>
    function formSubmitAdd(){
    document.topForm.submit();
    function formSubmitSub(){
    document.topForm.pro.value=2;
    document.topForm.submit();
    function formSubmitMulty(){
    document.topForm.pro.value=3;
    document.topForm.submit();
    function formSubmitDiv(){
    document.topForm.pro.value=4;
    document.topForm.submit();
    </script>
    <body>
    <FORM name='topForm' action='compute_300603.jsp'>
    <INPUT type=hidden name=pro value=1>
    <input type=BUTTON value=Add onclick=formSubmitAdd();>
    <input type=BUTTON value=Multiply onclick=formSubmitMulty();>
    <input type=BUTTON value=Substract onclick=formSubmitSub();>
    <INPUT type=BUTTON value=Divide onclick=formSubmitDiv();>
    <%-- <jsp:useBean id="beanInstanceName" scope="session" class="package.class" /> --%>
    <%-- <jsp:getProperty name="beanInstanceName" property="propertyName" /> --%>
    </body>
    </html>

    It seems that the server detected an error on the
    <jsp:include ..> tag.
    Try replacing <jsp:include page='top.jsp' /> by
    <jsp:include page="top.jsp" /> I have the same problem.. and this didnt work.. I also added flush="true". It works fine on tomcat but not on NES (netscape)
    Any suggestions..?
    Thanks..
    Kamala

  • Connection in jsp with a sas server?

    Hi i have a problem with connecting a jsp-application to a sas server.
    I have the following code used to make a connection.
    [begin code]
    [import the packages]
    <%@page errorPage="ErrorPageKBO.jsp" %>
    <%@page import="com.sas.rmi.Connection"%>
    <%@page import="com.sas.rmi.Rocf"%>
    <%@ page import="java.io.*,
    java.util.*,
    java.net.*,
                   javax.servlet.*,
                   java.sql.*,
                   java.util.Date,
    com.sas.collection.StringCollection,
    com.sas.servlet.beans.*,
    com.sas.servlet.beans.html.*,
    com.sas.servlet.util.*" %>
    [code used for connection]
    String Lang="";
    if (session.getAttribute("lang").equals("nl"))
         Lang="Dutch";
    if (session.getAttribute("lang").equals("fr"))
         Lang="French";
         Connection connection = new Connection();
         connection.setHost("Localhost");
         connection.setFunnel(true);
         connection.setFunnelHost("Localhost");
         connection.setProfileName("local1");
         connection.setUseProfile(true);
         Rocf rocf = new Rocf();
         // Begin code om de connectie en rocf objecten in de sessie te zetten.
         com.sas.servlet.util.BoundRocf br = new com.sas.servlet.util.BoundRocf(rocf);
         com.sas.servlet.util.BoundConnection bc = new com.sas.servlet.util.BoundConnection(connection);
         session.setAttribute("cleanupConnection", connection);
         session.setAttribute("cleanupRocf", rocf);
         session.setAttribute("cleanupBc", bc);
         session.setAttribute("cleanupBr", br);
         // Einde code om de connectie en rocf objecten in de sessie te zetten.
         session.setAttribute("rocfAttr",rocf);//nieuw
         com.sas.sasserver.submit.SubmitInterface si = (com.sas.sasserver.submit.SubmitInterface)
              rocf.newInstance(com.sas.sasserver.submit.SubmitInterface.class, connection);
         com.sas.servlet.util.SocketListener socket = new com.sas.servlet.util.SocketListener();
         String pgmText;
         if (request.getParameter("V")!=null)
              pgmText=
              "data _null_;"                                                                                     + "\n" +
              "     call symput(\'ond_nr\',PUT((INPUT(\'" + request.getParameter("V") + "\',HEX.)-TODAY()),Z10.));"               + "\n" +
              "run;";                                                                                     
         else
              pgmText =
              "%let ond_nr="+request.getParameter("ON")+request.getParameter("ON1")+request.getParameter("ON2")+";";
         pgmText=pgmText +
              "%let UpdForm=" + session.getAttribute("updateProfile") + ";" + "\n" +
              "%let lang=" + Lang + ";"                                                                                 + "\n" +
              "libname initieel 'd:/rawdata/ftproot/KBO/initieelprivate';"                                                   + "\n" +
              "filename sock SOCKET '" + (java.net.InetAddress.getLocalHost()).getHostAddress() + ":" + socket.setup()           + "';\n" +
              "%include \"d:/ecodata/nl/servlet/kbo_ps/sasprograms/private_onderneming_&lang..sas\";"                                        + "\n" +
              "%include 'd:/ecodata/nl/servlet/kbo_ps/sasprograms/private_onderneming.sas';";
         socket.start();
         si.setProgramText(pgmText);
         //out.write("<pre>" + pgmText + "</pre>");
         //out.write("<pre>" + si.getLastLogText() + "</pre>");
         pgmText=" ";
         socket.write(out);
         socket.close();
         rocf.stop();
         session.removeAttribute("rocfAttr");
    [end code]
    Now they say that to connect from a common server, where the jsp application is stored and executed, with the sas server named "sng3pubsearch". You just have to change "Localhost" into the name of the sas server!
    But i did that and could'nt connect with the sas server.
    I searched on the Internet and found out that you have to give as well the package name and the host.
    But i don't know just how to code that?
    Can anyone help me in this ?
    Thanks a lot!
    grts
    Wimvg

    Start by moving all this code out of the JSP and into a Servlet or something else. JSP's are for presentation and what you're doing is bad practice.
    That said, you should use code tags when you post code. You should post the error if you're getting one (preferably a stack trace as well). And honestly, you haven't posted enough info for me to help. Maybe someone else has more info.
    Try connecting with a standalone class first. Don't do this in a JSP unless you like headaches.

  • Registering the Web based application as a Partner Application

    Good day
    I went through the suggested documentation of registering a
    web based application as a partner application of the SSO Login Server.
    I installed the SSOSDK.JAR and went through the demo application (JSP Demo)
    which consists of the following programs :
    papp.jsp
    ssoinclude.jsp
    ssoEnablerJspBean
    SSOEnablerBean
    SSOSignon
    As per the technical documentation,I register this demo application as a
    partner application.
    1 - The source code of the papp.jsp checks for the existence of the user
    through method of ssoEnablerJspBean [getSSOUserInfo(request, response)] which
    calls method of SSOEnablerBean [getSSOUserInfo (request, response) and this
    method calls getUserInfo(p_request) of SSOEnablerBean (the same program) to
    check the existence of the application cookie.
    2 - If it doesn't exit , it redirect it to the SSO Login page for user
    authentication.Once the user is authenticated, a SSO login cookie is created on
    the client's browser and redirects back to the SSOSignOn.
    3 - The SSOSignOn program creates the application cookie and redirects back to
    the entry point of the demo application which is papp.jsp.
    My Questions are as follows :
    1 - Instead of creating a session object within my web based application to hold some
    information used between the different pages, can I define them in the
    application cookie? kindly advise? Is there any limitation for the length of
    the application cookie? If yes, what will be the risk?
    2 - The SSOSignOn program is calling a method in the SSOEnablerBean
    [setPartnerAppCookie(response, request). Within this method , it is retrieving
    the parameters values of the request object as :
    request.getParameterValues("urlc")[0];
    What is the role of this [urlc]? Is it hard coded? Can I change it?
    3 - In order to ensure that I am still dealing with the same user, shall I put
    the above security check procedure on each page of my weeb based application? Kindly advise?
    Thanks in advance for your prompt feedback
    regards

    Dear Paul
    I think there is a misunderstanding regarding the last correspondence.
    I am talking about the customized home page of the PORTAL and not the home page of my web based application (JSP) .So in this case, Am I able to use the customized home page which contains a login portlet instead of the default Login page of the SSO Login Server.Kindly advise!!!
    On the other hand, I am facing a problem during the surfing of the web based application.
    The web based application consists mainly of two packages :
    Package I : Bank.counter which contains a set of jsp pages.
    JSP_HOME_COUNTER (MAIN PAGE WHICH CONTAINS 2 FRAMES)
    JSP_LEFT_FRAME_COUNTER
    JSP_MAIN_FRAME_COUNTER
    JSP_MAIN_FRAME_COUNTER_DETAIL
    Package II : Bank.portfolio which contains a set of jsp pages.
    JSP_HOME_PORTFOLIO (MAIN PAGE WHICH CONTAINS 2 FRAMES)
    JSP_LEFT_FRAME_PORTFOLIO
    JSP_MAIN_FRAME_PORTFOLIO
    Please note that the SSO classes are residing under the first package.
    As agreed on in the third question, I am including in each page of my web based application, a security check procedure as follows :
    <%@ include file="ssoinclude.jsp" %>
    <%
    if(usrInfo == null)
    response.getWriter().println("<center>User information not found</center>");
    else
    my jsp code.......
    %>
    Please note that all the jsp page of the portfolio package are pointing to the SSO classes as follows :
    <%@ include file="../counter/ssoinclude.jsp" %>
    <%
    if(usrInfo == null)
    response.getWriter().println("<center>User information not found</center>");
    else
    my jsp code.......
    %>
    Once I invoke the JSP_HOME_COUNTER , it will render the JSP_LEFT_FRAME_COUNTER page and
    JSP_MAIN_FRAME_COUNTER page which invokes the SSO Login page. Once the user has been authenticate, the result of the JSP_MAIN_FRAME_COUNTER is rendered successfully. The result contains an hyperlink to the
    JSP_MAIN_FRAME_COUNTER_DETAIL page. As the user has been authenticated , this page is rendering automatically the result without displaying the SSO Login page. (Perfect as of now!!).
    Once I invoke the JSP_HOME_PORTFOLIO from the JSP_HOME_COUNTER, it runs the security procedure without any rendering of the SSO Login page (fine!!) but redirects me back to JSP_HOME_COUNTER instead of rendering the result of the JSP_HOME_PORTFOLIO.
    please note that the m_requestUrl variable in the SSOEnablerJSPBean class has been assigned the folowing value : JSP_HOME_COUNTER
    Kindly advise .

  • Change password at first login

    Hi all,
    In my JSF web app, if a user has his password reset by an admin, the new password is emailled to him, and as soon as he logs with the new password in he MUST change his password, before being allowed to use any other part of the site.
    How can I force the "change password" screen to appear?
    My current "hack" is to add this code to the beginning of every single JSF page:
    <%
         final boolean userMustChangePasswordAtNextLogin = ((Boolean) MyAbstractView.evaluateValueBinding("#{loggedInUser.userBean.mustChangePasswordAtNextLogin}")).booleanValue();
         if(userMustChangePasswordAtNextLogin) {
    %>
         <html>
              <head>
                   <META HTTP-EQUIV="Refresh" CONTENT="0; URL=ChangePassword.jsp">
              </head>
         </html>
    <% } else { %>
         [Regular JSP/JSF page content...]
    <% } %>Is there a graceful JSF way of doing this? I've investigated the NavigationHandler, but it doesn't get invoked until the user clicks on a CommandButton or such like. I've investigated ViewHandler as well, but cannot see how this would help.
    Any advice appreciated & many thanks in advance...
    - Adam.

    Thanks a lot SirG ....
    This is what I have done so far:
    package com.abc.send.controller.security;
    import javax.faces.component.UIViewRoot;
    import javax.faces.context.FacesContext;
    import javax.faces.event.PhaseEvent;
    import javax.faces.event.PhaseId;
    import javax.faces.event.PhaseListener;
    public class LoginPasswordPhaseListener implements PhaseListener
         public void afterPhase(final PhaseEvent phaseEvent)
              // Nothing to do
         public void beforePhase(final PhaseEvent phaseEvent)
              if(phaseEvent.getPhaseId().equals(PhaseId.RENDER_RESPONSE))
                   final FacesContext facesContext = phaseEvent.getFacesContext();
                   final String viewId = facesContext.getViewRoot().getViewId();
                   final boolean userMustChangePasswordAtNextLogin = true;
                   if((!viewId.equals("/logout.jsp")) && userMustChangePasswordAtNextLogin)
                        final UIViewRoot newRoot = facesContext.getApplication().getViewHandler().createView(facesContext,
                             "/restricted/changePassword.jsp");
                        facesContext.setViewRoot(newRoot);
         public PhaseId getPhaseId()
              // Seems that returning PhaseId.RESTORE_VIEW here doesn't work, so we
              // have to use an if expression in beforePhase(..)
              return PhaseId.ANY_PHASE;
    }Then in the faces-config.xml:
    <lifecycle>
        <phase-listener>com.abc.common.jsf.view.ViewScopePhaseListener</phase-listener>
        <phase-listener>com.abc.common.jsf.filter.secureserver.SecureServerPhaseListener</phase-listener>
        <phase-listener>com.abc.common.jsf.filter.browservalidation.BrowserValidationPhaseListener</phase-listener>
        <phase-listener>com.abc.common.jsf.filter.security.SecurityPhaseListener</phase-listener>
        <phase-listener>com.abc.common.jsf.filter.postback.PostBackValidationPhaseListener</phase-listener>
      <phase-listener>com.abc.send.controller.security.LoginPasswordPhaseListener</phase-listener>
      </lifecycle>So if final boolean userMustChangePasswordAtNextLogin = true; then on a successfull login currently I should be taken to the changePassword.jsp right ?

  • Bean confusion - questions - beginner

    jsp A
    <jsp:useBean id="searchHeaders" scope="session" class="database.Tool"/>
    <p><c:out value="${searchHeaders.searchHeaderMap}"/> // This shows my bean info
    <p><a href="/<c:out value="${param.newID}"/>/searchTooling.jsp?newID=<c:out value="${param.newID}"/>">Tool Lookup </a>Quick Background
    When a user clicks on the above link they are taken to a form with two input fields where they can search by an asset number or a serial number. However, depending on what site they are on - the wording might be different - asset number might be called quality number or something else.
    <jsp:useBean id="searchHeaders" scope="session" class="database.Tool"/> 
    <c:forEach var="i" items="${searchHeaders.searchHeaderMap}" varStatus="status">
              <c:forEach var="h" items="${i.key}" varStatus="status">
                  <c:choose>
                  <c:when test='${(i.key) <= "2"}'>
                      <c:forEach var="d" items="${i.value}" varStatus="status">
                      <td><c:out value="${d}"/><INPUT TYPE='text' NAME='<c:out value="${d}"/>' SIZE='30'></td> 
                   </c:forEach>     
                  </c:when>
                  </c:choose>
              </c:forEach>
              </c:forEach>My problem is that jsp A has the bean information showing but once I click on a link the bean information doesnt show until I submit the form on jsp B( which forwards back to jsp B through servlet). I thought that once I called the bean and put it in a session scope I would be able to use it/call it until I expired the session...
    How can I share a bean between two jsp's without using a form?

    First of all - sorry if my terms dont make sense - still new and learning. I dont understand what you are asking me..
    Here is the servlet that is calling/creating the bean
    public class tooling_index extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            DataFactory dbf = DataFactory.getDataFactory(DataFactory.sybase);
            ToolSearchInformation searchInfo = dbf.getToolSearchInformation();
            Tool searchHeaders = searchInfo.findSearchTableHeaders(newID);
            request.setAttribute("searchHeaders", searchHeaders);
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp?newID="+ newID);
            dispatcher.forward(request, response);
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            doGet(request, response);
    }This forwards to my jsp A. Is this what you are asking ?

  • How to access application vars into JavaBeans or Java File?

    I have the application directory strcuture like this. I am using Apache Tomcat/6.0.14 and Eclipse IDE.
    -/MyFirstServlet
    -/MyFirstServlet/WebContent
    -/MyFirstServlet/WebContent/WEB-INF/web.xml
    -/MyFirstServlet/WebContent/web.jsp
    -/MyFirstServlet/Src
         - com.model.DAO/userDAO.java (java class within package)
    I have put following code into "web.xml".
    ==================================
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
         <display-name>
         MyFirstServlet
         </display-name>
         <context-param>
              <param-name>DBDriver</param-name>
              <param-value>com.microsoft.sqlserver.jdbc.SQLServerDriver</param-value>
         </context-param>
         <context-param>
              <param-name>connectionUrl</param-name>
    <param-value>jdbc:sqlserver://localhost:1433;databaseName=MyFirstServletDB;user=hitesh;password=hit
    esh;</param-value>
         </context-param>
         <welcome-file-list>
              <welcome-file>index.html</welcome-file>
              <welcome-file>index.htm</welcome-file>
              <welcome-file>index.jsp</welcome-file>          
              <welcome-file>default.jsp</welcome-file>
         </welcome-file-list>
    </web-app>
    I am easily able to access from "web.jsp"
    ===================================
    String DBDriver = application.getInitParameter("DBDriver");
    out.println("<br>DBDriver:==="+DBDriver);
    String connectionUrl = application.getInitParameter("connectionUrl");
    out.println("<br>connectionUrl:==="+connectionUrl);
    BUT when I try to access withing userDAO.java it gives "application is not resolved"
    ========================================================================
    String DBDriver = (String)application.getInitParameter("DBDriver");
    NOTE: I understand I need to import some inbuilt java package which will allow to use applcation vars
    within java class.
    What is that package? and how to do that?
    Is there any other easy method to use global/application vars which can be used in all
    JSP/JavaBeans/Java files?
    Thanks in advance.

    It might be easier to put that code somewhere else. JSP's are for presentation, not for accessing databases, business logic, etc.

  • Issue upon upgrading from 10.1.2 to 10.1.3.3

    Hi,
    i am upgrading the AS from 10.1.2 to 10.1.3.3,
    i have deployed the same ear on oc4j 10.1.3.3 which i have deployed on 10.1.2
    the issue is, upon session time out on 10.1.3.3 it give error and doesn't redirect to session expire page(defined in web.xml) but the same ear works fine on 10.1.2 :
    error message is :
    java.lang.IllegalArgumentException: path must begin with a "/"     at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.HttpApplication.getRequestDispatcher(HttpApplication.java:1668)     at com.bidm.misc.service.bo.SessionExpireFilter.doFilter(SessionExpireFilter.java:99)     at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:623)     at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:370)     at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:871)     at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:453)     at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.AJPRequestHandler.run(AJPRequestHandler.java:302)     at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].server.http.AJPRequestHandler.run(AJPRequestHandler.java:190)     at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)     at com.evermind[Oracle Containers for J2EE 10g (10.1.3.3.0) ].util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)     at java.lang.Thread.run(Thread.java:595)
    Thanks,
    DJ

    hi steve,
    yes i am using a filter to handle the session timeout, here is the code in web.xml
    root context for the application is: /MyApp
    location for expire.jsp is : /MyApp/expire.jsp
         <filter>
              <filter-name>SessionExpireFilter</filter-name>
              <filter-class>com.myapp.SessionExpireFilter</filter-class>
              <init-param>
              <param-name>redirect</param-name>
              <param-value>expire.jsp</param-value>
              </init-param>
         </filter>
         <filter-mapping>
              <filter-name>SessionExpireFilter</filter-name>
              <url-pattern>*.jsp</url-pattern>
         </filter-mapping>
    code for SessionExpireFilter.java:
    public class SessionExpireFilter implements Filter {
    private static boolean no_init = true;
    private static Log log = LogFactory.getLog(SessionExpireFilter.class);
    private FilterConfig config;
    private String redirect;
    public SessionExpireFilter() {
    redirect = null;
    public void init(FilterConfig filterconfig) throws ServletException {
    config = filterconfig;
    no_init = false;
    initRoute();
    public void destroy() {
    config = null;
    public void doFilter(ServletRequest servletrequest,
    ServletResponse servletresponse, FilterChain filterchain)
    throws IOException, ServletException {
    HttpServletRequest httpservletrequest = (HttpServletRequest) servletrequest;
    HttpSession httpsession = httpservletrequest.getSession(true);
    if ((httpsession == null) ||
    (httpservletrequest.getRequestedSessionId() == null) ||
    (redirect == null)) {
    if ((httpservletrequest.getRequestURI().indexOf("login.jsp") != -1) ||
    ((httpservletrequest.getRequestURI().indexOf("bookingAdviceAction.do") != -1) &&
    (httpservletrequest.getParameterMap() != null) &&
    httpservletrequest.getParameterMap().containsKey("servletAction")) ) {
    filterchain.doFilter(servletrequest, servletresponse);
    } else {
    //session is expired
    RequestDispatcher requestdispatcher = config.getServletContext().getRequestDispatcher(redirect);
    requestdispatcher.forward(servletrequest, servletresponse);
    } else {
    // session is expired
    HttpServletResponse httpservletresponse = (HttpServletResponse) servletresponse;
    ServletContext servletcontext = config.getServletContext();
    // It won't happen so frequent
    if (getRedirect(redirect)) {
    httpservletresponse.sendRedirect(redirect);
    } else {
    // these jsp won't be filtered, login.jsp & index.jsp
    if ((httpservletrequest.getRequestURI().indexOf("login.jsp") != -1) ||
    (httpservletrequest.getRequestURI().indexOf("index.jsp") != -1)) {
    filterchain.doFilter(servletrequest, servletresponse);
    } else {
    RequestDispatcher requestdispatcher = servletcontext.getRequestDispatcher(redirect);
    requestdispatcher.forward(servletrequest, servletresponse);
    public void initRoute() {
    //log.debug("in initRoute");
    redirect = config.getInitParameter("redirect");
    if (redirect == null) {
    if (log.isDebugEnabled()) {
    log.debug(
    "Session Expire filter: could not get an initial parameter redirect");
    redirect = "expire.jsp";
    private boolean getRedirect(String s) {
    //log.debug("in getRedirect");
    int i = s.indexOf(":");
    if (i <= 0) {
    return false;
    } else {
    String s1 = s.substring(0, i).toUpperCase();
    return s1.startsWith("HTTP");
    Thanks,
    DJ

  • Urgent help pls -  an authenticate codes

    hi every1 can u pls help me. i need a jsp program where it authenticates the mem_ID and password which is in the login table in the database. if valid then will forward to the login.jsp or else index.jsp
    thanks for helping.

    Hi, found it but seems to be slightly messed up now :-/
    http://www.kjkoster.org/java/content/packages.jsp
    Maybe you can just ignore the user comments in between the different parts (they are a bit out of control) and make sense of it, the actual tutorial is good for what you wanted...

  • Deploying EJBs in 8i iAS 8.1.6

    I am getting a corba.COMM_FAILURE error trying to deploy Session EJB from helloworld example. Everything else works (JSP, Servlets). Any ideas?

    thanks,
    corrected the problem ORA-02085,
    it is working now. Created the dblink with the same name as the remote db service name.
    thanks to
    Getting ORA-02085
    Kris

  • Request Dispatcher question

    Hi all,
    I have a simple question based on RequestDispatcher.
    When we dispatch a file in our servlet, where should we place RequestDispatcher --- Within try block or after try, catch block as defined in this program
    Please see the coding/program---------------
    // import all necessary packages
    public class SimpleServlet extends HttpServlet
    public void doGet()throws ServletException,IOException
    try
    Here I am retrieving data from database and then store them into bean,and doing some coding.
    This Servlet will call MyJsp.jsp file.
    dispatch="/jsp/MyJsp.jsp";
    Should we define RequestDispatcher here ?
    catch
    // OR here---------
    RequestDispatcher dispatcher=request.getRequestDispatcher(dispatch)
    dispatcher.forward(request,response);
    } // end doGet() method
    } // end class
    Thanks
    amitindia

    Hi,
    It`s better to use outside try{}catch{} block if you forward to a page based on some condition like..
    try{
    if(i.equals("soemthing")){
    dispatch="/jsp/MyJsp.jsp";
    else{
    dispatch="/jsp/Error.jsp";
    catch{}
    RequestDispatcher dispatcher=request.getRequestDispatcher(dispatch)
    dispatcher.forward(request,response);
    OR if u`r going to forward to a single page whatever be the condition then you can use Dipatch inside the try{} block itself.
    regards,
    Saravanan

Maybe you are looking for

  • When I send a photo to someone by bluetooth it says "not supported content"

    i just got this BB curve 8520 today and I tried to send a photo to a friend via bluetooth, but they couldn't open it. Instead, it said "not supported content". I can send stuff to my friend from my old Nokia phone. Any idea what's wrong?

  • How to use sql query in java ?

    i don't know how to use sql query in java code. who can give me some advice? thanks

  • How do I turn a large poster into a small PDF?

    I made an academic poster in Pages (about 4' x 3') but now i need to save it as a PDF to send out.  Both printing as a PDF and exporting as a PDF look horrible, so I am following previous advice and saving it as a PostScript and then opening in Previ

  • Conditional Display Based on a Field Value

    I'm a newbie ... I developed an application that shows payment information. Record type one is a cheque Record type two is a payment stub Rec Type Account Amount PDFFile 1 888888 1234.00 summary.pdf 2 888888 10.00 2 888888 400.00 2 888888 800.00 2 88

  • U2515H Randomly goes black

    I purchased this monitor about 4 weeks ago. The screen goes black only for a 1-2 seconds and then back to normal. This happens randomly. I am pretty sure I can rule out the GPU since my previous monitor 2412HM was running with it and it didnt go rand