0

I want to set property in bean using <jsp:setProperty> and assigning value using param. Here is the code:

In create.jsp:

<form id="form1" name="form1" action="save.jsp" method="POST"
enctype="multipart/form-data">
<input required="" type="text" name="nam">

In save.jsp:

 <jsp:useBean class="jbeans.account.BankAccount" scope="request" id="ac1">
</jsp:useBean>
    <jsp:setProperty name="ac1" property="accountHolderName" param = "nam">
</jsp:setProperty>
<%
        ac1.createAccount(request); //createAccount is a public method.
                                    //Recieving value of nam always as null
%>

In jbeans.account.BankAccount.java:

public void setAccountHolderName(String accountHolderName) {
    this.accountHolderName = accountHolderName;
}

When i type the value inside nam textbox, the value of accountHolderName i recieve is always null. How to get right value?

Malwinder Singh
  • 6,644
  • 14
  • 65
  • 103

1 Answers1

0

The problem is that you explicitely put enctype="multipart/form-data" in your form definition. It is not the default, and allows to upload files to a server.

Unfortunately, it cannot be used is simple JSP parameter decoding.

If you do not need to upload files, just write

<form id="form1" name="form1" action="save.jsp" method="POST">
<input required="" type="text" name="nam">
...

in your get.jsp, and everything should go fine. If you really need to upload files, you will need to decode parameters in a servlet, but that would be quite another question ...

Edit : how to get multipart in servlets

For remaining of the answer, I assume that you use at least servlet 3.0 api and a compliant container (at least Tomcat 7)

To decode multipart/form-data, you will have to declare a servlet with a multipart-config element or annotation, and use it as the action of the form (say its url is "/saver").

<form id="form1" name="form1" action="${pageContext.request.contextPath}/saver"
    method="POST" enctype="multipart/form-data">
<input required="" type="text" name="nam">
<input type="file" name="file">
...

You declare the servlet that way (using annotations) :

@WebServlet(name="saveServlet", urlPatterns="/saver")
@MultipartConfig
public class SaveServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // get an use the file part
        Part part = req.getPart("file");
        // ...
        req.getRequestDispatcher("/save.jsp").forward(req, resp);
    }
}

Note that the servlet forwards to your original JSP file that now can find the request parameter, since it has be decode from the multipart by the servlet. But IMHO, you'd better do all processing in the servlet (call of ac1.createAccount(request);) and use the JSP do display the results.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252