From 416c103cdae797b9314cccb9ea1f43b36b4d6b17 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Fri, 24 May 2019 15:01:37 -0300 Subject: [PATCH 01/13] Created new empty module spring-mvc-basics --- .gitignore | 4 + spring-mvc-basics/README.md | 8 + spring-mvc-basics/pom.xml | 299 ++++++++++++++++++ .../com/baeldung/config/AppInitializer.java | 27 ++ .../src/main/resources/annotations.properties | 0 .../SpringContextIntegrationTest.java | 21 ++ 6 files changed, 359 insertions(+) create mode 100644 spring-mvc-basics/README.md create mode 100644 spring-mvc-basics/pom.xml create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java create mode 100644 spring-mvc-basics/src/main/resources/annotations.properties create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java diff --git a/.gitignore b/.gitignore index 50cb889e5b..e84b19c168 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ */bin/* +bin/ *.class @@ -21,6 +22,9 @@ *.iws out/ +# VSCode +.vscode/ + # Mac .DS_Store diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md new file mode 100644 index 0000000000..46681afb48 --- /dev/null +++ b/spring-mvc-basics/README.md @@ -0,0 +1,8 @@ +========= + +## Spring MVC Basics with Java Configuration Example Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml new file mode 100644 index 0000000000..777537b0b9 --- /dev/null +++ b/spring-mvc-basics/pom.xml @@ -0,0 +1,299 @@ + + 4.0.0 + com.baeldung + spring-mvc-basics + 0.1-SNAPSHOT + spring-mvc-basics + war + + + parent-spring-5 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + org.springframework + spring-webmvc + ${spring.version} + + + javax.servlet + javax.servlet-api + 4.0.1 + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.3 + + + javax.servlet + jstl + ${jstl.version} + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + org.aspectj + aspectjrt + 1.9.1 + + + org.aspectj + aspectjweaver + 1.9.1 + + + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + + commons-io + commons-io + + + + + net.sourceforge.htmlunit + htmlunit + 2.32 + + + commons-logging + commons-logging + + + commons-io + commons-io + + + + + commons-io + commons-io + ${commons-io.version} + + + + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + + + org.thymeleaf + thymeleaf + ${thymeleaf.version} + + + + com.jayway.jsonpath + json-path + test + 2.4.0 + + + org.springframework + spring-test + ${spring.version} + test + + + + + org.apache.poi + poi-ooxml + ${poi.version} + + + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + + + + + com.google.code.gson + gson + 2.8.5 + + + org.springframework + spring-websocket + ${spring.version} + + + + org.springframework + spring-messaging + ${spring.version} + + + + + spring-mvc-basics + + + src/main/resources + true + + + + + + + maven-resources-plugin + ${maven-resources-plugin.version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + **/*IntTest.java + + + **/*LiveTest.java + + + + + + + json + + + + + org.codehaus.cargo + cargo-maven2-plugin + + false + + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + + + + + + 3.0.9.RELEASE + + + 6.0.10.Final + 5.1.40 + + + 6.0.10.Final + + + 19.0 + 3.5 + 1.3.2 + 2.5 + 2.2.0 + + + 4.4.5 + 4.5.2 + 3.0.7 + 2.23 + + + 3.2.2 + 2.7 + 1.6.1 + 3.1.0 + + + 1.9.1 + + + 3.16-beta1 + + 3.0.1-b06 + + + + + diff --git a/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java b/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java new file mode 100644 index 0000000000..a76d955e4f --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java @@ -0,0 +1,27 @@ +package com.baeldung.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class AppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + + context.scan("com.baeldung"); + + container.addListener(new ContextLoaderListener(context)); + + ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/"); + } + +} diff --git a/spring-mvc-basics/src/main/resources/annotations.properties b/spring-mvc-basics/src/main/resources/annotations.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..d8cf4cfc0d --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.config.AppInitializer; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppInitializer.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } +} From 20c2c2dd7634c37d15ac405287bd8e9b52756f00 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sat, 25 May 2019 12:03:17 -0300 Subject: [PATCH 02/13] * moved 'Spring MVC Tutorial' code from spring-mvc-java to new module spring-mvc-basics * cleaned spring-mvc-basics pom --- spring-mvc-basics/.gitignore | 13 + spring-mvc-basics/README.md | 1 + spring-mvc-basics/pom.xml | 253 +----------------- .../baeldung/spring/web/config/WebConfig.java | 33 +++ .../web/controller/SampleController.java | 13 + .../src/main/resources/annotations.properties | 0 .../src/main/resources/mvc-configuration.xml | 20 ++ .../src/main/webapp/WEB-INF/view/index.jsp | 7 + .../src/main/webapp/WEB-INF/view/sample.jsp | 7 + spring-mvc-java/README.md | 1 - spring-mvc-java/pom.xml | 1 - 11 files changed, 103 insertions(+), 246 deletions(-) create mode 100644 spring-mvc-basics/.gitignore create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java delete mode 100644 spring-mvc-basics/src/main/resources/annotations.properties create mode 100644 spring-mvc-basics/src/main/resources/mvc-configuration.xml create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp diff --git a/spring-mvc-basics/.gitignore b/spring-mvc-basics/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-mvc-basics/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 46681afb48..63d046de2d 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -6,3 +6,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: +- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index 777537b0b9..8217421948 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -1,4 +1,5 @@ - 4.0.0 com.baeldung @@ -15,136 +16,33 @@ - - org.springframework + + org.springframework spring-webmvc ${spring.version} javax.servlet javax.servlet-api - 4.0.1 + ${javax.servlet-api.version} javax.servlet.jsp javax.servlet.jsp-api - 2.3.3 + ${javax.jsp-api.version} javax.servlet jstl ${jstl.version} - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - org.aspectj - aspectjrt - 1.9.1 - - - org.aspectj - aspectjweaver - 1.9.1 - - - - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - - commons-io - commons-io - - - - - net.sourceforge.htmlunit - htmlunit - 2.32 - - - commons-logging - commons-logging - - - commons-io - commons-io - - - - - commons-io - commons-io - ${commons-io.version} - - - - - org.thymeleaf - thymeleaf-spring4 - ${thymeleaf.version} - - - org.thymeleaf - thymeleaf - ${thymeleaf.version} - - - - com.jayway.jsonpath - json-path - test - 2.4.0 - org.springframework spring-test - ${spring.version} + ${spring.version} test - - - - org.apache.poi - poi-ooxml - ${poi.version} - - - - - org.hibernate.validator - hibernate-validator - ${hibernate-validator.version} - - - - - - com.google.code.gson - gson - 2.8.5 - - - org.springframework - spring-websocket - ${spring.version} - - - - org.springframework - spring-messaging - ${spring.version} - @@ -155,144 +53,11 @@ true - - - - - maven-resources-plugin - ${maven-resources-plugin.version} - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - - - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntegrationTest.java - **/*IntTest.java - - - **/*LiveTest.java - - - - - - - json - - - - - org.codehaus.cargo - cargo-maven2-plugin - - false - - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - - - - - - - - 3.0.9.RELEASE - - - 6.0.10.Final - 5.1.40 - - - 6.0.10.Final - - - 19.0 - 3.5 - 1.3.2 - 2.5 - 2.2.0 - - - 4.4.5 - 4.5.2 - 3.0.7 - 2.23 - - - 3.2.2 - 2.7 - 1.6.1 - 3.1.0 - - - 1.9.1 - - - 3.16-beta1 - - 3.0.1-b06 - + 4.0.1 + 2.3.3 diff --git a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java new file mode 100644 index 0000000000..6ee20d7a6b --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.spring.web.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/") + .setViewName("index"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } +} \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java new file mode 100644 index 0000000000..c13986e005 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java @@ -0,0 +1,13 @@ +package com.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class SampleController { + @GetMapping("/sample") + public String showForm() { + return "sample"; + } + +} diff --git a/spring-mvc-basics/src/main/resources/annotations.properties b/spring-mvc-basics/src/main/resources/annotations.properties deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-mvc-basics/src/main/resources/mvc-configuration.xml b/spring-mvc-basics/src/main/resources/mvc-configuration.xml new file mode 100644 index 0000000000..7505614c99 --- /dev/null +++ b/spring-mvc-basics/src/main/resources/mvc-configuration.xml @@ -0,0 +1,20 @@ + + + + + + + + + /WEB-INF/view/ + + + .jsp + + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp new file mode 100644 index 0000000000..4f4eb0068d --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the index view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp new file mode 100644 index 0000000000..7cc14b5dcd --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample view

+ + \ No newline at end of file diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 3deeb21afc..2c0f594bd2 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -29,6 +29,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) -- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 853d8db64c..ffa76d405d 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -34,7 +34,6 @@ javax.servlet jstl ${jstl.version} - From 33d0ac573830369ee113b3689d16b1d775448594 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sun, 26 May 2019 15:30:12 -0300 Subject: [PATCH 03/13] * Moved Controller vs RestController article code from spring-mvc-java to spring-mvc-basics * now using jupiter tests for the tests involved * fixed error in involved test --- spring-mvc-basics/README.md | 1 + spring-mvc-basics/pom.xml | 14 +++++++ .../main/java/com/baeldung/model/Book.java | 42 +++++++++++++++++++ .../web/controller/SimpleBookController.java | 0 .../controller/SimpleBookRestController.java | 0 .../SpringContextIntegrationTest.java | 2 +- .../SimpleBookControllerIntegrationTest.java | 8 ++-- ...mpleBookRestControllerIntegrationTest.java | 12 +++--- spring-mvc-java/README.md | 1 - 9 files changed, 66 insertions(+), 14 deletions(-) create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/model/Book.java rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/SimpleBookController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java (90%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java (85%) diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 63d046de2d..aa1fffdf42 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -7,3 +7,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) +- [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index 8217421948..cb9f1be9eb 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -36,6 +36,13 @@ jstl ${jstl.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + org.springframework @@ -43,6 +50,12 @@ ${spring.version} test + + com.jayway.jsonpath + json-path + test + ${jayway.json-path.version} + @@ -58,6 +71,7 @@ 4.0.1 2.3.3 + 2.4.0 diff --git a/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java b/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java new file mode 100644 index 0000000000..bdfa1d835a --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java @@ -0,0 +1,42 @@ +package com.baeldung.model; + +public class Book { + + private int id; + private String author; + private String title; + + public Book() { + } + + public Book(int id, String author, String title) { + this.id = id; + this.author = author; + this.title = title; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java diff --git a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java index d8cf4cfc0d..511e56aeab 100644 --- a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java similarity index 90% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java index 23be3a1655..87d70c2d29 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java @@ -5,19 +5,17 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import com.baeldung.web.controller.SimpleBookController; - public class SimpleBookControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; - @Before + @BeforeEach public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java similarity index 85% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java index c5bd53f1a7..294943f2e2 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java @@ -5,27 +5,25 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import com.baeldung.web.controller.SimpleBookController; - public class SimpleBookRestControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; - @Before + @BeforeEach public void setup() { - this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); + this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookRestController()).build(); } @Test public void givenBookId_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc - .perform(get("/books/42")) + .perform(get("/books-rest/42")) .andExpect(status().isOk()) .andExpect(content().contentType(CONTENT_TYPE)) .andExpect(jsonPath("$.id").value(42)); diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 2c0f594bd2..e39ddd8af7 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -24,7 +24,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) - [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) -- [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) From ee4953b7ef831d4205e505225497adb4073f5793 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sun, 26 May 2019 17:42:54 -0300 Subject: [PATCH 04/13] * Added example and test for "using @ResponseStatus" article in the spring-mvc-basics module --- spring-mvc-basics/README.md | 1 + .../ResponseStatusRestController.java | 48 +++++++++++++++++ ...seStatusRestControllerIntegrationTest.java | 52 +++++++++++++++++++ spring-mvc-java/README.md | 1 - 4 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index aa1fffdf42..c8a0ac6508 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) +- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java new file mode 100644 index 0000000000..4cc7589bc8 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java @@ -0,0 +1,48 @@ +package com.baeldung.web.controller; + +import java.util.concurrent.ThreadLocalRandom; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.model.Book; + +@RestController +public class ResponseStatusRestController { + + @GetMapping("/teapot") + @ResponseStatus(HttpStatus.I_AM_A_TEAPOT) + public void teaPot() { + } + + @GetMapping("empty") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void emptyResponse() { + } + + @GetMapping("empty-no-responsestatus") + public void emptyResponseWithoutResponseStatus() { + } + + @PostMapping("create") + @ResponseStatus(HttpStatus.CREATED) + public Book createEntity() { + // here we would create and persist an entity + int randomInt = ThreadLocalRandom.current() + .nextInt(1, 100); + Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); + return entity; + } + + @PostMapping("create-no-responsestatus") + public Book createEntityWithoutResponseStatus() { + // here we would create and persist an entity + int randomInt = ThreadLocalRandom.current() + .nextInt(1, 100); + Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); + return entity; + } +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java new file mode 100644 index 0000000000..1f37a3750c --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class ResponseStatusRestControllerIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new ResponseStatusRestController()) + .build(); + } + + @Test + public void whenTeapotEndpointCalled_thenTeapotResponseObtained() throws Exception { + this.mockMvc.perform(get("/teapot")) + .andExpect(status().isIAmATeapot()); + } + + @Test + public void whenEmptyNoContentEndpointCalled_thenNoContentResponseObtained() throws Exception { + this.mockMvc.perform(get("/empty")) + .andExpect(status().isNoContent()); + } + + @Test + public void whenEmptyWithoutResponseStatusEndpointCalled_then200ResponseObtained() throws Exception { + this.mockMvc.perform(get("/empty-no-responsestatus")) + .andExpect(status().isOk()); + } + + @Test + public void whenCreateWithCreatedEndpointCalled_thenCreatedResponseObtained() throws Exception { + this.mockMvc.perform(post("/create")) + .andExpect(status().isCreated()); + } + + @Test + public void whenCreateWithoutResponseStatusEndpointCalled_thenCreatedResponseObtained() throws Exception { + this.mockMvc.perform(post("/create-no-responsestatus")) + .andExpect(status().isOk()); + } + +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index e39ddd8af7..4d1a7c172c 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -26,7 +26,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) -- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) From ed7630c2d092cc527dd5274bfb954de7910c10c5 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sun, 26 May 2019 19:08:28 -0300 Subject: [PATCH 05/13] Moved ViewResolver article related code from spring-mvc-java to spring-mvc-basics --- spring-mvc-basics/README.md | 3 +- spring-mvc-basics/pom.xml | 18 ++++++++-- .../baeldung/spring/web/config/WebConfig.java | 19 +++++++++++ .../web/controller/SampleController.java | 13 +++++++- .../src/main/resources/views.properties | 3 ++ .../src/main/resources/views.xml | 18 +++++----- .../src/main/webapp/WEB-INF/view2/sample2.jsp | 7 ++++ .../src/main/webapp/WEB-INF/view3/sample3.jsp | 7 ++++ .../controller/SampleControllerLiveTest.java | 33 +++++++++++++++++++ spring-mvc-java/README.md | 1 - .../baeldung/spring/web/config/WebConfig.java | 19 ----------- .../src/main/resources/views.properties | 3 -- 12 files changed, 108 insertions(+), 36 deletions(-) create mode 100644 spring-mvc-basics/src/main/resources/views.properties rename {spring-mvc-java => spring-mvc-basics}/src/main/resources/views.xml (65%) create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java delete mode 100644 spring-mvc-java/src/main/resources/views.properties diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index c8a0ac6508..15b19cc1d0 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -8,4 +8,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) -- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) \ No newline at end of file +- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) +- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) \ No newline at end of file diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index cb9f1be9eb..3bcf5bc4ca 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -36,12 +36,12 @@ jstl ${jstl.version} - + com.fasterxml.jackson.core jackson-databind - ${jackson.version} + ${jackson.version} @@ -56,6 +56,18 @@ test ${jayway.json-path.version} + + io.rest-assured + rest-assured + ${rest-assured.version} + test + + + org.hamcrest + hamcrest-all + ${hamcrest.version} + test + @@ -72,6 +84,8 @@ 4.0.1 2.3.3 2.4.0 + 4.0.0 + 1.3 diff --git a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 6ee20d7a6b..9fa9bd58db 100644 --- a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -3,12 +3,15 @@ package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; +import org.springframework.web.servlet.view.ResourceBundleViewResolver; +import org.springframework.web.servlet.view.XmlViewResolver; @EnableWebMvc @Configuration @@ -27,7 +30,23 @@ public class WebConfig implements WebMvcConfigurer { bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); + bean.setOrder(2); + return bean; + } + + @Bean + public ViewResolver resourceBundleViewResolver() { + final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); + bean.setBasename("views"); bean.setOrder(0); return bean; } + + @Bean + public ViewResolver xmlViewResolver() { + final XmlViewResolver bean = new XmlViewResolver(); + bean.setLocation(new ClassPathResource("views.xml")); + bean.setOrder(1); + return bean; + } } \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java index c13986e005..ce89669fde 100644 --- a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java @@ -5,9 +5,20 @@ import org.springframework.web.bind.annotation.GetMapping; @Controller public class SampleController { - @GetMapping("/sample") + + @GetMapping("/sample") public String showForm() { return "sample"; } + + @GetMapping("/sample2") + public String showForm2() { + return "sample2"; + } + + @GetMapping("/sample3") + public String showForm3() { + return "sample3"; + } } diff --git a/spring-mvc-basics/src/main/resources/views.properties b/spring-mvc-basics/src/main/resources/views.properties new file mode 100644 index 0000000000..06d042b446 --- /dev/null +++ b/spring-mvc-basics/src/main/resources/views.properties @@ -0,0 +1,3 @@ +sample2.(class)=org.springframework.web.servlet.view.JstlView +sample2.url=/WEB-INF/view2/sample2.jsp + diff --git a/spring-mvc-java/src/main/resources/views.xml b/spring-mvc-basics/src/main/resources/views.xml similarity index 65% rename from spring-mvc-java/src/main/resources/views.xml rename to spring-mvc-basics/src/main/resources/views.xml index 83bca5293d..a44d3deae4 100644 --- a/spring-mvc-java/src/main/resources/views.xml +++ b/spring-mvc-basics/src/main/resources/views.xml @@ -1,10 +1,10 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp new file mode 100644 index 0000000000..c826700a75 --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample2 view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp new file mode 100644 index 0000000000..b58a0973da --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample3 view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java new file mode 100644 index 0000000000..bd24bb6ff9 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java @@ -0,0 +1,33 @@ +package com.baeldung.web.controller; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.RestAssured; + +public class SampleControllerLiveTest { + + private static final String SERVICE_BASE_URL = "/spring-mvc-basics"; + + @Test + public void whenSampleEndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample") + .then() + .statusCode(HttpStatus.OK.value()); + } + + @Test + public void whenSample2EndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample2") + .then() + .statusCode(HttpStatus.OK.value()); + } + + @Test + public void whenSample3EndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample3") + .then() + .statusCode(HttpStatus.OK.value()); + } + +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 4d1a7c172c..c670b153cf 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -9,7 +9,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) - [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial) - [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial) -- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) - [Integration Testing in Spring](http://www.baeldung.com/integration-testing-in-spring) - [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables) - [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring) diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 191d721dfb..96b50f2c37 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -12,7 +12,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import org.springframework.context.support.ResourceBundleMessageSource; -import org.springframework.core.io.ClassPathResource; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; @@ -26,8 +25,6 @@ import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; -import org.springframework.web.servlet.view.ResourceBundleViewResolver; -import org.springframework.web.servlet.view.XmlViewResolver; import org.springframework.web.util.UrlPathHelper; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; @@ -110,22 +107,6 @@ public class WebConfig implements WebMvcConfigurer { return multipartResolver; } - - @Bean - public ViewResolver xmlViewResolver() { - final XmlViewResolver bean = new XmlViewResolver(); - bean.setLocation(new ClassPathResource("views.xml")); - bean.setOrder(1); - return bean; - } - - @Bean - public ViewResolver resourceBundleViewResolver() { - final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); - bean.setBasename("views"); - bean.setOrder(0); - return bean; - } @Override public void extendMessageConverters(final List> converters) { diff --git a/spring-mvc-java/src/main/resources/views.properties b/spring-mvc-java/src/main/resources/views.properties deleted file mode 100644 index 95687cb62a..0000000000 --- a/spring-mvc-java/src/main/resources/views.properties +++ /dev/null @@ -1,3 +0,0 @@ -sample.(class)=org.springframework.web.servlet.view.JstlView -sample.url=/WEB-INF/view/sample.jsp - From 802000d5453fb9000736959849fcbf043eb39629 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Fri, 14 Jun 2019 12:40:42 -0300 Subject: [PATCH 06/13] Migrated spring-mvc-basics to a Spring Boot project --- spring-mvc-basics/pom.xml | 81 +++++-------------- .../main/java/com/baeldung/Application.java | 11 +++ .../baeldung/spring/web/config/WebConfig.java | 10 +-- .../src/main/resources/application.properties | 1 + .../SpringContextIntegrationTest.java | 12 +-- .../controller/SampleControllerLiveTest.java | 2 +- 6 files changed, 41 insertions(+), 76 deletions(-) create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/Application.java create mode 100644 spring-mvc-basics/src/main/resources/application.properties diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index 3bcf5bc4ca..d04bdda8f6 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -1,3 +1,4 @@ + @@ -6,87 +7,49 @@ spring-mvc-basics 0.1-SNAPSHOT spring-mvc-basics - war + jar - parent-spring-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-spring-5 + ../parent-boot-2 - org.springframework - spring-webmvc - ${spring.version} + org.springframework.boot + spring-boot-starter-web + - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.jsp-api.version} + org.apache.tomcat.embed + tomcat-embed-jasper + provided javax.servlet jstl ${jstl.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - org.springframework - spring-test - ${spring.version} - test - - - com.jayway.jsonpath - json-path - test - ${jayway.json-path.version} - - - io.rest-assured - rest-assured - ${rest-assured.version} - test - - - org.hamcrest - hamcrest-all - ${hamcrest.version} + org.springframework.boot + spring-boot-starter-test test - spring-mvc-basics - - - src/main/resources - true - - + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.Application + JAR + + + - - - 4.0.1 - 2.3.3 - 2.4.0 - 4.0.0 - 1.3 - - diff --git a/spring-mvc-basics/src/main/java/com/baeldung/Application.java b/spring-mvc-basics/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..d58049fb35 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/Application.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 9fa9bd58db..a56dfe550f 100644 --- a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -1,11 +1,9 @@ package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -13,9 +11,9 @@ import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.ResourceBundleViewResolver; import org.springframework.web.servlet.view.XmlViewResolver; -@EnableWebMvc +//@EnableWebMvc +//@ComponentScan(basePackages = { "com.baeldung.web.controller" }) @Configuration -@ComponentScan(basePackages = { "com.baeldung.web.controller" }) public class WebConfig implements WebMvcConfigurer { @Override @@ -33,7 +31,7 @@ public class WebConfig implements WebMvcConfigurer { bean.setOrder(2); return bean; } - + @Bean public ViewResolver resourceBundleViewResolver() { final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); @@ -41,7 +39,7 @@ public class WebConfig implements WebMvcConfigurer { bean.setOrder(0); return bean; } - + @Bean public ViewResolver xmlViewResolver() { final XmlViewResolver bean = new XmlViewResolver(); diff --git a/spring-mvc-basics/src/main/resources/application.properties b/spring-mvc-basics/src/main/resources/application.properties new file mode 100644 index 0000000000..4de974142e --- /dev/null +++ b/spring-mvc-basics/src/main/resources/application.properties @@ -0,0 +1 @@ +server.servlet.context-path=/spring-mvc-basics \ No newline at end of file diff --git a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java index 511e56aeab..2feb9efce1 100644 --- a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,17 +1,9 @@ package com.baeldung; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; -import com.baeldung.config.AppInitializer; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { AppInitializer.class }, loader = AnnotationConfigContextLoader.class) -@WebAppConfiguration +@SpringBootTest public class SpringContextIntegrationTest { @Test diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java index bd24bb6ff9..0b958996c9 100644 --- a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java @@ -6,7 +6,7 @@ import org.springframework.http.HttpStatus; import io.restassured.RestAssured; public class SampleControllerLiveTest { - + private static final String SERVICE_BASE_URL = "/spring-mvc-basics"; @Test From 1e9364a7dc6663336c2616b3f0f3c12e3ab2ed70 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Fri, 14 Jun 2019 14:36:15 -0300 Subject: [PATCH 07/13] Moved code of article spring-handler-mappings from spring-mvc-java to spring-mvc-basics Renamed beans to avoid collisions --- spring-mvc-basics/README.md | 3 ++- .../handlermapping/BeanNameHandlerMappingController.java | 0 .../handlermapping/SimpleUrlMappingController.java | 0 .../web/controller/handlermapping/WelcomeController.java | 0 .../baeldung/config/BeanNameUrlHandlerMappingConfig.java | 7 +++---- .../com/baeldung/config/HandlerMappingDefaultConfig.java | 2 +- .../baeldung/config/HandlerMappingPrioritiesConfig.java | 6 +++--- .../com/baeldung/config/SimpleUrlHandlerMappingConfig.java | 6 +++--- .../BeanNameMappingConfigIntegrationTest.java | 0 .../HandlerMappingDefaultConfigIntegrationTest.java | 0 .../HandlerMappingPriorityConfigIntegrationTest.java | 0 .../SimpleUrlMappingConfigIntegrationTest.java | 0 .../src/test/resources/BeanNameUrlHandlerMappingConfig.xml | 0 .../resources/ControllerClassNameHandlerMappingConfig.xml | 0 .../test/resources/HandlerMappingConfiguringPriorities.xml | 0 .../src/test/resources/SimpleUrlHandlerMappingConfig.xml | 0 spring-mvc-java/README.md | 1 - 17 files changed, 12 insertions(+), 13 deletions(-) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java (76%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java (90%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java (89%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java (85%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/resources/BeanNameUrlHandlerMappingConfig.xml (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/resources/ControllerClassNameHandlerMappingConfig.xml (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/resources/HandlerMappingConfiguringPriorities.xml (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/resources/SimpleUrlHandlerMappingConfig.xml (100%) diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 15b19cc1d0..997e6a88df 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -9,4 +9,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) -- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) \ No newline at end of file +- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) +- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java similarity index 76% rename from spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java index e3dcb15de8..577825d8c5 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java @@ -1,11 +1,10 @@ package com.baeldung.config; -import com.baeldung.web.controller.handlermapping.WelcomeController; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; -import org.springframework.web.servlet.view.InternalResourceViewResolver; + +import com.baeldung.web.controller.handlermapping.WelcomeController; @Configuration public class BeanNameUrlHandlerMappingConfig { @@ -16,7 +15,7 @@ public class BeanNameUrlHandlerMappingConfig { } @Bean("/beanNameUrl") - public WelcomeController welcome() { + public WelcomeController welcomeBeanNameMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java similarity index 90% rename from spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java index d3a329a387..4072278fee 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java @@ -16,7 +16,7 @@ public class HandlerMappingDefaultConfig { } @Bean - public WelcomeController welcome() { + public WelcomeController welcomeDefaultMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java similarity index 89% rename from spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java index 2d80dbfeaf..c5fec171a7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java @@ -16,14 +16,14 @@ import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; public class HandlerMappingPrioritiesConfig { @Bean - BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() { + BeanNameUrlHandlerMapping beanNameUrlHandlerMappingOrder1() { BeanNameUrlHandlerMapping beanNameUrlHandlerMapping = new BeanNameUrlHandlerMapping(); beanNameUrlHandlerMapping.setOrder(1); return beanNameUrlHandlerMapping; } @Bean - public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { + public SimpleUrlHandlerMapping simpleUrlHandlerMappingOrder0() { SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); simpleUrlHandlerMapping.setOrder(0); Map urlMap = new HashMap<>(); @@ -37,7 +37,7 @@ public class HandlerMappingPrioritiesConfig { return new SimpleUrlMappingController(); } - @Bean("/welcome") + @Bean("/welcome-priorities") public BeanNameHandlerMappingController beanNameHandlerMapping() { return new BeanNameHandlerMappingController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java similarity index 85% rename from spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java index c7921c2706..7a366ecbd7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java @@ -18,7 +18,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; public class SimpleUrlHandlerMappingConfig { @Bean - public ViewResolver viewResolver() { + public ViewResolver viewResolverSimpleMappingConfig() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/"); viewResolver.setSuffix(".jsp"); @@ -29,13 +29,13 @@ public class SimpleUrlHandlerMappingConfig { public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); Map urlMap = new HashMap<>(); - urlMap.put("/simpleUrlWelcome", welcome()); + urlMap.put("/simpleUrlWelcome", welcomeSimpleMappingConfig()); simpleUrlHandlerMapping.setUrlMap(urlMap); return simpleUrlHandlerMapping; } @Bean - public WelcomeController welcome() { + public WelcomeController welcomeSimpleMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/BeanNameUrlHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/BeanNameUrlHandlerMappingConfig.xml diff --git a/spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/ControllerClassNameHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/ControllerClassNameHandlerMappingConfig.xml diff --git a/spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml b/spring-mvc-basics/src/test/resources/HandlerMappingConfiguringPriorities.xml similarity index 100% rename from spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml rename to spring-mvc-basics/src/test/resources/HandlerMappingConfiguringPriorities.xml diff --git a/spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/SimpleUrlHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/SimpleUrlHandlerMappingConfig.xml diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index c670b153cf..8ba9b5fd1e 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -17,7 +17,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) -- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) - [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) From 00c4774774e3cc1c68874bafd91e26a965c1781e Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sat, 15 Jun 2019 19:02:55 -0300 Subject: [PATCH 08/13] Moved Content Negotiation article code from spring-mvc-java to spring-mvc-basics --- spring-mvc-basics/README.md | 3 +- spring-mvc-basics/pom.xml | 1 - .../java/com/baeldung/model/Employee.java | 61 ++++++++++++++++++ .../baeldung/spring/web/config/WebConfig.java | 17 +++++ .../web/controller/EmployeeController.java | 31 +++++++++ .../src/main/resources/application.properties | 8 ++- ...llerContentNegotiationIntegrationTest.java | 63 +++++++++++++++++++ spring-mvc-java/README.md | 1 - .../baeldung/spring/web/config/WebConfig.java | 6 -- .../controller/EmployeeIntegrationTest.java | 51 --------------- 10 files changed, 181 insertions(+), 61 deletions(-) create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java delete mode 100644 spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 997e6a88df..9593fd6222 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -10,4 +10,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) -- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) \ No newline at end of file +- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) +- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) \ No newline at end of file diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index d04bdda8f6..8c52c60b65 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -30,7 +30,6 @@ javax.servlet jstl - ${jstl.version} org.springframework.boot diff --git a/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java b/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java new file mode 100644 index 0000000000..fb0a452219 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java @@ -0,0 +1,61 @@ +package com.baeldung.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Employee { + + private long id; + private String name; + private String contactNumber; + private String workingArea; + + public Employee() { + super(); + } + + public Employee(final long id, final String name, final String contactNumber, final String workingArea) { + this.id = id; + this.name = name; + this.contactNumber = contactNumber; + this.workingArea = workingArea; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(final String contactNumber) { + this.contactNumber = contactNumber; + } + + public String getWorkingArea() { + return workingArea; + } + + public void setWorkingArea(final String workingArea) { + this.workingArea = workingArea; + } + + @Override + public String toString() { + return "Employee [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + ", workingArea=" + workingArea + "]"; + } + +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java index a56dfe550f..9a321f65a2 100644 --- a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -3,7 +3,9 @@ package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; +import org.springframework.http.MediaType; import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -47,4 +49,19 @@ public class WebConfig implements WebMvcConfigurer { bean.setOrder(1); return bean; } + + /** + * Spring Boot allows configuring Content Negotiation using properties + */ + @Override + public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { + configurer.favorPathExtension(true) + .favorParameter(true) + .parameterName("mediaType") + .ignoreAcceptHeader(false) + .useRegisteredExtensionsOnly(false) + .defaultContentType(MediaType.APPLICATION_JSON) + .mediaType("xml", MediaType.APPLICATION_XML) + .mediaType("json", MediaType.APPLICATION_JSON); + } } \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java new file mode 100644 index 0000000000..00bbbfbe41 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -0,0 +1,31 @@ +package com.baeldung.web.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.model.Employee; + +@Controller +public class EmployeeController { + + Map employeeMap = new HashMap<>(); + + @ModelAttribute("employees") + public void initEmployees() { + employeeMap.put(1L, new Employee(1L, "John", "223334411", "rh")); + employeeMap.put(2L, new Employee(2L, "Peter", "22001543", "informatics")); + employeeMap.put(3L, new Employee(3L, "Mike", "223334411", "admin")); + } + + @RequestMapping(value = "/employee/{Id}",produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final Long Id) { + return employeeMap.get(Id); + } +} diff --git a/spring-mvc-basics/src/main/resources/application.properties b/spring-mvc-basics/src/main/resources/application.properties index 4de974142e..b8a9be0b40 100644 --- a/spring-mvc-basics/src/main/resources/application.properties +++ b/spring-mvc-basics/src/main/resources/application.properties @@ -1 +1,7 @@ -server.servlet.context-path=/spring-mvc-basics \ No newline at end of file +server.servlet.context-path=/spring-mvc-basics + +### Content Negotiation (already defined programatically) +spring.mvc.pathmatch.use-suffix-pattern=true +#spring.mvc.contentnegotiation.favor-path-extension=true +#spring.mvc.contentnegotiation.favor-parameter=true +#spring.mvc.contentnegotiation.parameter-name=mediaType diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java new file mode 100644 index 0000000000..6500955d23 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +public class EmployeeControllerContentNegotiationIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenEndpointUsingJsonSuffixCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1.json")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlSuffixCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1.xml")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } + + @Test + public void whenEndpointUsingJsonParameterCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1?mediaType=json")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlParameterCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1?mediaType=xml")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } + + @Test + public void whenEndpointUsingJsonAcceptHeaderCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlAcceptHeaderCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 8ba9b5fd1e..8a302e6fa3 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -13,7 +13,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables) - [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring) - [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) -- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 96b50f2c37..44fef92917 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -17,7 +17,6 @@ import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; @@ -94,11 +93,6 @@ public class WebConfig implements WebMvcConfigurer { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } - @Override - public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useRegisteredExtensionsOnly(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", - MediaType.APPLICATION_JSON); - } @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java deleted file mode 100644 index 0c2aa3de1b..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.web.controller; - -import org.junit.Before; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -import com.baeldung.model.Employee; -import com.baeldung.spring.web.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = WebConfig.class) -public class EmployeeIntegrationTest { - - @Autowired - private EmployeeController employeeController; - - @Before - public void setup() { - employeeController.initEmployees(); - } - - @Test - public void whenInitEmployees_thenVerifyValuesInitiation() { - - Employee employee1 = employeeController.employeeMap.get(1L); - Employee employee2 = employeeController.employeeMap.get(2L); - Employee employee3 = employeeController.employeeMap.get(3L); - - Assert.assertTrue(employee1.getId() == 1L); - Assert.assertTrue(employee1.getName().equals("John")); - Assert.assertTrue(employee1.getContactNumber().equals("223334411")); - Assert.assertTrue(employee1.getWorkingArea().equals("rh")); - - Assert.assertTrue(employee2.getId() == 2L); - Assert.assertTrue(employee2.getName().equals("Peter")); - Assert.assertTrue(employee2.getContactNumber().equals("22001543")); - Assert.assertTrue(employee2.getWorkingArea().equals("informatics")); - - Assert.assertTrue(employee3.getId() == 3L); - Assert.assertTrue(employee3.getName().equals("Mike")); - Assert.assertTrue(employee3.getContactNumber().equals("223334411")); - Assert.assertTrue(employee3.getWorkingArea().equals("admin")); - } - -} From e84ea4d4c50ab8d14470188857663ba2abd9dc19 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 1 Jul 2019 18:32:49 -0300 Subject: [PATCH 09/13] Moved RequestMapping Shortcut annotations article code from spring-mvc-java to spring-mvc-basics --- spring-mvc-basics/README.md | 3 +- .../RequestMappingShortcutsController.java | 47 +++++++++ ...RequestMapingShortcutsIntegrationTest.java | 97 +++++++++++++++++++ spring-mvc-java/README.md | 1 - .../RequestMappingShortcutsController.java | 47 --------- ...RequestMapingShortcutsIntegrationTest.java | 92 ------------------ 6 files changed, 146 insertions(+), 141 deletions(-) create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java delete mode 100644 spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java delete mode 100644 spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 9593fd6222..ed3d052306 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -11,4 +11,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) - [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) -- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) \ No newline at end of file +- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) +- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java new file mode 100644 index 0000000000..e91a914c6d --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java @@ -0,0 +1,47 @@ +package com.baeldung.web.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RequestMappingShortcutsController { + + @GetMapping("/get") + public @ResponseBody ResponseEntity get() { + return new ResponseEntity("GET Response", HttpStatus.OK); + } + + @GetMapping("/get/{id}") + public @ResponseBody ResponseEntity getById(@PathVariable String id) { + return new ResponseEntity("GET Response : " + id, HttpStatus.OK); + } + + @PostMapping("/post") + public @ResponseBody ResponseEntity post() { + return new ResponseEntity("POST Response", HttpStatus.OK); + } + + @PutMapping("/put") + public @ResponseBody ResponseEntity put() { + return new ResponseEntity("PUT Response", HttpStatus.OK); + } + + @DeleteMapping("/delete") + public @ResponseBody ResponseEntity delete() { + return new ResponseEntity("DELETE Response", HttpStatus.OK); + } + + @PatchMapping("/patch") + public @ResponseBody ResponseEntity patch() { + return new ResponseEntity("PATCH Response", HttpStatus.OK); + } + +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java new file mode 100644 index 0000000000..3fbb5da75e --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java @@ -0,0 +1,97 @@ +package com.baeldung.web.controller; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class RequestMapingShortcutsIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new RequestMappingShortcutsController()) + .build(); + } + + @Test + public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("GET Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("POST Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("PUT Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("DELETE Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("PATCH Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 8a302e6fa3..6ae700ee03 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -15,7 +15,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) -- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) - [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java deleted file mode 100644 index 5d4cbe9d78..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.web.controller; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PatchMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class RequestMappingShortcutsController { - - @GetMapping("/get") - public @ResponseBody ResponseEntity get() { - return new ResponseEntity("GET Response", HttpStatus.OK); - } - - @GetMapping("/get/{id}") - public @ResponseBody ResponseEntity getById(@PathVariable String id) { - return new ResponseEntity("GET Response : " + id, HttpStatus.OK); - } - - @PostMapping("/post") - public @ResponseBody ResponseEntity post() { - return new ResponseEntity("POST Response", HttpStatus.OK); - } - - @PutMapping("/put") - public @ResponseBody ResponseEntity put() { - return new ResponseEntity("PUT Response", HttpStatus.OK); - } - - @DeleteMapping("/delete") - public @ResponseBody ResponseEntity delete() { - return new ResponseEntity("DELETE Response", HttpStatus.OK); - } - - @PatchMapping("/patch") - public @ResponseBody ResponseEntity patch() { - return new ResponseEntity("PATCH Response", HttpStatus.OK); - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java deleted file mode 100644 index fb21905027..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.baeldung.web.controller; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultMatcher; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.baeldung.spring.web.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = WebConfig.class) -public class RequestMapingShortcutsIntegrationTest { - - @Autowired - private WebApplicationContext ctx; - - private MockMvc mockMvc; - - @Before - public void setup () { - DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.ctx); - this.mockMvc = builder.build(); - } - - @Test - public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("GET Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("POST Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PUT Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("DELETE Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PATCH Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - -} From e77faf8d99fe2f26cd22cdea1546b77b7f1e2eaa Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 1 Jul 2019 19:35:33 -0300 Subject: [PATCH 10/13] Moved MVC Custom Valitation article code from spring-mvc-java to spring-mvc-basics module --- spring-mvc-basics/README.md | 3 +- .../ContactNumberConstraint.java | 48 +++++------ .../ContactNumberValidator.java | 34 ++++---- .../customvalidator/FieldsValueMatch.java | 0 .../FieldsValueMatchValidator.java | 0 .../java/com/baeldung/model/NewUserForm.java | 5 +- .../com/baeldung/model/ValidatedPhone.java | 44 +++++----- .../web/controller/NewUserController.java | 0 .../controller/ValidatedPhoneController.java | 64 +++++++------- .../main/webapp/WEB-INF/view/phoneHome.jsp | 76 ++++++++--------- .../ClassValidationMvcIntegrationTest.java | 55 ++++++------ .../CustomMVCValidatorIntegrationTest.java | 84 ++++++++++--------- spring-mvc-java/README.md | 1 - 13 files changed, 207 insertions(+), 207 deletions(-) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java (89%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java (97%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/model/NewUserForm.java (82%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/model/ValidatedPhone.java (94%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/NewUserController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java (96%) rename {spring-mvc-java => spring-mvc-basics}/src/main/webapp/WEB-INF/view/phoneHome.jsp (89%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java (51%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java (63%) diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index ed3d052306..1d5fc98f95 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -12,4 +12,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) - [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) -- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) \ No newline at end of file +- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) +- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java similarity index 89% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java index dbd38c1122..42e441f8f9 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java @@ -1,24 +1,24 @@ -package com.baeldung.customvalidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -@Documented -@Constraint(validatedBy = ContactNumberValidator.class) -@Target({ElementType.METHOD, ElementType.FIELD}) -@Retention(RetentionPolicy.RUNTIME) -public @interface ContactNumberConstraint { - - String message() default "Invalid phone number"; - - Class[] groups() default {}; - - Class[] payload() default {}; - -} +package com.baeldung.customvalidator; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.validation.Constraint; +import javax.validation.Payload; + +@Documented +@Constraint(validatedBy = ContactNumberValidator.class) +@Target({ ElementType.METHOD, ElementType.FIELD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ContactNumberConstraint { + + String message() default "Invalid phone number"; + + Class[] groups() default {}; + + Class[] payload() default {}; + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java similarity index 97% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java index dea6b9099b..fe14f3ccf1 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java @@ -1,17 +1,17 @@ -package com.baeldung.customvalidator; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -public class ContactNumberValidator implements ConstraintValidator { - - @Override - public void initialize(ContactNumberConstraint contactNumber) { - } - - @Override - public boolean isValid(String contactField, ConstraintValidatorContext cxt) { - return contactField != null && contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14); - } - -} +package com.baeldung.customvalidator; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class ContactNumberValidator implements ConstraintValidator { + + @Override + public void initialize(ContactNumberConstraint contactNumber) { + } + + @Override + public boolean isValid(String contactField, ConstraintValidatorContext cxt) { + return contactField != null && contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java b/spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java similarity index 82% rename from spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java rename to spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java index 12969b6002..b4fe82ab4a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java @@ -2,10 +2,7 @@ package com.baeldung.model; import com.baeldung.customvalidator.FieldsValueMatch; -@FieldsValueMatch.List({ - @FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"), - @FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!") -}) +@FieldsValueMatch.List({ @FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"), @FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!") }) public class NewUserForm { private String email; private String verifyEmail; diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java b/spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java similarity index 94% rename from spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java rename to spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java index be702a8517..8cea915e6e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java @@ -1,22 +1,22 @@ -package com.baeldung.model; - -import com.baeldung.customvalidator.ContactNumberConstraint; - -public class ValidatedPhone { - - @ContactNumberConstraint - private String phone; - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - @Override - public String toString() { - return phone; - } -} +package com.baeldung.model; + +import com.baeldung.customvalidator.ContactNumberConstraint; + +public class ValidatedPhone { + + @ContactNumberConstraint + private String phone; + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + @Override + public String toString() { + return phone; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/NewUserController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/NewUserController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/NewUserController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/NewUserController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java similarity index 96% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java index 9b3a6b3a4c..73e1e4bb25 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java @@ -1,32 +1,32 @@ -package com.baeldung.web.controller; - -import com.baeldung.model.ValidatedPhone; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; - -import javax.validation.Valid; - -@Controller -public class ValidatedPhoneController { - - @GetMapping("/validatePhone") - public String loadFormPage(Model m) { - m.addAttribute("validatedPhone", new ValidatedPhone()); - return "phoneHome"; - } - - @PostMapping("/addValidatePhone") - public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) { - if (result.hasErrors()) { - return "phoneHome"; - } - - m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString()); - return "phoneHome"; - } - - -} +package com.baeldung.web.controller; + +import javax.validation.Valid; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; + +import com.baeldung.model.ValidatedPhone; + +@Controller +public class ValidatedPhoneController { + + @GetMapping("/validatePhone") + public String loadFormPage(Model m) { + m.addAttribute("validatedPhone", new ValidatedPhone()); + return "phoneHome"; + } + + @PostMapping("/addValidatePhone") + public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) { + if (result.hasErrors()) { + return "phoneHome"; + } + + m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString()); + return "phoneHome"; + } + +} diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp similarity index 89% rename from spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp rename to spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp index b873e9bc5f..ebc9052639 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp @@ -1,38 +1,38 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> - - - - - Sample Form - - - - -
- -

