6

user is null in servlet. Pls let me if doing mistake.

i m trying to get all html element in bean rateCode.jsp

<%@page import="com.hermes.data.RateCode_" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
    <head>
        <title>Rate Code</title>
    </head>
    <body>      
         <jsp:useBean id="user" class="com.hermes.data.RateCode_" scope="request" >
            <jsp:setProperty name="user" property="*"/></jsp:useBean>
            <form  id="f_rateCode" action="/ratePromoCodes" method="post"  >
                <table align="center" border="1" cellspacing="0">
                    <tr>
                        <td colspan="2" align="center" class="header">Rate Code Administrations</td>
                    </tr>
                    <tr>
                        <td align="right" style="border-style: solid;">Rate Code:</td>
                        <td align="left" style="border-style: solid;">
                            <input type="text" id="code" name="code" value="${user.code}"  size="10" maxlength="32" style="width: 100px"/>
                    </td>
                </tr>

                <tr>
                    <td align="right" style="border-style: solid;">Rate Description:</td>
                    <td align="left" style="border-style: solid;">
                        <input type="text" id="description" name="description" value="<%=user.getDescription()%>" maxlength="128" size="40"></td>
                </tr>              
                <tr><td><input type="submit" value="ok" /></td> </tr>
            </table>
        </form>

Servlet - ratePromoCodes

protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        RateCode_ rc = (RateCode_) req.getAttribute("user");
        Enumeration an = req.getAttributeNames();
        Enumeration pn = req.getParameterNames();
        Object o = null;
        while (an.hasMoreElements()) {
            o = an.nextElement();
            System.out.println(o);
        }
        while (pn.hasMoreElements()) {
            o = pn.nextElement();
            System.out.println(o);
        }
    }

RateCode.java (javaBean)

public class RateCode_  {    
    private String code ;
    private String description;
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Ravi Parekh
  • 5,253
  • 9
  • 46
  • 58

3 Answers3

10

You seem to misunderstand the working and purpose of jsp:useBean.

First of all, you've declared the bean to be in the session scope and you're filling it with all parameters of the current request.

<jsp:useBean id="user" class="com.hermes.data.RateCode_" scope="session">
    <jsp:setProperty name="user" property="*"/>
</jsp:useBean>

This bean is thus stored as session attribute with the name user. You need to retrieve it in the servlet as session attribute, not as request attribute.

RateCode_ user = (RateCode_) request.getSession().getAttribute("user");

(user is a terrible and confusing attribute name by the way, I'd rename it rateCode or something, without this odd _ in the end)

However, it'll contain nothing. The getCode() and getDescription() will return null. The <jsp:setProperty> has namely not filled it with all request parameters yet at that point you're attempting to access it in the servlet. It will only do that when you forward the request containing the parameters back to the JSP page. However this takes place beyond the business logic in the servlet.

You need to gather them as request parameters yourself. First get rid of whole <jsp:useBean> thing in the JSP and do as follows in the servlet's doPost() method:

RateCode_ user = new RateCode_();
user.setCode(request.getParameter("code"));
user.setDescription(request.getParameter("description"));
// ...
request.setAttribute("user", user); // Do NOT store in session unless really necessary.

and then you can access it in the JSP as below:

<input type="text" name="code" value="${user.code}" />
<input type="text" name="description" value="${user.description}" />

(this is only sensitive to XSS attacks, you'd like to install JSTL and use fn:escapeXml)

No, you do not need <jsp:useBean> in JSP. Keep it out, it has practically no value when you're using the MVC (level 2) approach with real servlets. The <jsp:useBean> is only useful for MV design (MVC level 1). To save boilerplate code of collecting request parameters, consider using a MVC framework or Apache Commons BeanUtils. See also below links for hints.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • thanx buddy. i have done same thing and `action="forward.jsp"` forward.jsp ` ` and i get it `RateCode_ user = request.getAttribute("rateCode")` but how to populate Bean RateCode without another jsp (forward.jsp) so i don't have to getParameter one-by-one just like we do in struts. i have to use only JSP, servlet. – Ravi Parekh Feb 17 '11 at 13:09
  • As explained in the answer, don't use `jsp:useBean`. Populate it in the servlet. – BalusC Feb 17 '11 at 13:17
  • but how? as yor said. `req.getParameter("code")` is there any way to populate in bean b'coz i have so many input fields in jsp. Thanx for u r support. – Ravi Parekh Feb 17 '11 at 13:21
  • Just write code or use a MVC framework which does the populating job for you. The `jsp:useBean` is inappropriate for this whenever you want to use a servlet. There are workarounds, but you'll lose the control over the request/response (and please write full words like a professional, not like a teen ;) ). – BalusC Feb 17 '11 at 13:32
  • :) thank you. i have to use only JSP Servlet. i know struts, spring but project is old one. that is why. :) – Ravi Parekh Feb 17 '11 at 13:41
  • So it sounds like useBean helps you on a GET request, but not on a POST? – Ryan Sep 30 '11 at 18:45
  • 1
    @Ryan: No, it works in both. But it makes no sense when you're using servlets. It's helpful in basic/starter servletless JSP-only webapps. You only need to understand its lifecycle. It does not offer any way to control the request/response. Only pre/postprocessing the data and nothing else. You could hack in a getter which does the business action method and returns the result, but that's ugly. A servlet offers you a clean way to control request/response and invoke actions. If your sole intent is populating the bean in a servlet, check commons BeanUtils or just use a MVC framework like JSF. – BalusC Sep 30 '11 at 18:53
  • 1
    @Ryan: see also: http://stackoverflow.com/questions/5096454/easy-way-of-populating-javabeans-based-on-request-parameters and http://stackoverflow.com/questions/3541077/design-patterns-web-based-applications/ – BalusC Sep 30 '11 at 19:00
  • I was thinking that I can bind DTO with forms and send data to servlet from jsp (like `*.xhtml` to `ManagedBean` in JSF ) . Because I am getting values from dto object eg. ``. If I can send object from servlet to jsp then there may be an option to send object from jsp to servlet. What do you say @BalusC? – Yubaraj Jan 18 '16 at 13:41
  • @Yubaraj: yes, a lot of starters intuivively expected jsp:useBean to work the same way. But it **does not** as explained in the answer. Just use a normal MVC framework. – BalusC Jan 18 '16 at 13:43
  • Actually now I am working in a project using technologies only JSP and Servlet so trying to make MVC based. i.e. using jsp page as view and servlet as controller. so tried to bind dto with jsp (html) form and came to this question/answer. Is there any option @BalusC to do? – Yubaraj Jan 18 '16 at 13:47
  • @Yubaraj: http://stackoverflow.com/q/5096454, http://stackoverflow.com/q/7879806 and, importantingly, http://stackoverflow.com/q/2658922 – BalusC Jan 18 '16 at 13:55
4

The problem (and its solution) is as follows:

You create a request scope bean user but once the page is loaded the request is finished and gone - no wonder it is null in the next request which is completely unrelated to this one. What you probably wanted to do is the following:

1) Remove the <jsp:useBean ...> from your jsp page completely so it will look as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="com.hermes.data.RateCode_" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head><title>Rate Code</title></head>
<body>
<form id="f_rateCode" action="/forwarder.jsp" method="post">
    <table align="center" border="1" cellspacing="0">
        <tr>
            <td colspan="2" align="center" class="header">Rate Code Administrations</td>
        </tr>
        <tr>
            <td align="right" style="border-style: solid;">Rate Code:</td>
            <td align="left" style="border-style: solid;"><input type="text" id="code" name="code" value=""
                                                                 size="10" maxlength="32" style="width: 100px"/></td>
        </tr>
        <tr>
            <td align="right" style="border-style: solid;">Rate Description:</td>
            <td align="left" style="border-style: solid;"><input type="text" id="description" name="description"
                                                                 value="" maxlength="128"
                                                                 size="40"></td>
        </tr>
        <tr>
            <td><input type="submit" value="ok"/></td>
        </tr>
    </table>
