5

I have a jsp form as below,

<form action="../Registration" enctype="multipart/form-data">
    <label> First Name:</label>
    <input type="text" class="large-field" name="firstname">

    <label> Last Name:</label>
    <input type="text" class="large-field" name="lastname">

    <label> Gender:</label>
    <label class="radio">
    <input type="radio" name="gender"  value="Male">
        Male
    </label>
    <label class="radio">
    <input type="radio" name="gender" value="Female">
        FeMale
    </label>


    <label> Address :</label>
    <input type="text" class="large-field" name="address">


    <label> City:</label>
    <input type="text" class="large-field" name="city">


    <label> College:</label>
    <select class="large-field" name="college">
    <option value=""> --- Please Select --- </option>
    <option value="XYZ">XYZ</option>

    </select>

    <label> Branch:</label>
    <select class="large-field" name="branch">
        <option value=""> --- Please Select --- </option>
        <option value="ABC">ABC</option>
    </select>
    <br />
    <label> Mobile Number:</label>
    <input type="text" class="large-field" name="mobilenumber">
    <br />

    <label> Email_ID:</label>
    <input type="text" class="large-field" name="email">
    <br />
    <label> Password:</label>
    <input type="password" class="large-field"  name="password">
    <br />
    <label> Re-Enter Password:</label>
    <input type="password" class="large-field"  name="repassword">
    <br />
    <label> Profile Picture:</label>
    <input type="file" name="file">
    <br />

    <button class="btn btn-primary">Continue</button>
</form>

Then this calls my servlet which is coded as below:

package Client_Controller;

import CommonData.ComData;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import java.util.*;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;


public class Registration extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String f_name = request.getParameter("firstname");
            String l_name = request.getParameter("lastname");
            String gender = request.getParameter("gender");
            String address = request.getParameter("address");
            String city = request.getParameter("city");
            String college = request.getParameter("college");
            String branch = request.getParameter("branch");
            String mobile = request.getParameter("mobilenumber");
            String email = request.getParameter("email");
            String password = request.getParameter("password");
            String filePath = request.getParameter("file").toString();

            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/table", "root", "root");
            s = con.createStatement();
            s.execute("insert into tblmembers(first_name,last_name,sex,address,city,college_name,branch,mobile,email_id,password) " +
                    "values('" + f_name + "','" + l_name + "','" + gender + "','" + address + "','" + city + "','" + college + "','" + branch + "','" + mobile + "'," + email + ",'" + password + "')");

            out.write("Suceess");
        } catch (Exception e) {
            out.write("" + e);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);
    }


    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

When data is inserted all values are getting null. I have tried lots of things but not working so need some help. I using bootstrap as front end.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Ronak Joshi
  • 1,553
  • 2
  • 20
  • 43

4 Answers4

12

When using enctype="multipart/form-data" you cannot retrieve parameters using plain request.getParameter. Looks like you're using Servlet 2.5 or prior, so you need to parse the request using a third party library that process it by knowing the enctype. This can be easily done using Apache Common FileUpload library.

Note that this problem should not arise if using Servlet 3.0 or newer.

More info:

