Using Spring to Retrieve URL Parameters

After adding a parameter to the request in Spring Boot, we are able to retrieve its value. If you need guidance on using Spring Boot and web services, I recommend consulting tutorials like this one provided by Spring: https://spring.io/guides/gs/rest-service/. The RequestParam annotation can be utilized to bind method parameters to web request parameters.

Question:

My Spring application requires me to set a parameter in the URL and then forward to it. For instance, when I click on “Show detail” in index.html, I am directed to /employees/show/1111 where the ShowController.java receives the value 1111. However, when I click on “show detail” again, I encounter a white page error. I tried setting a break point in ShowController.java, but it did not work. Can you assist me in identifying the issue and fixing it?

Controller

@Controller
@RequestMapping("/employees/show/{employee.empId}/")
public class ShowController {
    @Autowired
    EmployeeService empService;
    @GetMapping
    public String details(@RequestParam("empId") String empId, Model model) {
        Employee employee = empService.getEmployeeInfo(Long.parseLong(empId)); // break point at this row
        model.addAttribute("employee", employee);
        return "view/show";
    }

index.html


    
Id Name
Show detail

show.html


            

The arrangement of folders can be observed in the following image marked as

.



Solution:

The issue lies with the URL. The base URL being used is

/employees/show/{employee.empId}/

, while

@GetMapping

has no assigned URL and therefore takes the exact URL from

@RequestMapping("/employees/show/{employee.empId}/")

.

The purpose of

@RequestParam

is to retrieve various types of data from the request, including query parameters, form parameters, and files. On the other hand,

@PathVariable

is employed to indicate to Spring that a portion of the URI path should be treated as a value that needs to be passed to your method.

It appears that your situation is a bit ambiguous as you have been utilizing

@RequestParam

instead of

@PathVariable

.

@Controller
@RequestMapping("/employees/show/{employee:.*}/") //since spring will skip anything after a dot(.)
....
@GetMapping
public String details(@PathVariable("empId") String empId, Model model) {....}

Frequently Asked Questions