Issue
I have written a controller in my application that finds an item that belongs to the user and returns it. However, when the request contains the ID of an item that does not belong to the user, my controller is returning an empty object. How can I force the application to issue a 403 error instead?
Here is a simplified of the code for the controller:
@Controller
@RequestMapping("/item")
public class ItemController {
@Autowired
private ItemService itemService;
@GetMapping(value="/getItem", produces = MediaType.TEXT_PLAIN_VALUE)
public String getItem(@RequestParam("itemId") int itemId,
HttpServletRequest request,
Model theModel) {
// get the username from the HTTP Request
Principal principal = request.getUserPrincipal();
String theUsername = principal.getName();
// create model attribute to bind form data
Item theItem = itemService.getItem(itemId);
if (theUsername.equals(theItem.getUserProfile().getUsername())) {
theModel.addAttribute("item", theItem);
} else {
theModel.addAttribute("item", new Item());
}
return "json/item";
}
}
P.S. Please note that the ItemService
is only a middle layer that connects to the data layer and fetches the data to return.
P.S. I am aware that the design may not follow the best practices. Please feel free to highlight any design issues in the comments, but avoid ranting the post about them.
Solution
You can do it in couple of ways. You can set the status code in the controller class methods like this
@ResponseStatus(HttpStatus.SC_FORBIDDEN)
public Response doSomething() {
//do some thing here and return
}
If this doesn't suits your requirement you can handle this in an exceptional handler method like this.
@ResponseStatus(code = HttpStatus.SC_FORBIDDEN)
class CustomException extends RuntimeException {
//Handle something here;
}
For better information follow this
Answered By - raj240