I have a requirement to implement an HTTP PATCH method in a Spring MVC application. I followed this tutorial: https://www.baeldung.com/http-put-patch-difference-spring.
This is the piece of code:
#RequestMapping(value = "/heavyresource/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> partialUpdateGeneric(
#RequestBody Map<String, Object> updates,
#PathVariable("id") String id) {
heavyResourceRepository.save(updates, id);
return ResponseEntity.ok("resource updated");
}
The problem is that my repository (JPARepository) does not have a method "save" where I can pass a map and an id.
I tried this implementation on my own:
#PatchMapping("/heavyresource/{id}")
public Beer patchUpdate(#RequestBody HeavyResource heavyResource) {
return heavyResourceRepository.save(heavyResource);
}
But it does not work properly because if I pass only one property (that's the point in PATCH) it let's all the others properties as null and I need to update only the property that was passed. Even thinking in DTOs I was not able to implement.
Thanks!
Related
I have a Spring MVC controller but I'm not sure that it is a good or bad design. As far as I know, api versioning is missing but apart from that I implemented Swagger for documentation and added SpringSecurity and tried to follow YARAS(Yet Another RESTful API Standard) to build it but I need another eye on that to comment it.
#Slf4j
#Controller
#RequestMapping
#RequiredArgsConstructor
public class XGameController implements GameController {
private final GameService gameService;
private final ObjectMapper mapper;
#RequestMapping(value = "/", method= RequestMethod.GET)
public String index() {
return "game";
}
#RequestMapping(value = "/login", method= RequestMethod.GET)
public String login() {
return "login";
}
#Secured("ROLE_USER")
#RequestMapping(value = "/games", method= RequestMethod.POST)
public String initializeGame(Model model) {
log.info("New XGame is initializing...");
Game game = new Game();
game = gameService.initializeGame(game.getId());
try {
model.addAttribute("game", mapper.writeValueAsString(game));
} catch (JsonProcessingException e) {
log.error(e.getMessage());
}
log.info("New XGame is initialized successfully!");
return "game";
}
#Secured("ROLE_USER")
#RequestMapping(value = "/games/{gameId}", method= RequestMethod.PUT)
public #ResponseBody Game play(#PathVariable("gameId") String gameId,
#RequestParam Integer pitNumber,
#RequestParam String action) {
log.info("Sowing stone is triggered...");
return gameService.executeGameRules(UUID.fromString(gameId), pitNumber);
}
#RequestMapping(value = "/403", method= RequestMethod.GET)
public String error403() {
return "/error/403";
}
}
My swagger snapshot;
I would make some changes.
In /games/{gameId} I would use PATCH instead of PUT. The reason is that PUT is intended to completely replace the resource (in your case, the Game). This does not seem to be what you are doing in this endpoint. PATCH is intended to partially update a resource, which seems much more suited to what you are doing here.
Still in /games/{gameId} I would use the request body to provide the needed data instead of query parameters. It simply doesn't seem right. Query parameters are way more suited to GET requests than to POST, PUT or PATCH.
I would rename /403 to something else that actually gives some context about what 403 is. Having said this, I would go with /error-pages/403. Additionally, I would also consider removing this endpoint from the swagger specification.
Other than this, it seems fine to me.
Some advices :
Use a path that represents the context or the idea of your controller and you can add the version
#RequestMapping("/V1/xgame")
Use specialized annotations such as : #GetMapping, #PostMapping etc...
For /403 use a meaning full name such as /errors
Use custom message that you will return to the users. For that you need a ControllerAdvice.
Google on patterns and best practices Rest API design
Read some books for better undertanding.
Firstly, instead of #RequestMapping use a specific Mapping(Get, Post,etc.) and the use of type of mapping is up to you which you find more particular to the cause of using it
if you are redirecting from a page to homepage try to use return "redirect:"/url"" instead of just returning HTML file directly.
Rename your method for error, RequestMapping value to some more reasonable name.
instead of using return "/error/403"
use return "redirect:/error/403"
In spring doc, I can get following explanations for the difference of the spring mvc and spring rest.
Spring REST architecture is also based on Spring MVC, slightly making the difference on the View part. Traditional Spring MVC relies on the View technology to render the model data, the Spring REST architecture also does the same, except that the model object is set directly into the HTTP response, which the #ResponseBody converts into JSON/XML automatically. The output of a RESTful web service has to be a JSON or an XML, a standard format that could be easily handled across different consumer application platforms.
But in https://en.wikipedia.org/wiki/Representational_state_transfer.
It has a couple of feactures except for the json response like the rest will use the HTTP PUT/DELETE/POST method to manipulate resource.
I was wondering if below spring controller can be treated as a restful service. I have used #RestController to return json response, but did not use any other rest features.
#RestController
#RequestMapping(value = "/employee")
public class EmployeeController {
#RequestMapping(value = RequestAction.LOADLIST, method = RequestMethod.POST)
public List<Employee> list(#RequestBody Employee bo) {
System.out.println(bo);
return employeeList;
}
#RequestMapping(value = RequestAction.LOAD, method = RequestMethod.POST)
public Employee getEmployee(
#RequestBody Employee input) {
for (Employee employee : employeeList) {
if (employee.getId().equals(input.getId())) {
return employee;
}
}
return input;
}
#RequestMapping(value = RequestAction.ADD, method = RequestMethod.POST)
public Employee addEmployee(#RequestBody Employee bo) {
System.out.println(bo);
return bo;
}
#RequestMapping(value = RequestAction.UPDATE, method = RequestMethod.POST)
public Employee updateEmployee(#RequestBody Employee bo) {
System.out.println(bo);
for (Employee employee : employeeList) {
if (employee.getId().equals(bo.getId())) {
employee.setName(bo.getName());
return employee;
}
}
return bo;
}
}
Your example script is not REST because it change the url for each task, and use always POST verb. Spring REST use different HTTP verbs (GET, POST, DELETE) to differentiate the action. A few times sharing the same url.
Example:
#RestController
#RequestMapping("/users")
public class UsersController {
#GetMapping
public List<User> index() {...}
#GetMapping("{id}")
public User show(...) {...}
#PostMapping
public User create(...) {...}
#PutMapping("{id}")
public User update(...) {...}
#DeleteMapping("{id}")
public void delete(...) {...}
}
Your example is not following the conventionals of a REST API (e.g. GET for retrieval, POST for create, PUT for full update, PATCH for partial update, etc.), but it does not mean, that you can't. As others stated above, you might just got confused with the term. REST is a protocol and it has lots of conventionals for service usages, which if you follow, you can say that your service is REST or RESTful.
This page is the simple best source of tutoring you in this area:
https://restfulapi.net
More importantly this, when we are considering your example: https://restfulapi.net/http-methods/
I also check it sometimes.
In my Spring Boot web application I have a JPA entity Medium that records information about uploaded files.
I have a basic Spring Data Rest repository to handle the generic operations:
#RepositoryRestResource(path = "/media")
public interface MediumRepository extends CrudRepository<Medium, Long> {
}
However, I need the client to upload a file using HTTP multipart upload, then create a Medium record and return it in the response. The structure of the response should be the same as calling repository.save(). What I cannot figure out is how to have the HATEOAS metadata added. Obviously, if I just return
return mediumRepository.save(medium);
it will return a basic JSON representation of the entity, no HATEOAS. I already learned that I should probably use a PersistentEntityResourceAssembler.
So, my current controller code is:
#RestController
#RequestMapping("/upload")
public class MediaEndpoint {
#Autowired
private MediumRepository mediumRepository;
#RequestMapping(method = POST)
public PersistentEntityResource uploadMedium(
#RequestPart MultipartFile data,
PersistentEntityResourceAssembler persistentEntityResourceAssembler) {
Medium medium = new Medium();
// setup of the medium instance
Medium savedMedium = mediumRepository.save(medium);
return persistentEntityResourceAssembler.toResource(savedMedium);
}
}
However, I cannot get the persistentEntityResourceAssembler injected into the method - I'm getting
Failed to instantiate [org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.<init>()
How can I implement this?
Following Cepr0's answer, I changed my controller to a #RepositoryRestController, but I got an exception
Circular view path [upload]: would dispatch back to the current handler URL [/upload] again.
Check your ViewResolver setup! (Hint: This may be the result of an unspecified view,
due to default view name generation.)
I found that RepositoryRestControllers are not annotated with #ResponseBody and should return a ResponseEntity, so I changed my code to the following:
#RepositoryRestController
#RequestMapping("/upload")
public class MediaEndpoint {
#Autowired
private MediumRepository mediumRepository;
#RequestMapping(method = POST)
public ResponseEntity<PersistentEntityResource> uploadMedium(
#RequestPart MultipartFile data,
PersistentEntityResourceAssembler persistentEntityResourceAssembler) {
Medium medium = new Medium();
// setup of the medium instance
Medium savedMedium = mediumRepository.save(medium);
return ResponseEntity.ok(persistentEntityResourceAssembler.toResource(savedMedium));
}
}
This gives me a nice JSON response with HATEOAS metadata.
Alternatively, annotating the method or the controller with #ResponseBody works the same way.
Try to use #RepositoryRestController instead of #RestController.
I'm running a webapp in Spring Web MVC 3.0 and I have a number of controller methods whose signatures are roughly as follows:
#RequestMapping(value = "/{level1}/{level2}/foo", method = RequestMethod.POST)
public ModelAndView createFoo(#PathVariable long level1,
#PathVariable long level2,
#RequestParam("foo_name") String fooname,
#RequestParam(value = "description", required = false) String description);
I'd like to add some validation - for example, description should be limited to a certain length or fooname should only contain certain characters. If this validation fails, I want to return a message to the user rather than just throw some unchecked exception (which would happen anyway if I let the data percolate down to the DAO layer). I'm aware of JSR303 but have not worked with it and don't quite understand how to apply it in a Spring context.
From what I understand, another option would be to bind the #RequestBody to an entire domain object and add validation constraints there, but currently my code is set up to accept individual parameters as shown above.
What is the most straightforward way to apply validation to input parameters using this approach?
This seems to be possible now (tried with Spring 4.1.2), see https://raymondhlee.wordpress.com/2015/08/29/validating-spring-mvc-request-mapping-method-parameters/
Extract from above page:
Add MethodValidationPostProcessor to Spring #Configuration class:
#Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
Add #Validated to controller class
Use #Size just before #RequestParam
#RequestMapping("/hi")
public String sayHi(#Size(max = 10, message = "name should at most 10 characters long") #RequestParam("name") String name) {
return "Hi " + name;
}
Handle ConstraintViolationException in an #ExceptionHandler method
There's nothing built in to do that, not yet anyway. With the current release versions you will still need to use the WebDataBinder to bind your parameters onto an object if you want automagic validation. It's worth learning to do if you're using SpringMVC, even if it's not your first choice for this task.
It looks something like this:
public ModelAndView createFoo(#PathVariable long level1,
#PathVariable long level2,
#Valid #ModelAttribute() FooWrapper fooWrapper,
BindingResult errors) {
if (errors.hasErrors() {
//handle errors, can just return if using Spring form:error tags.
}
}
public static class FooWrapper {
#NotNull
#Size(max=32)
private String fooName;
private String description;
//getset
}
If you have Hibernate Validator 4 or later on your classpath and use the default dispatcher setup it should "Just work."
Editing since the comments were getting kind of large:
Any Object that's in your method signature that's not one of the 'expected' ones Spring knows how to inject, such as HttpRequest, ModelMap, etc, will get data bound. This is accomplished for simple cases just by matching the request param names against bean property names and calling setters. The #ModelAttribute there is just a personal style thing, in this case it isn't doing anything. The JSR-303 integration with the #Valid on a method parameter wires in through the WebDataBinder. If you use #RequestBody, you're using an object marshaller based on the content type spring determines for the request body (usually just from the http header.) The dispatcher servlet (AnnotationMethodHandlerAdapter really) doesn't have a way to 'flip the validation switch' for any arbitrary marshaller. It just passes the web request content along to the message converter and gets back a Object. No BindingResult object is generated, so there's nowhere to set the Errors anyway.
You can still just inject your validator into the controller and run it on the object you get, it just doesn't have the magic integration with the #Valid on the request parameter populating the BindingResult for you.
If you have multiple request parameters that need to be validated (with Http GET or POST). You might as well create a custom model class and use #Valid along with #ModelAttribute to validate the parameters. This way you can use Hibernate Validator or javax.validator api to validate the params. It goes something like this:
Request Method:
#RequestMapping(value="/doSomething", method=RequestMethod.GET)
public Model dosomething(#Valid #ModelAttribute ModelRequest modelRequest, BindingResult result, Model model) {
if (result.hasErrors()) {
throw new SomeException("invalid request params");
}
//to access the request params
modelRequest.getFirstParam();
modelRequest.getSecondParam();
...
}
ModelRequest class:
class ModelRequest {
#NotNull
private String firstParam;
#Size(min = 1, max = 10, message = "You messed up!")
private String secondParam;
//Setters and getters
public void setFirstParam (String firstParam) {
this.firstParam = firstParam;
}
public String getFirstParam() {
return firstParam;
}
...
}
Hope that helps.
The question sounds weird, I'm playing around with Spring MVC and am trying to move between two pages and basically I'm creating a JSP page using Spring Form JSTL's so it just uses a POST, and I use a controller to move from one page to the next. But Models are lost from page to page, and I'd like to hide the actual variable so QueryStrings are out of the question(as
far as I know). I know I can use a InternalResourceView, but only allows me to use a model.
I want to transfer a variable that will be exclusive to that page, what's the best way without a model or using QueryStrings?
I was planning on using SessionAttribute to easily define them, but was wondering, how do you remove a SessionAttribute created variable? I tried HttpSession.removeAttribute and it didn't seem to work.
You can also use SessionStatus.setComplete() like this:
#RequestMapping(method = RequestMethod.GET, value="/clear")
public ModelAndView clear(SessionStatus status, ModelMap model, HttpServletRequest request) {
model.clear();
status.setComplete();
return new ModelAndView("somePage");
}
or DefaultSessionAttributeStore.cleanUpAttribute like this:
#RequestMapping(method = RequestMethod.GET, value="/clear")
public ModelAndView clear(DefaultSessionAttributeStore status, WebRequest request, ModelMap model) {
model.remove("mySessionVar");
status.cleanupAttribute(request, "mySessionVar");
return new ModelAndView("somePage");
}
I use it like this on one of my forms that has mulitple sessionAttributes and I want to remove only one of them.
Yes... HttpSession.removeAttribute
You can use the removeAttribute method from the HttpSession class.
you can use WebRequest.removeAttribute(String name, int scope) that works with Spring #SessionAttributes. Quote from #SessionAttributes javadoc - "Alternatively, consider using the attribute management capabilities of the generic {#link org.springframework.web.context.request.WebRequest} interface."
Also look at my example.
#Controller
#SessionAttributes({"sessionAttr"})
public class MyController {
#ModelAttribute("sessionAttr")
public Object defaultSessionAttr() {
return new Object();
}
#RequestMapping(value = "...", method = RequestMethod.GET)
public String removeSessionAttr(WebRequest request, Model model) {
request.removeAttribute("sessionAttr", WebRequest.SCOPE_SESSION);
model.addAttribute("sessionAttr", defaultSessionAttr());
return "myView";
}
}