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.

6
  • @ElliottFrisch that won't solve the problem since OP has <input type="file" /> in that HTML form. Commented Apr 30, 2014 at 15:09
  • After removing this, even null values are not getting. @ElliottFrisch Commented Apr 30, 2014 at 15:09
  • @LuiggiMendoza I didn't scroll down that far. Good catch. Commented Apr 30, 2014 at 15:10
  • But if '<input type="file" />' have problem then why others fields getting null values? @LuiggiMendoza Commented Apr 30, 2014 at 15:11
  • @ElliottFrisch I didn't either, just searched for file word in this page :P Commented Apr 30, 2014 at 15:11

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

13 Comments

Yes, i am looking forward to it for file upload. But what is the solution of other fields? @LuiggiMendoza
@RonakJoshi the links in my answer are not for decoration purpose. Check them as well.
I got the solution of this by using cos-multipart.jar. Thanks @LuiggiMendoza
@RonakJoshi don't forget to mark the best post as an answer.
@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.
|
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");

6 Comments

But it not working for "file" type. @KapilJituri
@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.
@RonakJoshi, did you found any solution which was solved your problem. Currently I stuck with similar issue?
@SubbaReddyNallamachu If you have file upload, then use this cos.jar library which is very good and easy to implement. servlets.com/cos
@RonakJoshi, do you have any sample source how to use this COS API.
|
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");

Comments

-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>

2 Comments

It is submitting the form, but the parameters cannot be parsed by the current state of the request.
No that not working. @Susie

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.