Request not processing using jackson REST web services (RESTful Spring Controllers) @PathVariable

Viewed 62

I got this error when I was working with Jackson REST web services (RESTful Spring Controllers) @PathVariable.

    @Controller
    @RequestMapping("/api")
    public class EmployeeRestControllerImpl{

        @GetMapping("/employeeList/{empId}")
            public @ResponseBody
               ResponseMessage getEmployeeListById(@PathVariable int empId){
    
                   .....
                   System.out.println(employees.get(empId));
                   .....
        }

    }

employees:[{"firstName":"ABC","lastName":"ABC"},{"firstName":"XYZ","lastName":"XYZ"},{"firstName":"DEF","lastName":"DEF"}]

Exception:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Optional int parameter 'empId' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Is it necessary to change the primitive type to wrapper object.. why? Help me to figure out .Thanks in advance..

1 Answers
  • The error is very specific

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Optional int parameter 'empId' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.

    Seems you are requesting the API without any empId hence the null value for path variable. The error message says that if you want to support null then instead of primitive int variable user wrapper objects like Integer

as

@GetMapping("/employeeList/{empId}")
public @ResponseBody ResponseMessage getEmployeeListById(@PathVariable Integer empId)
  • Try passing right empId in the request http://localhost:8080/api/employeeList/123 and it should work
Related