Phone Number

-
${message}
- - - - - - -
- - -
-
- - +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> + + + + + Sample Form + + + + +
+ +

Phone Number

+
${message}
+ + + + + + +
+ + +
+
+ + diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java similarity index 51% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java index 2cd225a775..24182f492a 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java @@ -5,46 +5,47 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; public class ClassValidationMvcIntegrationTest { - private MockMvc mockMvc; - - @Before - public void setup(){ - this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController()).build(); + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController()) + .build(); } - + @Test public void givenMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/user") - .accept(MediaType.TEXT_HTML) - .param("email", "john@yahoo.com") - .param("verifyEmail", "john@yahoo.com") - .param("password", "pass") - .param("verifyPassword", "pass")) - .andExpect(model().attribute("message", "Valid form")) - .andExpect(view().name("userHome")) - .andExpect(status().isOk()) - .andDo(print()); + .accept(MediaType.TEXT_HTML) + .param("email", "john@yahoo.com") + .param("verifyEmail", "john@yahoo.com") + .param("password", "pass") + .param("verifyPassword", "pass")) + .andExpect(model().attribute("message", "Valid form")) + .andExpect(view().name("userHome")) + .andExpect(status().isOk()) + .andDo(print()); } - + @Test public void givenNotMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/user") - .accept(MediaType.TEXT_HTML) - .param("email", "john@yahoo.com") - .param("verifyEmail", "john@yahoo.commmm") - .param("password", "pass") - .param("verifyPassword", "passsss")) - .andExpect(model().errorCount(2)) - .andExpect(view().name("userHome")) - .andExpect(status().isOk()) - .andDo(print()); + .accept(MediaType.TEXT_HTML) + .param("email", "john@yahoo.com") + .param("verifyEmail", "john@yahoo.commmm") + .param("password", "pass") + .param("verifyPassword", "passsss")) + .andExpect(model().errorCount(2)) + .andExpect(view().name("userHome")) + .andExpect(status().isOk()) + .andDo(print()); } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java similarity index 63% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java index 013cf9c91d..11b72e1650 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java @@ -1,41 +1,43 @@ -package com.baeldung.web.controller; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -public class CustomMVCValidatorIntegrationTest { - - private MockMvc mockMvc; - - @Before - public void setup(){ - this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController()).build(); - } - - @Test - public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception{ - this.mockMvc.perform(get("/validatePhone")).andExpect(view().name("phoneHome")); - } - - @Test - public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone"). - accept(MediaType.TEXT_HTML). - param("phoneInput", "123")). - andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone","ContactNumberConstraint")). - andExpect(view().name("phoneHome")). - andExpect(status().isOk()). - andDo(print()); - } - -} +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class CustomMVCValidatorIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController()) + .build(); + } + + @Test + public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception { + this.mockMvc.perform(get("/validatePhone")) + .andExpect(view().name("phoneHome")); + } + + @Test + public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone") + .accept(MediaType.TEXT_HTML) + .param("phoneInput", "123")) + .andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone", "ContactNumberConstraint")) + .andExpect(view().name("phoneHome")) + .andExpect(status().isOk()) + .andDo(print()); + } + +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 6ae700ee03..15daac97a5 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -16,7 +16,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) -- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) - [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) From bb2765c4e33d09b2398be17d92860af38c3b6875 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 1 Jul 2019 20:26:45 -0300 Subject: [PATCH 11/13] Moved Using @ResponseStatus article from spring-mvc-java to spring-mvc-basics module --- spring-mvc-basics/README.md | 3 ++- spring-mvc-java/README.md | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 1d5fc98f95..80db309df2 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -13,4 +13,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) -- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) \ No newline at end of file +- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) +- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) \ No newline at end of file diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 15daac97a5..d8a79b9759 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -21,6 +21,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) -- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) From dc3c7937172b51303389255f8d6c6cb15352f8dc Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 1 Jul 2019 22:08:02 -0300 Subject: [PATCH 12/13] Moved ModeAttribute article from spring-mvc-java to spring-mvc-basics module --- spring-mvc-basics/README.md | 3 +- .../web/controller/EmployeeController.java | 31 ++++++++++++++++- .../main/webapp/WEB-INF/view/employeeHome.jsp | 33 +++++++++++++++++++ .../main/webapp/WEB-INF/view/employeeView.jsp | 25 ++++++++++++++ spring-mvc-java/README.md | 1 - .../web/controller/EmployeeController.java | 26 ++++++++------- .../main/webapp/WEB-INF/view/employeeHome.jsp | 2 +- .../main/webapp/WEB-INF/view/employeeView.jsp | 5 --- 8 files changed, 106 insertions(+), 20 deletions(-) create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 80db309df2..afb71ce63d 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -14,4 +14,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) - [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) -- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) \ No newline at end of file +- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) +- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java index 00bbbfbe41..cbea4c98c6 100644 --- a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -4,11 +4,15 @@ import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; import com.baeldung.model.Employee; @@ -24,8 +28,33 @@ public class EmployeeController { employeeMap.put(3L, new Employee(3L, "Mike", "223334411", "admin")); } - @RequestMapping(value = "/employee/{Id}",produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } + + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) public @ResponseBody Employee getEmployeeById(@PathVariable final Long Id) { return employeeMap.get(Id); } + + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("workingArea", employee.getWorkingArea()); + model.addAttribute("id", employee.getId()); + + employeeMap.put(employee.getId(), employee); + + return "employeeView"; + } + + @ModelAttribute + public void addAttributes(final Model model) { + model.addAttribute("msg", "Welcome to the Netherlands!"); + } } diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp new file mode 100644 index 0000000000..fa5812faea --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -0,0 +1,33 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Register an Employee + + +

