1

I'm new in Java. Trying to create simple CRUD application. But facing issue while adding record in DB, getting request.getParameter() null. I'm using jersey for RESTful Web services and Gson for json data.

See below code.

Java

protected void doPost(HttpServletRequest request, HttpServletResponse response)   
         throws ServletException, IOException {  
    PrintWriter out = response.getWriter();
    System.out.println(request.getParameterMap());
    if (request.getParameterMap().containsKey("id")) {
        String id = request.getParameter("id");
        System.out.println(id);
    }

    String firstname = request.getParameter("firstname");
    int id = Integer.parseInt(request.getParameter("id"));
    String lastname = request.getParameter("lastname");
    int phone = Integer.parseInt(request.getParameter("phone"));
    String jobId = request.getParameter("jobId");
    Double salary = Double.parseDouble(request.getParameter("salary"));

    Employee e = new Employee();
    e.setFirstname(firstname);
    e.setId(id);
    e.setLastname(lastname);
    e.setPhone(phone);
    e.setJobId(jobId);
    e.setSalary(salary);

    int status=EmployeeDao.add(e);

    if(status > 0){
        System.out.println("Record added successfully!");
    }else{
        System.out.println("Unable to add record");
    }
    out.close();
}

AngularJS

$http({
        method : 'POST',
        url : 'AddResource',
        data: empObj,
        headers: { 'Content-Type': 'application/json' }
    }).then(function successCallback(response) {
        if(response.data){
            $scope.getEmployee();
        }
    }, function errorCallback(response) {
        console.log("Data not coming");
    });
Santosh Shelke
  • 562
  • 2
  • 6
  • 19
  • Yes all the parameters. Ex. {"firstname":"Santosh","lastname":"Shelke","id":123,"phone":987098,"jobId":"Software Eng","salasy":98708} – Santosh Shelke Dec 28 '17 at 14:34
  • even System.out.println(request.getParameterMap()) also given empty object. – Santosh Shelke Dec 28 '17 at 14:37
  • In Google Chrome debugger upon sending the request, as you have your `empObj` object built, go to console and type `dir(empObj)` and press Enter. And then inspect all the properties of this object. Does it contain `id` property or not? –  Dec 28 '17 at 14:39
  • It has all the parameters, which require. firstname : "Sachin" id : "123" jobId : "87403" lastname : "S" phone : "0384630" salary : "20000" – Santosh Shelke Dec 28 '17 at 14:45

4 Answers4

1

EDIT

@Santosh, As i mentioned in comment you can do this in two ways.

Method 1 :: send parameters separately in JS.

       $http({
            method : 'POST',
            url : 'AddResource',
            data: 'id=' + id + 'firstname=' + firstname,
            headers: { 'Content-Type': 'text/plain' }
        }).then(function successCallback(response) {
            if(response.data){
                $scope.getEmployee();
            }
        }, function errorCallback(response) {
            console.log("Data not coming");
        });

then you can extract them in Java like

request.getParameter('id');
request.getParameter('firstname');

Method 2 :: send as object and split in Java

       $http({
            method : 'POST',
            url : 'AddResource',
            data: 'empObj=' + empObj,
            headers: { 'Content-Type': 'text/plain' }
        }).then(function successCallback(response) {
            if(response.data){
                $scope.getEmployee();
            }
        }, function errorCallback(response) {
            console.log("Data not coming");
        });

then you can extract the object in Java like

String JSON = request.getParameter('empObj');

use a parser like Gson to parse this JSON.

Gson gson = new Gson();

Employee empObj = gson.fromJson(JSON, Employee.class);
  • Thank you Kumar for your response. But I am sending object which having all parameters. – Santosh Shelke Dec 28 '17 at 14:42
  • @SantoshShelke yes I got it, you need to split your object either in js or in Java. Java cannot go in to your object and check for the variable id. Example :: In js you can do like data : ‘id=‘+id + ‘name=‘+name. or in java extract the empObj like Employee empObj = (Employee) request.getParameter(‘empObj’), in this case you need to send in Ajax like data : ‘empObj=‘+empObj –  Dec 28 '17 at 14:44
  • But I am sending JSON, so it should be accepted right? – Santosh Shelke Dec 28 '17 at 14:48
  • getting null with ‘id=‘ + empObj – Santosh Shelke Dec 28 '17 at 14:54
  • @SantoshShelke Check my edit and let me know if you still have issues. You can also send JSON, but since servlets cannot parse them, they will be received as a string. Just change you content type to 'Content-Type': 'text/plain' –  Dec 28 '17 at 15:11
  • Changed 'Content-Type': 'text/plain' but still getting null request.getParameter("empObj") – Santosh Shelke Dec 28 '17 at 15:47
1

You are setting content type to application/json. The documentation for ServletRequest.getParameter() states

Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

Try to omit the Content-Type parameter to use getParameter(), or alternatively get the request body and parse the JSON String from there.

//Edit: Apparently angular defaults to application/json, so omitting content-type will be without effect. To form-encode your data, see this question: How do I POST urlencoded form data with $http?

Michael A. Schaffrath
  • 1,992
  • 1
  • 14
  • 23
1

if You are using json data stream you can't use request.getParameter("firstname"); for get json parametrer, you need to read the raw data.

    protected void doPost(HttpServletRequest request, HttpServletResponse response)   
             throws ServletException, IOException {  
        PrintWriter out = response.getWriter();


StringBuffer strJson = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                strJson.append(line);
            }

            Employee employee = new GsonBuilder().create().fromJson(strJson.toString(), Employee.class);


        int status=EmployeeDao.add(employee);

        if(status > 0){
            System.out.println("Record added successfully!");
        }else{
            System.out.println("Unable to add record");
        }
        out.close();
} catch(Exception ex) {
}
    }
Jialzate
  • 315
  • 1
  • 6
0

Modify the request produced with angular to pass the object as a json string in the body, something like:

employer="{id:1,\"firstname\":\"John\",....}"

In the servlet:

String jsonString = request.getParameter("employer");
Gson gson = new Gson();
Employee empObj = gson.fromJson(jsonString, Employee.class);

You can also use a pojo or an EJB and expose it as a web service, that is a more simple and flexible solution in my opinion

@Stateless
@Path(value = "employer")
@PermitAll
public class EmployerController {
    ... some object or injections

    @Path(value = "insert")
    @Consumes("application/x-www-form-urlencoded")
    @Produces(MediaType.APPLICATION_JSON)
    @POST
    public T create(@FormParam("employer")String entity)throws ValidationException, Exception{
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode j;
    try {
        j = (ObjectNode) mapper.readTree(entity);
        Employer myemp = mapper.readValue(j, Employer.class);
        ...do what you need...
        return myemp;
    } catch(Exception e){
      LOG.log(Level.SEVERE,"Error",e);
      throw e;
    }
}

}

or in a more fancy way, you can implement a method "fromString(String json)" like this

public static MyEmpl fromString(String jsonString) throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    MyEmpl object = mapper.readValue(jsonString, MyEmpl.class);
    return object;
}

and then define the previous method as:

    public T create(@FormParam("employer")MyEmpl entity)throws Exception{

and the deserializer (for instance, jackson in wildlfy) do the magic things

Daniele Licitra
  • 1,520
  • 21
  • 45