Also, you have to add method="POST" to your current form to make it work. You cannot upload files using GET request.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Yes, i am looking forward to it for file upload. But what is the solution of other fields? @LuiggiMendoza – Ronak Joshi Apr 30 '14 at 15:17
  • @RonakJoshi the links in my answer are not for decoration purpose. Check them as well. – Luiggi Mendoza Apr 30 '14 at 15:18
  • I got the solution of this by using cos-multipart.jar. Thanks @LuiggiMendoza – Ronak Joshi Apr 30 '14 at 20:38
  • @RonakJoshi don't forget to mark the best post as an answer. – Luiggi Mendoza Apr 30 '14 at 20:58
  • @Ronak: Please click and read the "More info" link. It absolutely isn't there for decoration. It explains among others why the cos-multipart is **not** the recommended solution. – BalusC May 02 '14 at 07:40
  • 1
    @Luiggi: that the `org.apache.tomcat.util.http.fileupload.*` imports successfully compile suggests that OP is actually using Servlet 3.0, albeit in a completely wrong way. His actual problem is that he was reading Servlet<=2.5 targeted resources about Commons FileUpload and got completely confused because exactly those classes are under the covers also used by Tomcat 7 to fulfill the new Servlet 3.0 feature. The right answer/solution would be to just put `@MultipartConfig` annotation on the servlet class and tell him to not read outdated resources anymore as they are only confusing. – BalusC May 02 '14 at 07:44
  • I have tried but still getting null exception using "@MultipartConfig". But using cos.jar my requirement is full filled. But thanks for your opinion @BalusC . But there are some new problems now i am facing in it in some of my modules. But cos.jar working in other modules. – Ronak Joshi May 02 '14 at 15:27
  • @LuiggiMendoza, I have gone through your answers. First, thank you for such a nice answer. But, I have the similar problem even I am using Servlet - 3.0. I do not have any problem to get the selected files and File parameters. I do have only problem with entered description which I am getting the value as null(request.getParameter("description")). I don't want to use other library to solve this issue. If do you have any solution please let me know. I am using enctype="multipart/form-data" in form tag. – Nallamachu Jul 31 '17 at 13:43
  • @SubbaReddyNallamachu I would need to know which libraries you're using for your web application project, the content of your web.xml file, the servlet container or application server where you test/deploy the application and the code of your JSP. Based on that, we can know the specific Servlet version you have and if the fields are named correctly (note that server doesn't recognize the data by `id` field but using `name` e.g. ` `. – Luiggi Mendoza Jul 31 '17 at 15:29
  • Here is the web.xml file header..... The JSP I have declared....... I am trying to get the value in servlet as....... request.getParameter("description"); – Nallamachu Jul 31 '17 at 15:52
  • @SubbaReddyNallamachu check that the form is already using `enctype="multipart/form-data"` and that your Servlet is configured like this: `@WebServlet("/upload") @MultipartConfig` (as described in the link I posted above). – Luiggi Mendoza Jul 31 '17 at 16:53
  • @LuiggiMendoza, no need of declaring the servlet configuration if I declare @WebServlet("/upload") @MultipartConfig? – Nallamachu Aug 01 '17 at 13:04
  • @SubbaReddyNallamachu that's configuuration vía annotations. – Luiggi Mendoza Aug 01 '17 at 15:13
1

Don't know why but it worked for me when I provided 'name' attribute to input text.

My Old code which returned null in Servlet:

<input id="closure" type="text" size="25"><a
                        href="javascript:NewCal('closure','ddmmyyyy')"><img
                            src="drawables/cal.gif" width="16" height="16" border="0"
                            alt="Pick a date"></a>

Just putting name="closure" worked for me. Now it perfectly returns value of this input text into servlet.

<input id="closure" name="closure" type="text" size="25"><a
                        href="javascript:NewCal('closure','ddmmyyyy')"><img
                            src="drawables/cal.gif" width="16" height="16" border="0"
                            alt="Pick a date"></a>

And I am getting value of this input text in Servlet as follows:

String closure = request.getParameter("closure");
Kapil Jituri
  • 1,241
  • 14
  • 25
  • 1
    But it not working for "file" type. @KapilJituri – Ronak Joshi Jun 11 '14 at 14:27
  • @Kapil, id and name tags are depending on the browsers. Chrome browser will support with only ID parameter but not IE. It's always better to declare both ID, NAME parameters to declare to stop browser compatibility issues. – Nallamachu Jul 31 '17 at 13:36
  • @RonakJoshi, did you found any solution which was solved your problem. Currently I stuck with similar issue? – Nallamachu Jul 31 '17 at 13:37
  • @SubbaReddyNallamachu If you have file upload, then use this cos.jar library which is very good and easy to implement. http://www.servlets.com/cos/ – Ronak Joshi Jul 31 '17 at 13:46
  • @RonakJoshi, do you have any sample source how to use this COS API. – Nallamachu Jul 31 '17 at 13:51
  • You can find reference over google. For startup you can refer this link, https://www.javatpoint.com/example-of-uploading-file-to-the-server-in-servlet – Ronak Joshi Jul 31 '17 at 13:54
0

use below one to access file data

  public static Hashtable getParamsFromMultipartForm(HttpServletRequest req) throws FileUploadException {
        Hashtable ret = new Hashtable();
        List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
        for (FileItem item : items) {
            if (item.isFormField()) {
                ret.put(item.getFieldName(), item.getString());
            }
        }
        return ret;
    }

And then, whenever i need the value of any of my params, just write as below

/at the beginning of a servlet

Hashtable multipartParams = TheClassWhereIPutThatMethod.getParamsFromMultipartForm(req);


String myParamFromForm = multipartParams.get("myParamFromForm");
Karibasappa G C
  • 2,686
  • 1
  • 18
  • 27
-1

Change the following button to type submit and try again. My guess is your button is not submitting the form.

<button type="submit" class="btn btn-primary">Continue</button>
Susie
  • 5,038
  • 10
  • 53
  • 74