Populating bean attributes from servlet Request

I know that in a JSP, you can use
<jsp:setProperty name="p_filters" property="*"/>To populate the properties of a bean from parameters in a request.
Is there a reliable programmatic way to do this? Since I am using Tomcat, I could use
JspRuntimeLibrary.introspect(p_filters, request);But that relies on the servlet container's internal classes.
There really should be a way of doing this easily in a servlet as well as in a JSP! It should be part of the servlet standard, and the JSP standard <setProperty> tag should use that!

Well, that was buggy. Also, I've added common data types
     private static SimpleDateFormat[] df =
          new SimpleDateFormat("dd-MMM-yy"),
          new SimpleDateFormat("dd-MMM-yyyy"),
          new SimpleDateFormat("yyyyMMdd"),
          new SimpleDateFormat("dd/MM/yy"),
          new SimpleDateFormat("dd/MM/yyyy")
     public static Date parseDate(String d)
          Date result = null;
          for (int i = 0; i < df.length; i++)
               try
                    result = df.parse(d);
                    if (result != null)
                         return result;
               catch (Exception e) // Ignore
          return result;
     Sets all attributes of a bean using available parameters from HTTP request
     attributes without a matching parameter in the request are cleared.
     public static void populateBeanFromRequest(Object bean, HttpServletRequest request)
          Object[]     setParam = new Object[1];
          Method[]     methods = bean.getClass().getMethods();
          String          empty = "";
          Boolean          boolZero = new Boolean(false);
          Byte          bZero = new Byte((byte)0);
          Short          sZero = new Short((short)0);
          Integer          iZero = new Integer(0);
          Long          lZero = new Long(0);
          Float          fZero = new Float(0);
          Double          dZero = new Double(0);
          Date          dateZero = new Date(0);
          for (int i = 0; i < methods.length; i++)
               Class[] paramClass = methods[i].getParameterTypes();
               if (paramClass.length == 1)
                    String methodName = methods[i].getName();
                    if (methodName.substring(0, 3).equals("set"))
                         String propertyName = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
                         Logger.debug("Found property " + propertyName);
                         String paramValue = request.getParameter(propertyName);
                         if (paramValue == null)
                              Logger.debug("No matching parameter found");
                         else
                              Logger.debug("Found parameter value " + paramValue);
                         try
                              if (paramClass[0] == String.class)
                                   setParam[0] = (paramValue == null) ? empty : paramValue;
                              else if (paramClass[0] == Integer.TYPE)
                                   setParam[0] = (paramValue == null) ? iZero : new Integer(paramValue);
                              else if (paramClass[0] == Date.class)
                                   setParam[0] = (paramValue == null) ? dateZero : parseDate(paramValue);
                              else if (paramClass[0] == Byte.TYPE)
                                   setParam[0] = (paramValue == null) ? bZero : new Byte(paramValue);
                              else if (paramClass[0] == Short.TYPE)
                                   setParam[0] = (paramValue == null) ? sZero : new Short(paramValue);
                              else if (paramClass[0] == Boolean.TYPE)
                                   setParam[0] = (paramValue == null) ? boolZero : new Boolean(paramValue);
                              else if (paramClass[0] == Long.TYPE)
                                   setParam[0] = (paramValue == null) ? lZero : new Long(paramValue);
                              else if (paramClass[0] == Float.TYPE)
                                   setParam[0] = (paramValue == null) ? fZero : new Float(paramValue);
                              else if (paramClass[0] == Double.TYPE)
                                   setParam[0] = (paramValue == null) ? dZero : new Double(paramValue);
                              else
                                   continue;
                              Logger.debug(methodName + "(" +
                                   ((paramClass[0] == String.class) ? "\"" : "") +
                                   setParam[0].toString() +
                                   ((paramClass[0] == String.class) ? "\"" : "") + ")");
                              methods[i].invoke(bean, setParam);
                         catch (Exception e)
                              Logger.error("Error populating bean", e);
                              continue;