Welcome, Enter The Employee Details

+ + + + + + + + + + + + + + + + + + +
Name
Id
Contact Number
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp new file mode 100644 index 0000000000..9a9b879a35 --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp @@ -0,0 +1,25 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Employee Information

+

${msg}

+ + + + + + + + + + + + + +
Name :${name}
ID :${id}
Contact Number :${contactNumber}
+ + \ No newline at end of file diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index d8a79b9759..f12c904229 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -18,7 +18,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) - [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) -- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java index ef76059567..251287dff8 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -1,20 +1,29 @@ package com.baeldung.web.controller; -import com.baeldung.model.Employee; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.MatrixVariable; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; -import java.util.*; +import com.baeldung.model.Employee; @SessionAttributes("employees") @Controller -@ControllerAdvice public class EmployeeController { Map employeeMap = new HashMap<>(); @@ -35,7 +44,7 @@ public class EmployeeController { public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { return employeeMap.get(Id); } - + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { @@ -51,11 +60,6 @@ public class EmployeeController { return "employeeView"; } - @ModelAttribute - public void addAttributes(final Model model) { - model.addAttribute("msg", "Welcome to the Netherlands!"); - } - @RequestMapping(value = "/employees/{name}", method = RequestMethod.GET) @ResponseBody public ResponseEntity> getEmployeeByNameAndBeginContactNumber(@PathVariable final String name, @MatrixVariable final String beginContactNumber) { diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp index 8a32fd12b6..268f0a055a 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -8,7 +8,7 @@

Welcome, Enter The Employee Details

- + diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp index 627a9d9ddb..1457bc5fc8 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp @@ -6,7 +6,6 @@

Submitted Employee Information

-

${msg}

Name
@@ -20,10 +19,6 @@ - - - -
Name :Contact Number : ${contactNumber}
Working Area :${workingArea}
\ No newline at end of file From e239fb97633c05393917395b0a17dfadb5c5f826 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 1 Jul 2019 22:30:44 -0300 Subject: [PATCH 13/13] Added Integration test for ModelAttribute article --- ...ntrollerModelAttributeIntegrationTest.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java new file mode 100644 index 0000000000..5195adabd5 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import java.util.Arrays; +import java.util.Collection; + +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +public class EmployeeControllerModelAttributeIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void givenUrlEncodedFormData_whenAddEmployeeEndpointCalled_thenModelContainsMsgAttribute() throws Exception { + Collection formData = Arrays.asList(new BasicNameValuePair("name", "employeeName"), new BasicNameValuePair("id", "99"), new BasicNameValuePair("contactNumber", "123456789")); + String urlEncodedFormData = EntityUtils.toString(new UrlEncodedFormEntity(formData)); + + mockMvc.perform(post("/addEmployee").contentType(MediaType.APPLICATION_FORM_URLENCODED) + .content(urlEncodedFormData)) + .andExpect(status().isOk()) + .andExpect(view().name("employeeView")) + .andExpect(model().attribute("msg", "Welcome to the Netherlands!")); + } +}