views:

165

answers:

3

I want to pass value to servlet but I keep get null value.

<jsp:useBean id="Helper" class="model.Registration" scope="request"/>
<form action="/Project/Registration" method="post" enctype="multipart/form-data">
    <input type="text" size="20" name="name" value="<%=Helper.getName()%>">
    <input type="submit">
</form>

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    Registrationh2 = (Registration) request.getAttribute("Helper");
    if(h2!=null){
       System. out.println(h2.getName());
    }
    else
        System. out.println("NULL");        
}

Is there anything wrong with my code?

A: 

I am assuming you want to pass the name String from the Registration model. If that is the case you need fetch using the following code.

String registrationName = request.getParameter("name");

Also, remove the enctype as multipart. It is used when you are uploading any files from the client.

Snehal
+1  A: 

The scope of the Registration object is request. So it wont be available in the servlet which is a new request. You can get the bean by setting in session. Or, make the scope to session.

oks16
+1  A: 

Regardless of the scope, jsp:useBean will not work if you use multipart/form-data form encoding. This encoding is required to handle file uploads and the support to parse this encoding is not built in JSP/Servlet in such a transparent manner that request.getParameter() and consorts would return the desired value. The new Servlet 3.0 API has however support for this form encoding, but since you would need request.getPart() for this instead, this will not work with jsp:useBean as well.

As answered several times in related questions you posted before, you need Apache Commons FileUpload to parse a multipart/form-data request. You can however create a Filter which transparently parses and replaces the original request in case of multipart/form-data requests. You can find here a blog article about it, complete with code examples.

BalusC
Hi a very good example thank you.