Using a bean in a servlet

In my application I am having:-
1)- a table in my database which contains the details of the user profile.
2)- a bean which contains the string variables for all the user details along with the getters and setters.
3)- a servelet and a jsp.
In servlet I want to fetch entire data of the table and want to assign the values to the setters of the bean.
in jsp I want to call that bean and want to use its getters to display the entire profile of the user.
I am finding compleatly unable to use the bean in the servlet, please help me out.

hi,
try like this..
after fetching all of your datas
store in setter method of the bean.
pass it as session.setAttribute ( "beanname", bean);
in jsp
get that session attribute
beanname b = (beanname) session.getAttribute ( "beanname" ) ;
<%=b.getMethod ()%>

Similar Messages

  • The use of javabean in a servlet

    I used a javabean in (scope=application) a jsp, but now I want to use that bean in my servlet, can anybody show me how?

    why not share with others ??
    please write out

  • How to use the Javabeans in the servlets

    I want to use the beans in the servlets ..
    Please help me out with some good examples...
    and the resources where I can get the related hints

    For visual beans, check out jsp:plugin
    This will convert you bean to an applet.
    For non-visual beans, check out jsp:useBean

  • Using java bean in servlet

    Hi,
    I have a problem in getting the values from simple bean to servlet. The project has one html form. When the user click on the submit button one jsp will be invoked which calls a bean program to validate the user data for required fields. Based on the result, jsp program forward the control to a servlet which stores the data in a database. Otherwise another jsp is called to inform the user to fill in the required data.
    My problem is how to send the data from bean to servlet?
    The snippet of jsp that calls bean is like this :
    <%!
    %>
    <jsp:useBean id="formHandler" class = "subFormBean" scope="request">
    <jsp:setProperty name="formHandler" property="*"/>
    </jsp:useBean>
    <%
    if (formHandler.validate()) {
    %>
    <jsp:forward page="subscriberRegistration"/>
    <%
    } else {
    %>
    <jsp:forward page="retry.jsp"/>
    <%
    %>
    And the snippet of the bean is like this :
    public boolean validate() {
    boolean bool=true;
    if (subname.equals("")) {
    errors.put("subname","Please enter your Name");
    subname="";
    bool=false;
    public subFormBean() {
    subname="";
    public String getSubName() {
    return subname;
    public void setSubName(String sname) {
    subname =sname;
    The servlet which is to receive the data is like this :
    public class subscriberRegistration extends HttpServlet{
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    subFormBean sfb = new subFormBean();
    sfb.setSubName(subname);
    But I'm getiing error while trying to compile the servelet saying that no variables found - sfb, subname etc.
    Please let me know how to invoke the bean from servlet. I want to use servlet to instead of jsp to insert records into database. How can i do this? Please help me. Thanks in advance.

    Hi Tolls,
    Sorry, I'll give a bigger snippet of the prog.code below :
    public class subscriberRegistration extends HttpServlet{
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    subFormBean sfb = new subFormBean();
    sfb.setSubName(subname);
    sfb.setSubAddress(subaddress);
    sfb.setSubCity(subcity);
    sfb.setSubState(substate);
    sfb.setSubCntry(subcntry);
    sfb.setSubPin(subpin);
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection = DriverManager.getConnection(connectionURL,"scott","tiger");
    stmt = connection.createStatement();
    rs = stmt.executeQuery("SELECT subid_seq.NEXTVAL FROM DUAL");
    while(rs.next()) {
    String subno = rs.getString("NEXTVAL");
    PreparedStatement pst = connection.prepareStatement("insert into eps_subscriber(eps_subno, eps_subname, eps_subaddress, eps_subcity, eps_substate, eps_subcntry, eps_subpin, eps_subphno, eps_subemailid, eps_subuserid, eps_subpwd) values(?,?,?,?,?,?,?,?,?,?,?)");
    pst.setString(1,subno);
    pst.setString(2,sfb.subname);
    pst.setString(3,sfb.subaddress);
    pst.setString(4,sfb.subcity);
    pst.setString(5,sfb.substate);
    pst.setString(6,sfb.subcntry);
    pst.setString(7,sfb.subpin);
    I'm validating the form data in beans program. Servlet is used to insert records into the database. So, i'm trying to capture data from the bean. How to capture the data from the bean to servlet? Or should I get it from the form fields directly? The servlet worked well when data was captured directly from html form fields. Please help me to fix this. Thanks in advance.

  • 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

  • Insert data into table from JSP page using Entity Beans(EJB 3.0)

    I want to insert data into a database table from JSP page using Entity Beans(EJB 3.0).
    1. I have a table 'FRIENDS', (in Oracle 10g database).
    2. It has two columns, 'NAME' and 'CITY'. Both have datatype strings(varchar2).
    3. Now from a JSP page, having two textfields, 'NAME' and 'CITY', I want to insert data into table 'FRIENDS'.
    4. In between JSP and database is a Entity Bean(EJB 3.0) and a stateless session bean.
    5. I am using JDev as editor.
    Please provide me code ASAP or link with similar example.
    Thank you.
    Anurag

    Hi,
    I am also trying that scenario. So u can
    Post the jsp form data to a Servlet which will act as a Controller.
    In the servlet invoke the business method.
    Similar kind of app is in www.roseindia.net
    Hope this would help u.
    Meanwhile if u get any optimal solution, pls post it.
    Thanks,
    Happy Java Coding.

  • Problem using a bean in JSP on Tomcat 5.0.28

    Hi,
    I'm new to JSP, I've installed Tomcat 5.0.28 and I'm able to run JSP but when I try an asp wich uses a bean it gives me this error, the directory structure is
    testingProject with the first.jsp
    testingProject\WEB-INF\classes\myPackage with the test.class
    the first.asp
    <%@ page import="myPackage.Test" %>
    <html><head><title>Test</title></head>
    <body bgcolor=white>
    <jsp:useBean id="list" class="myPackage.Test"> </jsp:useBean>
    <jsp:getProperty name="list" property="value1" />
    <%=list.value1%>
    <p>
    </body></html>
    the Test.java
    package myPackage;
    public class Test{
    String value1="testinggggggggg";
    public void Test(){
    public String getValue1(){ return value1}
    the error
    thanks in advance
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 6 in the jsp file: /first.jsp
    Generated servlet error:
    C:\Program Files\Apache Group\Tomcat 5.0\work\Catalina\localhost\testingProject\org\apache\jsp\first_jsp.java:60: cannot resolve symbol
    symbol : variable value1
    location: class myPackage.Test
    out.print(list.value1);
    ^
    1 error
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:332)
         org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:412)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:472)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:451)

    There are two ways of getting info from the bean.
    1) the jsp:getProperty tag, which seems correct in your code
    2) the <%= ... tag. In that case you must write a valid java expression. In your case: list.getValue1()

  • How to use connection pool in jsp/servlet ?

    I found I can "lookup" it in either java beans/servlets/JSP using JNDI. why?
    what is the best practice to use it in a jsp/servlet web app considering JNDI lookuping expensive?
    Thanks!
    Bo
    Edited by: BobXu on Nov 17, 2008 2:27 PM
    Edited by: BobXu on Nov 17, 2008 2:32 PM

    Huh?
    You can lookup a JNDI resource from anywhere in java code you want to. As long as you have a repository set up to search on :-)
    Of course whether that resource is available or not is a different matter. If you let the server set up the JNDI resource for you, then you can't run it standalone outside the server without something else setting the same thing up :-)
    So its not so much a limitation of beans, but just the environment you run the code in.
    Best practice? Don't write sql queries in JSP pages :-)
    For the rest you might consider the DAO pattern. Or ignore SQL altogether and let hibernate do the work there for you.
    Cheers,
    evnafets

  • "Sharing" a stateful session bean between two servlets, beans

    Hello!
    I just started to learn some java ee programming and was wondering how i would share one stateful session bean between two servlets.
    I created the bean with @Stateful.
    I tried to inject the stateful bean in both servlets by @EJB and i can manipulate the object, but each servlet seems to have its own object.
    The bean has a remote interface that it implements.
    What i also tried was to add the mappedName to the @Stateful expression. Something like: @Stateful(mappedName="name") and to use the bean by @EJB(mappedName="name") but it had no effect.
    Im using glassfish 2.1 with netbeans 6.7.1 as my environment (standard settings)
    dummy question, but i googled like hours and couldnt find anything : \
    hope someone can help and sorry for my bad english
    greets and thanks

    Hi there!
    I think you are searching for something like an application wide singleton. There is the possibility to define such one in the Glassfish admin console.
    Hope this helps!

  • Using java bean with jsp

    hello friends,
    i'm new to jsp. i want to create an html form that accepts username and a value from four radio buttons and display back the entered name and checked radio button's value using java bean.
    i use the <jsp:setProperty id="" property="*"> method. i don't know how to access the radio buttons value from the html.
    also when i use an additional field other than username the jsp page is showing error.
    Please give me the correct method to use java bean with jsp in this circumstance.
    thank you.

    thank you, but i have a problem left. the case is like this.
    i got the jsp and bean worked fine when i have a sinle input text field.
    but when i added a second text field i recieved the following error.
    javax.servlet.ServletException: basket.newbean.getUserPass()Ljava/lang/String;
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:825)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:758)
         org.apache.jsp.newform.process_jsp._jspService(process_jsp.java:69)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    where userPass is the new form element. I have made the subsequent chanes in my bean program and jsp file.
    pls hlp.

  • Reset Managed Bean in Action Servlet?

    I've searched through the forum and have came close in finding the answer however the recommended solution is not working...
    How can I use this code:
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("beanName");to reset a managed bean in an Action Servlet?
    How can I get the managed bean in the Action Servlet and reset it?
    I'm not after getting the HttpSession and invalidating it. I would just like to reset the managed bean in the servlet.
    Thanks!

    @RaymondDeCampo, Does resetting the managed
    bean same with resetting the session?If you remove the bean from the session, using traditional servlet APIs, it will appear to JSF as an uninitialized managed bean. When the application uses it next, JSF will instantiate it and set the properties as normal.

  • Beans, jsp and servlets

    i want to use jsp to servlet communication. i use a bean with session scope for each user. in the jsp pages i simply use the jsp command -<jsp:useBean id="cart" scope="session" class="DummyCart" /> and set properties etc. how can i use a servlet and set proprties for the same session bean as i cannot useBean there...

    A bean is just a class, and can be instantiated without means of a tag:DummyCart dc = new DummyCart();
    session.setAttribute("cart", dc);To pull the class out of the session (when set by tag or not):DummyCart dc = (DummyCart)session.getAttribute("cart");

  • What is the use of bean?

    I'm new to JSP.What is the use of bean? And how do we write it? Can I do the JSP which connect to database without using the bean?

    You don't need JavaBeans when working with JSPs. For info on JavaBeans look here: http://developer.java.sun.com/developer/onlineTraining/Beans/beans02/
    As a general rule of thumb it's not a very good idea to have JSPs connect directly to a database. I'd higly recommend you pickup "Java Servlet Programming" from O'Reilly, it covers Servlets, JSPs and how to tie them together.

  • Froward  bean value to servlet

    if I want to forward bean value to servlet I use
    <%@ page import="java.util.*" %>
    <html>
      <head>
    <jsp:useBean id="formHandler" class="cedars.FormBean" scope="request">
    <jsp:setProperty name="formHandler" property="*"/>
    </jsp:useBean>
    <%
       if (formHandler.validate()) {%>
    <jsp:forward page="/servlet/Insert"/>
    <% } else { %>
    <jsp:forward page="/resubmit.jsp"/>
    <% } %>
    </body>
    </html> is that right?
    why i keep get error message like NullPointerException on <jsp:forward page="/servlet/Insert"/>
    my beab local on cedars.FormBean, my Insert.java in WEB-INF/classes
    thank you for the help

    Hi,
    don't think it will execute EL this way. However,you should be able to execute JavaScript (what you should keep in mind though is that any DOM manipulation on AMX page rendering is a risk and can put you into trouble). What is the HTML you want to insert (and to what extend do you control the metadata tags added to the AMX page this way? Wouldn't it be possible to add the content using AMX components?
    Frank

  • How can i design a EJB application using session Beans?

    Hello,
    I am designing a Find application using EJB. Here a user is prompted a search page, where he can enter the search criteria's. Then on click of submit, the query is formed at the server side depending on what criteria's were selected. Then a jdbc query is performed and the results are returned back to the user. Here no session is maintained for the users. Can anyone suggest me how to design this application using EJB. Should i use entity beans for this or session beans will suffice? Should the jdbc query be performed in the bean itself or should it be outside in a helper class? Please kindlu suggest me the design for this application...
    Regards,
    Subbu

    Hi,
    First of all, I'm unable to figure out why you need to use EJB for this scenario. You can write a helper class to frame and execute the query.
    If you really want to use EJB, then I suggest you use a stateless Session Bean with transaction attribute as TX_NOT_SUPPORTED. From the session bean, you can call the helper class. But, by avoiding the session bean, you can eliminate remote calls, thus improving your performance. Also, check if the database & the db driver you are using supports sql caching.
    Regards,
    Raj.

Maybe you are looking for

  • IPad not recognized in Windows 7 Ultimate

    Good Morning, Last week, I received an iPad 32GB WiFi as a gift. At this time I was running Vista Ultimate 64 on my home system. When I unboxed the iPad I read the instructions and installed iTunes 64-bit 9.2.1 on my Vista system. I connected the iPa

  • Nikon Capture NX and Mac OS 10.4.11

    Using Nikon Capture NX, thumbnails don't display in the browser. Program will not quit and must be Force Quit every time. Other functions seem OK. I have tried various versions, from the CD that came with the camera (ver 1.3.0), to various others up

  • SAP HR Administrative Services Authorization

    Dear All, Can you please guide me for the HRAS Authorizations. I have selected the P_ASRCONT authorization object SAP_ASR_EMPLOYEE SAP_ASR_MANAGER But still when I pprocess the form, it doesnt go to the next level. But When I give SAP_ALL, the form i

  • Move hana db from single tenant to multi tenant

    Hi experts, I have read that, for the moment, we cannot do an upgrade of a SAP system + conversion to a multi tenant Hana database in one shot. We have to deploy it on a single tenant and then move it to a multi tenant environment (where we can put a

  • Please send me business blue print

    Hi All Could any of you send me a sample business blueprint, just to understand the intensity of the projects and the customizing that has to be done. my mail id is [email protected] Kindly do the needful. regards kumar