Thymeleaf multiple submit button in one form

You can create separate methods with different @RequestMappings using the params variable. @RequestMapping(value=”/edit”, method=RequestMethod.POST, params=”action=save”) public ModelAndView save() {} @RequestMapping(value=”/edit”, method=RequestMethod.POST, params=”action=cancel”) public ModelAndView cancel() {}

passing JSON data to a Spring MVC controller

Add the following dependencies <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.7</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.7</version> </dependency> Modify request as follows $.ajax({ url:urlName, type:”POST”, contentType: “application/json; charset=utf-8”, data: jsonString, //Stringified Json Object async: false, //Cross-domain requests and dataType: “jsonp” requests do not support synchronous operation cache: false, //This will force requested pages not to be cached by the … Read more

How to unit test a Spring MVC controller using @PathVariable?

I’d call what you’re after an integration test based on the terminology in the Spring reference manual. How about doing something like: import static org.springframework.test.web.ModelAndViewAssert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({/* include live config here e.g. “file:web/WEB-INF/application-context.xml”, “file:web/WEB-INF/dispatcher-servlet.xml” */}) public class MyControllerIntegrationTest { @Inject private ApplicationContext applicationContext; private MockHttpServletRequest request; private MockHttpServletResponse response; private HandlerAdapter handlerAdapter; private MyController controller; … Read more

What does the @Valid annotation indicate in Spring?

It’s for validation purposes. Validation It is common to validate a model after binding user input to it. Spring 3 provides support for declarative validation with JSR-303. This support is enabled automatically if a JSR-303 provider, such as Hibernate Validator, is present on your classpath. When enabled, you can trigger validation simply by annotating a … Read more

Trigger 404 in Spring-MVC controller?

Since Spring 3.0 you also can throw an Exception declared with @ResponseStatus annotation: @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { … } @Controller public class SomeController { @RequestMapping….. public void handleCall() { if (isFound()) { // whatever } else { throw new ResourceNotFoundException(); } } }