0

I am working on a spring web applications that are supposed to have URL parameter to be passed into the page. like

xyz.com/listing?type='Hotels'
xyz.com/listing-details?id=53

But When I am looking at the approach followed by other websites. It looks to be something like

xyz.com/listing/Hotels
xyz.com/listing-details/335

How Can I adjust my spring controller to fetch these parameters out of the URL.

Currently my controller method looks like this for xyz.com/listing?type='Hotels'

public ModelAndView getContactList(@RequestParam(value = "type", defaultValue =       "Hotels") String type, HttpServletRequest request) {
  Some Code
}

Also how can I show a 404 page when the request Parameter is not in the proper format and I don't find any results associated with that.

2
  • @PathParam will help you. Commented Apr 2, 2014 at 12:58
  • To match only when the user provides a particular GET param, you can do something like this: @RequestMapping(params = "type=Hotel"). I believe it can use regular expressions as well, and accepts a single string param or an array of them. Commented Apr 2, 2014 at 13:16

2 Answers 2

2

Use @PathVariable instead of @RequestParam

Assume you have Hotels 1-500 and you would like to return result if the number is less than 500. If the Hotel Number exceeds 500 then you want to return Resource Not Found 404.

Valid URLs:

xyz.com/hotels
xyz.com/hotels/335

Invalid URL:

xyz.com/hotels/501

Define the controller as below:

@Controller
@RequestMapping("/hotels")
public class HotelController {

    @RequestMapping(method=RequestMethod.GET)
    public ModelAndView getHotels(){
        System.out.println("Return List of Hotels");
        ModelAndView model = new ModelAndView("hotel");
        ArrayList<Hotel> hotels = null;
        // Fetch All Hotels
        model.addObject("hotels", hotels);
        return model;
    }

    @RequestMapping(value = "/{hotelId}", method=RequestMethod.GET)
    public ModelAndView getHotels(@PathVariable("hotelId") Integer hotelId){
        if (hotelId > 500){
            throw new ResourceNotFoundException();
        }
        ModelAndView model = new ModelAndView("hotel");
        Hotel hotel = null;
        // get Hotel
        hotel = new Hotel(hotelId, "test Hotel"+hotelId);
        model.addObject("hotel", hotel);

        return model;
    }
   }

Note @RequestMapping given as /hotels, this way the getHotels() method would be invoked when the URL is

xyz.com/hotels

and the request method is GET.

If the URL contains id information like xyz.com/hotels/2 then the getHotels() with the @PathVariable would be invoked.

Now, if you want to return 404 when the hotel id is greater than 500, throw a custom Exception. Notice ResponseStatus.NOT_FOUND is annotated in the custom exception handler method below:

@ResponseStatus(value = HttpStatus.NOT_FOUND)
class ResourceNotFoundException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public ResourceNotFoundException(){
        super();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

HttpStatus.NOT_FOUND written in the above method can be imorted as org.springframework.http.HttpStatus.NOT_FOUND
2

Check out Spring's @PathVariable. One relevant tutorial is this

From the above tutorial you can see that you can write code like the following (where you can see the flexibility of Spring MVC)

@Controller
public class TestController {
     @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)
     public String getLogin(@PathVariable("userId") String userId,
         @PathVariable("roleId") String roleId){
         System.out.println("User Id : " + userId);
         System.out.println("Role Id : " + roleId);
         return "hello";
     }
     @RequestMapping(value="/product/{productId}",method = RequestMethod.GET)
     public String getProduct(@PathVariable("productId") String productId){
           System.out.println("Product Id : " + productId);
           return "hello";
     }
     @RequestMapping(value="/javabeat/{regexp1:[a-z-]+}",
           method = RequestMethod.GET)
     public String getRegExp(@PathVariable("regexp1") String regexp1){
           System.out.println("URI Part 1 : " + regexp1);
           return "hello";
     }
}

A Controller is not limited to using only @PathVariable. It can use a combination of @PathVariable and @RequestVariable that fits the particular needs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.