Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsp useBean is NULL by getAttribute by servlet

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;
    }
}
like image 946
Ravi Parekh Avatar asked Feb 17 '11 09:02

Ravi Parekh


People also ask

Is useBean a directive in JSP?

The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the Bean class is already created, it doesn't create the bean depending on the scope.

What is JSP useBean?

The jsp:useBean tag accesses or creates an instance of a Java type, typically a JavaBean class, and associates the instance with a specified name, or ID. The instance is then available by that ID as a scripting variable of specified scope. Scripting variables are introduced in "Custom Tag Libraries".

What is the default scope of JSP useBean tag?

The scope in which the bean should be stored such as page, request, session, and application. The default scope is page. This line will make the useBean tag available to the JSP page with the prefix of wcbase .

Which JSP tag can be used to set bean property?

The <jsp:setProperty> tag sets the value of one or more properties in a JavaBean component, using the Bean's set methods. You must use a <jsp:useBean> tag to declare the Bean before you use <jsp:setProperty> . The value of name in <jsp:setProperty> must match the value of id in <jsp:useBean> .


2 Answers

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:

  • Easy way of populating Javabeans based on request parameters
  • Using beans in servlets
  • Our Servlets wiki page
like image 134
BalusC Avatar answered Sep 28 '22 07:09

BalusC


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);
    }
}
like image 23
Jan Zyka Avatar answered Sep 28 '22 07:09

Jan Zyka