Similar Messages

  • Can't pass bean or request attribute from servlet to JSP

    Hi,
    I have a web app that starts with a file upload page that uses commons io fileUpload, passes the info on to a servlet. Then the servlet passes its info on to a JSP.
    I can upload the file onto the web app successfully. I also can call that uploaded file directly from the JSP (i.e. bypassing the servlet) without problem. But if I try to chain all 3 together while passing the url for the file directly as an attribute or as a bean containing file's url, I get premature end of file or can't find the property in the bean. I'm not sure what I'm doing wrong.
    the error message:
    org.apache.jasper.JasperException: javax.servlet.jsp.JspException: Premature end of file.
         org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
         servlet.UploadServlet.processRequest(UploadServlet.java:329)
         servlet.UploadServlet.doPost(UploadServlet.java:363)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
         com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:322)
         com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:130)
         com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:87)
         com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
         com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117)
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:198)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
    root cause
    javax.servlet.ServletException: javax.servlet.jsp.JspException: Premature end of file.
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:854)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:791)
         org.apache.jsp.clinTrialsEditor_jsp._jspService(clinTrialsEditor_jsp.java:144)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
         servlet.UploadServlet.processRequest(UploadServlet.java:329)
         servlet.UploadServlet.doPost(UploadServlet.java:363)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
         com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:322)
         com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:130)
         com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:87)
         com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
         com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117)
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:198)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
    root cause
    org.xml.sax.SAXParseException: Premature end of file.
         org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
         org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
         org.apache.taglibs.standard.tag.common.xml.ParseSupport.parseInputSource(ParseSupport.java:227)
         org.apache.taglibs.standard.tag.common.xml.ParseSupport.parseInputSourceWithFilter(ParseSupport.java:193)
         org.apache.taglibs.standard.tag.common.xml.ParseSupport.parseReaderWithFilter(ParseSupport.java:199)
         org.apache.taglibs.standard.tag.common.xml.ParseSupport.parseStringWithFilter(ParseSupport.java:206)
         org.apache.taglibs.standard.tag.common.xml.ParseSupport.doEndTag(ParseSupport.java:138)
         org.apache.jsp.clinTrialsEditor_jsp._jspx_meth_x_parse_0(clinTrialsEditor_jsp.java:189)
         org.apache.jsp.clinTrialsEditor_jsp._jspService(clinTrialsEditor_jsp.java:88)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
         servlet.UploadServlet.processRequest(UploadServlet.java:329)
         servlet.UploadServlet.doPost(UploadServlet.java:363)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
         com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:322)
         com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:130)
         com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:87)
         com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
         com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117)
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:198)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
    Code from the servlet:
    String dName = "http://localhost:8084/fileUploadApp/faces/";
    url = dName + fileName;
    beans.FileInfo.setFileName(fileName);
    request.setAttribute("fileInfo", new FileInfo());
    beans.FileInfo.setDName(dName);
    beans.FileInfo.setDirName(dirName);
    beans.FileInfo.setUrl(url);
    File saveTo = new File(dirName + fileName);
    //if I use the next 2 lines I get "can't resolve symbol - create field, local var or parameter FileInfo"
    FileInfo fileInfo = new beans.FileInfo();
    request.setAttribute("fileInfo", FileInfo); //error here
    request.setAttribute("myUrl", url);
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/clinTrialsEditor.jsp");
    dispatcher.forward(request, response);
    on JSP
    <jsp:useBean id="fileInfo" class="beans.FileInfo" scope="request"/>
    <jsp:setProperty name="fileInfo" property="*"/>
    <%--<c:import url="http://localhost:8084/fileUploadApp/faces/lowVision.xml" var="url" /> --%> <c:import url="${myUrl}" var="url" />
    <x:parse xml="${url}" var="clin" />
    etc...x:set with xpath expressions
    Can anyone spot my error(s)?
    Thanks for the help!

    Thanks for your reply, Ram.
    I made the change but I get an error "Unable to find a value for "fileName" in bean of type beans.FileInfo"
    Here's the bean:
    package beans;
    public class FileInfo {
    private static String fileName;
    private static String dirName;
    private static String dName;
    private static String url;
    /** Creates a new instance of FileInfo */
    public FileInfo() {
    public static void setFileName(String fn){
    fileName = fn;
    public static String getFileName(){
    return fileName;
    public static void setDirName(String dn){
    dirName = dn;
    public static String getDirName(){
    return dirName;
    public static void setDName(String d){
    dName = d;
    public static String getDName(){
    return dName;
    public static void setUrl(String u){
    url = u;
    public static String getUrl(){
    return url;
    Pertinent parts of servlet:
    String dirName = "C:/MyNBProjects/fileUploadApp/web/"; //save file to web app then convert to url so it can be called to show it on next page
    String dName = "http://localhost:8084/fileUploadApp/faces/";
    url = dName + fileName;
    FileInfo fileInfo = new FileInfo();
    fileInfo.setFileName("fileName");
    fileInfo.setDName("dName");
    fileInfo.setDirName("dirName");
    fileInfo.setUrl("url");
    request.setAttribute("fileName", fileName);
    request.setAttribute("url", url);
    request.setAttribute("fileInfo", fileInfo);
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/clinTrialsEditor.jsp");
    dispatcher.forward(request, response);
    jsp:
    <jsp:useBean id="fileInfo" class="beans.FileInfo" scope="request"/>
    <jsp:setProperty name="fileInfo" property="*"/>
    url = <c:out value="${url}" />
    //works; not part of bean
    fileName = <c:out value="${fileName}" />
    //works; not part from the bean
    fileInfo.fileName = <jsp:getProperty name="fileInfo" property="fileName" />
    //doesn't work
    <%--fileName = <c:out value="${fileInfo.fileName}" /> //doesn't work
    Can you spot the error(s)?
    Thanks for your help.

  • Error while accessing bean created from servlet

    Hi there
    I have a jsp page form home.jsp where i am collecting user name and password and then directing to a LoginServlet.Here if the user is validated then i create a accMasterBean and store it in Session object which i create here and then redirect to profile.jsp
    In the profile.jsp page i am using bean as follows:--
    <jsp:useBean id="accMasterBean" scope="session" class="AccountMaster">
    <jsp:setProperty name="accMasterBean" property="*"/>
    </jsp:useBean>
    i am fetching the properties of this bean in profile.jsp itself and try to display as shown below:---
    <%=accMasterBean.getAccountNumber() %>
    where accountNumber is a property defined inside AccountMaster class
    but it gives an error as follows :---
    <input type="text" name="emailAddress" value="Exception generated ---javax.servlet.ServletException: Exception thrown on line '205' from page 'D:\\Program Files\\Allaire\\JRun\\servers\\default\\emtech2\\jsp\\members\\profile.jsp'.
    Plz note if remove the above line of fetching the property of bean in profile.jsp page then there is no error
    Hoping to get a reply soon
    Thanking u
    Mumtaz
    The code for LoginServelt is given below
    ====================================
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    public class LoginServlet extends HttpServlet{
         private Connection conn=null;
         public void init(ServletConfig config)throws ServletException{
              super.init(config);
         public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
         try{
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              conn=DriverManager.getConnection("jdbc:odbc:emt");
         }catch(ClassNotFoundException e){System.out.println("Error loading database driver");}
         catch(SQLException e){     System.out.println("SQL Exception in Databse driver");     }
         PrintWriter out = null;
         out=response.getWriter();
         response.setContentType("text/html");
         Statement st=null;
         ResultSet rs=null;
         String aN=null;
         String pN=null;
         String accountNumber1=null;
         String pinNumber1=null;
         String alternatePassword1=null;
         String emailAddress1=null;
         String firstName1=null;
         String lastName1=null;
         String address1=null;
         String zipPostalCode1=null;
         String city1=null;
         String state1=null;
         String country1=null;
         String companyName1=null;
         String title1=null;
         String homePhone1=null;
         String workPhone1=null;
         String mobilePhone1=null;
         String pager1=null;
         String faxNo1=null;
         String website1=null;
                        //Date dob;
         String dateOfBirth1=null;
         String gender1=null;
         String securityStatus1=null;
                        //Date doreg;
         String dateOfRegistration1=null;
         int noOfAccounts1=0;
         int noOfAttempts1=0;
         String remarks1=null;
         try{
              aN=request.getParameter("accountNumber");
              pN=request.getParameter("pinNumber");
              st=conn.createStatement(); // creating a statement to execute
              rs=st.executeQuery("SELECT * FROM ACCOUNT_MASTER where AccountNumber=\'" + aN + "\' and PinNumber= \'"+pN +"\' ;");
              while (rs.next())
                        accountNumber1=rs.getString("AccountNumber");
                        pinNumber1=rs.getString("PinNumber");
                                                           //alternatePassword1=rs.getString("alternatePassword");
                        emailAddress1=rs.getString("EmailAddress");
                        firstName1=rs.getString("FirstName");
                        lastName1=rs.getString("LastName");
                        address1=rs.getString("Address");
                        zipPostalCode1=rs.getString("ZipPostalCode");
                        city1=rs.getString("City");
                        state1=rs.getString("State");
                        country1=rs.getString("Country");
                        companyName1=rs.getString("CompanyName");
                        title1=rs.getString("Title");
                        homePhone1=rs.getString("HomePhone");
                        workPhone1=rs.getString("WorkPhone");
                        mobilePhone1=rs.getString("MobilePhone");
                        pager1=rs.getString("Pager");
                        faxNo1=rs.getString("FaxNo");
                        website1=rs.getString("WebSite");
                        gender1=rs.getString("Gender");
                        break ;
         // closing the connection
         rs=null;
         st=null;
         conn.close();
    if((accountNumber1.equals(aN))&&(pinNumber1.equals(pN))){
         // create all beans address and userprofile
         HttpSession session=request.getSession();// creating the session
         AccountMaster accMasterBean=new AccountMaster();
         accMasterBean.setAccountNumber(accountNumber1);
         accMasterBean.setPinNumber(pinNumber1);
         accMasterBean.setEmailAddress(emailAddress1);
         accMasterBean.setFirstName(firstName1);
         accMasterBean.setLastName(lastName1);
         accMasterBean.setAddress(address1);
         accMasterBean.setZipPostalCode(zipPostalCode1);
         accMasterBean.setCity(city1);
         accMasterBean.setState(state1);
         accMasterBean.setCountry(country1);
         accMasterBean.setCompanyName(companyName1);
         accMasterBean.setTitle(title1);
         accMasterBean.setHomePhone(homePhone1);
         accMasterBean.setMobilePhone(mobilePhone1);
         accMasterBean.setWorkPhone(workPhone1);
         accMasterBean.setPager(pager1);
         accMasterBean.setFaxNo(faxNo1);
         accMasterBean.setWebsite(website1);
         accMasterBean.setGender(gender1);
    session.setAttribute("accMasterBean",accMasterBean);// setting the account bean in the session attribute
         getServletConfig().getServletContext().getRequestDispatcher("/jsp/members/profile.jsp").forward(request,response);
    }else{
         // do some processing for account field and pasword field not set and return back to main page
         getServletConfig().getServletContext().getRequestDispatcher("/jsp/signup.jsp").forward(request,response);
    }// end of try
    catch(SQLException e){out.println("SQL Exception generated in LoginServlet---"+e);}
    catch(Exception e1){ out.println("Exception generated in LoginServlet---" + e1);}
    finally{
    try{
         if(conn!=null) conn=null;
         if (rs!=null) rs=null;
         if(st!=null) st=null;
    }catch(Exception e){out.println("Exception closing database connections "+e);}
    } // end of doPost
         public void destroy(){
              try {
                   if(conn!=null) conn=null;
         catch (Exception e) { System.out.println("Error closing database connection"); }
         public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{ doPost( request, response);}
    }//end of loginservlet
    =======================================

    Hi everyone
    I have got the solution
    Thanks
    Mumtaz

  • Set request attributes from the request attributes

    Using struts chaining actions.
    When using chaining the requestAttributes are lost.
    Is there a way to get all the request attributes and set them back to the request again?
    if so how to do this?
    Thanks.

    Looks like nobody knows :(
    It seems odd that nobody's tried to get InputSelectLOV or DataHandler working with a Struts app...
    ... anyway, on to finding out why the thing's throwing my releasemode away. This really is very like swimming through treacle :(

  • How can I create a java bean instance from servlet, at runtime?

    Will anybody help me?
    I want to send bean (class) name to a servlet through parameter and I need servlet to create specified bean instance and run its method that I will send through another parameter, at runtime.

    Thanks. I found answer

  • Returning ResultSet from servlet to jsp - java.lang.NullPointerException

    Hey all, i've been stuck on this for too long now...just trying to return a ResultSet from a servlet to jsp page.
    Had a bunch of problems earlier...which i think were fixed but...now i get a "java.lang.NullPointerException" in my jsp page when i try to get elements from the ResultSet object.
    Here is the latest version of my code:
    Servlet:
    String QueryStr="select ProdName from products";
    Statement stmt=conn.createStatement();
    rs=stmt.executeQuery(QueryStr); //get resultset
    sbean.setInventory(rs); //set ResultSet in bean
    req.getSession(true).setAttribute("s_resbean",sbean); //create session/request variable, set to bean
    Bean:
    package beans;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    import javax.sql.*;
    public class SearchBean extends HttpServlet{
         private int searchFlag=0;
         private ResultSet inventory;
         public SearchBean(){
         public int getSearchFlag(){
         return searchFlag;
         public ResultSet getInventory(){
              return inventory;
         public void setInventory(ResultSet rs){
              this.inventory=rs;
         public void setSearchFlag(){
              this.searchFlag=1;
    jsp:
    <%@ page language="java" import="java.lang.*,java.sql.*,javax.sql.*,PopLists.PopInvLists,beans.SearchBean"%>
    <jsp:useBean scope="session" id="s_resbean" class="beans.SearchBean" />
    <% ResultSet categories=PopInvLists.getCat();
    ResultSet manuf=PopInvLists.getManuf();
    ResultSet supplier=PopInvLists.getSupplier();
    ResultSet cars=PopInvLists.getCars();
    ResultSet search=(ResultSet)request.getAttribute("s_resbean");
    %>
    <%     while(search.next()){
         String pname=search.getString("ProdName");
    %>
    It craps out when i try to loop through the "search" ResultSet.
    I can loop through the rest of the ResultSets no problem....just this one doesn't work because it's set in a servlet, not a simple java class.
    Just to clarify, i am populating some dropdown lists on entry to the screen, which the user will use to perform a search. Once the search btn is clicked, the servlet is called, gets the request info for the search, performs search, and returns the resultset to the original screen. I want to eventually display the result under the search criteria.
    Someone....Please Please please tell me how to get this working...it should be very simple, but i just can't get it to work.
    Thanks in advance,
    Aditya

    req.getSession(true).setAttribute("s_resbean",sbean); //create session/request variable, set to beanHere you add an attribute to the session.
    ResultSet search=(ResultSet)request.getAttribute("s_resbean");Here you try to get the attribute from the request. Naturally it isn't there because you added it to the session, not the request. Despite your comment in the first line of code, a session is not a request. And vice versa.

  • How do I get the client certificate from the request

    We are on Netweaver 2004 using the SAP webdispatcher (end-to-end). I need to do an OCSP validation, I have all of the code I need for the OCSP portion.  What I need is the X509Certficate that came from the client.  Is this stored in the request object, session? How do I get it?
    Thanks.

    Hi Joseph,
    I think the question is which component terminates the SSL connection. It could be an upfront load balancer or the WebAS itself. The former could write the certificate into a request header vairable,  while the latter will create a J2EE standard request attribute: javax.servlet.request.X509Certificate
    I never did it with the web dispatcher, but you can try the following:
    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
    HTH
    Daniel

  • Passing bean as attribute to servlet in request scope

    Hello,
    I want to pass a bean from a jsp to my controller servlet. As I understood, as long as I can give the bean 'request' scope, then I should be abble to access the bean, as an attribute in the doPost / doGet method of my servlet. However, when I try to get the bean in the servlet, its always null.
    I am aware that request scope beans don't loose their values when passing to other JSP's , but what about passing to servlets?
    I dont want to use a session scoped bean as I believe this should be possible with a request scoped variable.
    <%-- vwLogon.jsp --%>
    <jsp:useBean id="viewBean" class="com.alto.common.ViewBean" scope="request">
         <jsp:setProperty name="viewBean" property="viewName" value="/vwLogon"/>
    </jsp:useBean>
    <html>
    <body>
    <h2>Enter Name</h2>
    <form method="GET" action="controller">
         Enter your name:<input type="text" name="vwLogon_User_txt" value=""/>
         Enter your password:<input type="secret" name="vwLogon_Password_txt" value=""/>
    <input type="submit" name="vwLogon_Logon_Btn" value="Logon"/>
    </form>
    </body>
    </html>
    ------------------------------- controller servlet
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ViewBean viewBean = (ViewBean)req.getAttribute("viewBean");
    String strURL = new String("");
    if (!(viewBean==null)) {
    strURL = viewBean.getViewName();

    A request/response pair is one communication between the client browser and the web server. A submit form action generates a new request.
    In this instance you have two requests:
    1 - load login page
    2 - submit login page
    The point of being able to give a bean request scope, is so that you can use jsp:forward, or jsp:include to pass on the request, and the bean as well.
    In your case, a session bean is probably called for, as you have 2 request/responses in your session.
    Hope this clears things up a little.
    Cheers,
    evnafets

  • Retrieve data from a bean into a Servlet

    Hi,
    I created a simple JSP file called index.jsp situated in application root, then I associated this JSP with a java bean in order to collect data after the form submission, the attribute Action inside the Form tag points on a Servlet called Login situated in the application com.myapp.servlets package.
    the problem is that, using the scope="session" in the JSP page, I'm able to get catch the bean generated after the submission of the form, even the action is the Servlet called Login neither a back to the currest JSP or a redirection to another JSP, but in the same time, when I try to use bean methods to read the data (username, password) it gives null as result, I'm not able to understand the behavior of the bean which is created via Form submission but unreachable via the Servlet.
    herese the code
    the JSP (index.jsp)
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <jsp:useBean id="MyBean" scope="session" class="com.datalog.beans.LoginBean"/>
    <jsp:setProperty name="MyBean" property="*"/>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Document sans nom</title>
    </head>
    <body>
    <table width="100%" border="1">
      <tr>
        <td> </td>
      </tr>
      <tr>
        <td><form name="form1" method="post" action="doLogin">
          <table width="100%"  border="0" cellspacing="0">
            <tr>
              <td width="30%">username : </td>
              <td><input name="username" type="text" id="username"></td>
            </tr>
            <tr>
              <td>password : </td>
              <td><input name="password" type="password" id="password"></td>
            </tr>
            <tr>
              <td> </td>
              <td><input type="submit" name="Submit" value="Envoyer"></td>
            </tr>
          </table>
        </form></td>
      </tr>
      <tr><!-- in case when try to use without a servlet call-->
        <td>username after submission <jsp:getProperty name="MyBean" property="username" /><br>
         password after submission <jsp:getProperty name="MyBean" property="password" /></td>
      </tr>
    </table>
    </body>
    </html>The bean (LoginBean.java)
    package com.datalog.beans;
    import java.io.Serializable;
    public class LoginBean implements Serializable {
        private String username;
        private String password;
        public LoginBean(){
            System.out.println("i'm the bean ... "+this);
        public String getPassword() {
            return password;
        public void setPassword(String password) {
            this.password = password;
            System.out.println(this.password);
        public String getUsername() {
            return username;
        public void setUsername(String username) {
            this.username = username;
            System.out.println(this.username);
    }Servlet (Login.java)
    * Created on 14 d�c. 2004
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package com.datalog.cpservlets;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import com.datalog.beans.LoginBean;
    * Servlet Class
    * @web.servlet              name="Login"
    *                           display-name="Name for Login"
    *                           description="Description for Login"
    * @web.servlet-mapping      url-pattern="/Login"
    * @web.servlet-init-param   name="A parameter"
    *                           value="A value"
    public class Login extends HttpServlet {
        public Login() {
            super();
            // TODO Auto-generated constructor stub
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
            // TODO Auto-generated method stub
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException,
            IOException {
            // TODO Auto-generated method stub
            super.doGet(req, resp);
        protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            PrintWriter out = response.getWriter();
            out.println("<br><br>Servlet (Login) in use.<br>");
            out.println("username from request.getParameter : "+request.getParameter("username")+"<br>");
            out.println("password from request.getParameter : "+request.getParameter("password")+"<br>");
            out.println("<br><br>Trying to use the bean...<br>");
            HttpSession session = request.getSession();
            LoginBean myBean = (LoginBean)session.getAttribute("MyBean");
            out.println("supposed bean adr : "+myBean);
            out.println("<br>username from myBean.getUsername : <b>"+myBean.getUsername()+"</b><br>");
            out.println("<br>password from myBean.getPassword : <b>"+myBean.getPassword()+"</b><br>");
    }thank's.

    The code that would populate the bean is here:
    <jsp:useBean id="MyBean" scope="session" class="com.datalog.beans.LoginBean"/>
    <jsp:setProperty name="MyBean" property="*"/>
    When this code runs, it
    1 - creates a LoginBean (if one is not already present)
    2 - Populates the loginBean from the request parameters.
    But this code is currently running when you generate the login page - not when you push the submit button.
    Solutions
    1 - Submit the form to a JSP page which runs the jsp:setProperty tag and then forwards to your Login servlet
    2 - Retrieve the request parameters in your servlet and populate the bean. The jakarta commons BeanUtils are the standard way to go here. They are actually preferable to the jsp:setProperty tag which has some "features" in its use.
    Cheers,
    evnafets

  • Does Weblogic 5.1 support the STANDARD javax.servlet.request.X509Certificate attribute?

    Hello!
    My strong suspicion from looking at the Weblogic SSL documentation on
    http://e-docs.bea.com is that WebLogic SSL does not put any client-side
    certificates into the 'javax.servlet.request.X509Certificate' attribute
    of a servlet's HttpServletRequest (as an array of
    java.security.cert.X509Certificate instances).
    Currently, it appears that Weblogic uses a proprietary attribute name
    ('weblogic.security.somethingOrOther') and returns instances of the
    deprecated Java 1.1 java.security.Certificate class.
    When will Weblogic support this aspect of the Servlet 2.2 specification,
    if it doesn't already?
    Regards,
    James W.

    I just verified this with the Java doc. Either the Java documentation is
    incorrect or we are still using the older version of the certificate
    encoding class. I will check on this, we may have fixed it in a subsequent
    service pack.
    Thanks,
    Michael
    Michael Girdley
    Product Manager, WebLogic Server & Express
    BEA Systems Inc
    "James Webster" <[email protected]> wrote in message
    news:[email protected]..
    Hello!
    My strong suspicion from looking at the Weblogic SSL documentation on
    http://e-docs.bea.com is that WebLogic SSL does not put any client-side
    certificates into the 'javax.servlet.request.X509Certificate' attribute
    of a servlet's HttpServletRequest (as an array of
    java.security.cert.X509Certificate instances).
    Currently, it appears that Weblogic uses a proprietary attribute name
    ('weblogic.security.somethingOrOther') and returns instances of the
    deprecated Java 1.1 java.security.Certificate class.
    When will Weblogic support this aspect of the Servlet 2.2 specification,
    if it doesn't already?
    Regards,
    James W.

  • Access of JSF Beans from Servlet Filter

    Is there any way how can I access session JSF beans from servlet filter?
    I need to check certain value of JSF bean stored in session scope in my filter.
    Thanks
    ferdo

    Frank,
    I am not sure about phase listener, this is the whole situation:
    as I am not using Container Managed Security with my JSF, after I do sucessfull login into application, I need to store some information into the session scope (user etc) and in the servlet filter I need to find out if the user is connected.
    I was trying to put such info into Servlet Session directly in my bean via External Context and reading the info in Filter.
    This is working fine when my application is running locally (jdev oc4j) but once deployed into Application server, when user login first time, user information is somehow removed from the session, and cannot figure out why.
    So I was thinking to try another approach, to find out from servlet filter if JSF bean value is set or not.
    Any other suggestions? Do not want to swicth to Container Manages Security now.
    ferdo
    null

  • Passing beans across JSR Portlet Requests

    I'm new to portlet development and having trouble getting my head around the following...
    All I wan't to do is display a simple form, process the data and display some results.
    I would expect to do this through a combination of processAction method and a doView method, however it seems incredibly difficult to get the data created in processAction method into my JSP.
    If I was writing a servlet I'd simply create a bean and store it as an attribute in the request scope, but this doesn't seem posible within portlets.
    The sun examples use setRenderParameter(), but this only takes strings.
    I'd could add the bean to the PortletScope but would rather not as
    1. The bean will hang around for the lifetime of the portlet rather than the lifetime of the request
    2. The Portlet Specification stes that "Attributes stored in the PORTLET_SCOPE are not protected from other web components of the portlet application.
    Surely it can't be this hard to create a bean in the processAction method and access it from the JSP. Please tell me I'm missing something!

    I have the same problem with WebLogic Portal, so I
    think there's a problem of clarification with the spec, and I
    hope this will be clarified once theres a new version of
    the portlet API.
    If attributes set in ActionRequest cannot be seen in
    the render() methods, I simply see no point in defining
    setAttribute() and getAttribute() methods on the base
    PortletRequest interface ( from which both
    RenderRequest and ActionRequest inherit ).
    I've checked JSR 168 and PLT3.1 states that
    "Attributes set in the portlet request are
    available in the included servlet request", but
    from the above it seems that this is only true of
    renderRequests. Is this a bug in my Portal server
    (Vignette 7 Trial Edition)?

  • Can't retrieve bean value from jsp!

    Here's the chain of events for my web app:
    JSP form (get info from user) -> forwarding jsp (uses bean to save info submitted to form)-> servlet (retrieves info from DB) -> JSP (presents DB info to user by populating values in text fields from original form)
    Right now, I can access all the values submitted to the first JSP from my servlet. However, after my servlet retrieves the info from a db and stores it in a bean and forwards the request (using requestdispatcher) to the 2nd JSP, I can't get the values from the bean from the 2nd jsp. I was able to use the bean to store the information submitted to the original JSP, however.
    Here's some relevant code:
    FROM FORWARDING JSP (which saves user-submitted info in bean)
    <jsp:useBean id="fxFormBean" class="fxmatcher.FxFormBean" scope="request"/>
    <jsp:setProperty name="fxFormBean" property="*" />
    <jsp:forward page="/FxMatcher" />
    FROM LAST JSP (which should populate form fields)
    header stuff:
    <jsp:useBean id="fxFormBean" class="fxmatcher.FxFormBean" scope="session"/>
    info retrieval:
    <INPUT TYPE="text" NAME="fx_key" value="<%= fxFormBean.getFx_key() %>">
    I wrote this JSP based on the example given here: http://www.jsptut.com/Editing.jsp, but I'm not getting the value from the bean. The result JSP just has value="".
    I'm pretty sure that my servlet is saving the info to bean correctly, but here's the code anyways:
    //retrieves info from DB
    FxFormBean fx = (FxFormBean) request.getAttribute("fxFormBean");
    fx.setFx_key (traderKey);
    fx.setAa_block(agent_block);
    fx.setAddition_to (additional_to);
    log("trader key: [" + fx.getFx_key() + "]"); //debugging code
    My debugging code did print out the correct info, so I don't think there's anything wrong with the bean or the servlet.
    I would appreciate any help. Thank you very much.

    The first JSP puts the bean in the request, the servlet retrieves the bean from the request and updates it but in the second JSP you set the scope to session:
    <jsp:useBean id="fxFormBean" class="fxmatcher.FxFormBean" scope="session"/>
    So the second JSP is looking in the wrong place for your bean. Change the scope in the second JSP to request:
    <jsp:useBean id="fxFormBean" class="fxmatcher.FxFormBean" scope="request"/>

  • Accesing a html parameter from servlet is not producing in a new file

    Hi,...
    I have passed two values from html and accessed thru a servlet file.
    In servlet, parameters are verified and result must passed to a new jsp file.
    Wen i run the file i can view only a blank page.I think the problem will be in servlet mapping.
    verify my coding and give me a result.
    I wer using net bean 6 with glassfish v2 server.
    public class Logverifier extends HttpServlet {
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
    /* TODO output your page here
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet Logverifier</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet Logverifier at " + request.getContextPath () + "</h1>");
    out.println("</body>");
    out.println("</html>");
    ServletConfig config=getServletConfig();
    String user=config.getInitParameter("user");
    String pass=config.getInitParameter("pass");
    ServletContext context=getServletContext();
    RequestDispatcher reqdis=context.getRequestDispatcher("menu.jsp");
    RequestDispatcher reqdis1=context.getRequestDispatcher("login.jsp");
    if((user.equals(request.getParameter("user")))&&(pass.equals(request.getParameter("pass"))))
    reqdis.forward(request, response);
    else
    reqdis1.forward(request, response);
    } finally {
    out.close();
    <servlet>
    <servlet-name>Logverifier</servlet-name>
    <servlet-class>com.Logverifier</servlet-class>
    <init-param>
    <description>          </description>
    <param-name>user</param-name>
    <param-value>admin</param-value>
    </init-param>
    <init-param>
    <param-name>pass</param-name>
    <param-value>media</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
    <servlet-name>Logverifier</servlet-name>
    <url-pattern>/com/Logverifier</url-pattern>
    </servlet-mapping>
    </servlet>
    regards,
    satheesh

    Hi,...
    I have passed two values from html and accessed thru a servlet file.
    In servlet, parameters are verified and result must passed to a new jsp file.
    Wen i run the file i can view only a blank page.I think the problem will be in servlet mapping.
    verify my coding and give me a result.
    I wer using net bean 6 with glassfish v2 server.
    public class Logverifier extends HttpServlet {
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
    /* TODO output your page here
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet Logverifier</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet Logverifier at " + request.getContextPath () + "</h1>");
    out.println("</body>");
    out.println("</html>");
    ServletConfig config=getServletConfig();
    String user=config.getInitParameter("user");
    String pass=config.getInitParameter("pass");
    ServletContext context=getServletContext();
    RequestDispatcher reqdis=context.getRequestDispatcher("menu.jsp");
    RequestDispatcher reqdis1=context.getRequestDispatcher("login.jsp");
    if((user.equals(request.getParameter("user")))&&(pass.equals(request.getParameter("pass"))))
    reqdis.forward(request, response);
    else
    reqdis1.forward(request, response);
    } finally {
    out.close();
    <servlet>
    <servlet-name>Logverifier</servlet-name>
    <servlet-class>com.Logverifier</servlet-class>
    <init-param>
    <description>          </description>
    <param-name>user</param-name>
    <param-value>admin</param-value>
    </init-param>
    <init-param>
    <param-name>pass</param-name>
    <param-value>media</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
    <servlet-name>Logverifier</servlet-name>
    <url-pattern>/com/Logverifier</url-pattern>
    </servlet-mapping>
    </servlet>
    regards,
    satheesh

  • How can i send xml file with a http servlet request

    Hi
    Please tell me how can I send a xml file into http servlet request.
    I have a servlet(action) java file.From this servlet I have generate a xml file. Now I need to send that xml file to another servlet with http servlet request object.
    Dave.

    When you say you have generated an XML file what do you mean?
    Is it a file stored on disk? Then pass the file path as a string to the servlet.
    Is it stored in memory as an object? The pass a reference to the object to the servlet.
    Or are you asking how to communicate between servlets?
    Look in the JavaDocs for the RequestDispatcher class. You can use this class to forward the request to another servlet. Data can be passes using the RequestDispatcher by storing it as attributes using the request getAttribute and setAttribute methods. Also described in the JavaDOcs.
    http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/RequestDispatcher.html

Maybe you are looking for

  • SSRS 2012 Conditional Formatting Color Issues When Exporting to Excel

    Hi all, We recently upgraded to SQL 2012 from SQL2008 R2. I'm having a strange issue with SSRS2012. One of the report has conditional formattings on cell background colors. Everything works fine when render the report in browser or preview mode. Howe

  • Certutil -crl problems (the directory name is invalid)

    Another problem for you fine experts to consider...2 tier PKI, offline Root 2008 R2, 1 Sub Ent CA in Domain1 (2008 R2) and 1 Sub Ent CA in Domain2 (2012 R2). SubCA 1 and 2 are configured pretty much identically, however when setting up SubCA 2 I am h

  • External monitors no longer sleep

    I have a Feb 2011 Macbook Pro 15" with the i7 and the AMD Radeon HD 6750M video card.. From the Thunderbolt port I go into a Matrox Dual Head 2 Go adpater, which gives me two DVI outputs to matching Lenovo 22" monitors... Before the 10.7.2 update, th

  • What are the differences between trace shapes and stamp shapes?

    Trace shapes can be drawn against like a stencil. Stamp shapes cannot be traced against. They can only be stamped onto the canvas. To stamp, double tap on the stamp shape. Shapes from Shape CC are stamp shapes.

  • HR Infotype Screen Programming!

    Hi All, I have a text field in my infotype screen which is editable. By default, the enteries are in CAPS. What do i need to do, if i want the field to accept "Caps" and small letters aswell? Thanks in advance for all the responses. Regards, Sundar.