</form>
</body>
</html>

2) Your form now redirects to another jsp, the forwarder. It looks like follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="user" class="com.hermes.data.RateCode_" scope="request"/>
<jsp:setProperty name="user" property="*" />
<jsp:forward page="/ratePromoCodes" />

What this does: it creates the bean in request scope - the request which submitted the form. Then it populates the bean properties with the data from the form and finally it forwards (IN SAME REQUEST, HERE IS THE POINT) to the servlet which does some job.

3) Finally do something in your servlet, I did this for testing purposes:

public class TestServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        RateCode_ code = (RateCode_) request.getAttribute("user");
        System.out.println(code);
    }
}
Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
  • thanx budy it works but why it don't work with servlet. GOT null. is there any other way to do this but only in JSP. without framework. – Ravi Parekh Feb 17 '11 at 11:14
  • scope="session" would also give NULL while it is in SESSION. – Ravi Parekh Feb 17 '11 at 11:26
  • The point is that if you want the bean to have properties set according to the form-entered values you must call AFTER the form was submitted. It will work with session scope if you go directly to the Servlet BUT 1) You must use request.getSession().getAttribute("user") 2) Note that if you put the in your form page the bean will try to get populated on page load when the form is empty. So as result the bean will not be null in the servlet but the properties will not get set. – Jan Zyka Feb 17 '11 at 11:36
  • yes u r right i tried this request.getSession().getAttribute("user") i found "user" but values of code & description is NULL – Ravi Parekh Feb 17 '11 at 11:57
  • for this we have to add another jsp for forward for every page and if validation error comes all html form will be blank and user have to fill it up again. so is their a way to keep it populated in same jsp. here is link but using forward and another jsp. [link] http://www.javaworld.com/jw-03-2000/jw-0331-ssj-forms.html?page=3 – Ravi Parekh Feb 17 '11 at 12:04
  • You might check the properties in the forwarder. If its ok you forward to the original servlet, otherwise you forward back to the index page. Then the index page should have again the and s as values in form. The bean won't be recreated if you forward from forwarder because one bean already exists. You should also set the properties to some meaningful defaults in the constructor to not see garbage (null etc.) on first visit. – Jan Zyka Feb 17 '11 at 12:30
0

You are using a request-scoped bean in a JSP. This JSP is submitted and a Servlet responds.

When the Servlet is executed, a new "life cycle" starts and the request-scope does not contain any request-scoped bean used/created in the JSP.

You have to submit the bean's properties as request parameters, and read them one-by-one in the servlet.

frm
  • 3,346
  • 1
  • 21
  • 21
  • 1
    can we get this as a Bean (RateCode) so i don't have to bind it one-by-one. like all html input elements in RateCode bean automatically. – Ravi Parekh Feb 17 '11 at 11:08