JAVA-3521: Moved spring-mvc-basics-4 inside spring-web-modules

This commit is contained in:
sampadawagde
2020-12-24 19:58:59 +05:30
parent c90bd8ae33
commit e5d433b1fb
59 changed files with 2 additions and 2 deletions

View File

@@ -0,0 +1,19 @@
package com.baeldung.contexts;
public class Greeting {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "Greeting [message=" + message + "]";
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.contexts.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class AnnotationsBasedApplicationAndServletInitializer //extends AbstractDispatcherServletInitializer
{
//uncomment to run the multiple contexts example
//@Override
protected WebApplicationContext createRootApplicationContext() {
//If this is not the only class declaring a root context, we return null because it would clash
//with other classes, as there can only be a single root context.
//AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
//rootContext.register(RootApplicationConfig.class);
//return rootContext;
return null;
}
//@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext();
normalWebAppContext.register(NormalWebAppConfig.class);
return normalWebAppContext;
}
//@Override
protected String[] getServletMappings() {
return new String[] { "/api/*" };
}
//@Override
protected String getServletName() {
return "normal-dispatcher";
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.contexts.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class AnnotationsBasedApplicationInitializer //extends AbstractContextLoaderInitializer
{
//uncomment to run the multiple contexts example
// @Override
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootApplicationConfig.class);
return rootContext;
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.contexts.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class ApplicationInitializer //implements WebApplicationInitializer
{
//uncomment to run the multiple contexts example
//@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//Here, we can define a root context and register servlets, among other things.
//However, since we've later defined other classes to do the same and they would clash,
//we leave this commented out.
//Root XML Context
//XmlWebApplicationContext rootContext = new XmlWebApplicationContext();
//rootContext.setConfigLocations("/WEB-INF/rootApplicationContext.xml");
//Annotations Context
//AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
//rootContext.register(RootApplicationConfig.class);
//Registration
//servletContext.addListener(new ContextLoaderListener(rootContext));
//Dispatcher Servlet
//XmlWebApplicationContext normalWebAppContext = new XmlWebApplicationContext();
//normalWebAppContext.setConfigLocation("/WEB-INF/normal-webapp-servlet.xml");
//ServletRegistration.Dynamic normal = servletContext.addServlet("normal-webapp", new DispatcherServlet(normalWebAppContext));
//normal.setLoadOnStartup(1);
//normal.addMapping("/api/*");
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.contexts.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.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.contexts.normal" })
public class NormalWebAppConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.contexts.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.baeldung.contexts.Greeting;
@Configuration
@ComponentScan(basePackages = { "com.baeldung.contexts.services" })
public class RootApplicationConfig {
@Bean
public Greeting greeting() {
Greeting greeting = new Greeting();
greeting.setMessage("Hello World !!");
return greeting;
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.contexts.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class SecureAnnotationsBasedApplicationAndServletInitializer// extends AbstractDispatcherServletInitializer
{
//uncomment to run the multiple contexts example
//@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
//@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext();
secureWebAppContext.register(SecureWebAppConfig.class);
return secureWebAppContext;
}
//@Override
protected String[] getServletMappings() {
return new String[] { "/s/api/*" };
}
//@Override
protected String getServletName() {
return "secure-dispatcher";
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.contexts.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.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.contexts.secure" })
public class SecureWebAppConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/secure/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.contexts.normal;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import com.baeldung.contexts.services.GreeterService;
@Controller
public class HelloWorldController {
@Autowired
WebApplicationContext webApplicationContext;
@Autowired
private GreeterService greeterService;
private void processContext() {
WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext();
System.out.println("root context : " + rootContext);
System.out.println("root context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames()));
System.out.println("context : " + webApplicationContext);
System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames()));
}
@RequestMapping(path = "/welcome")
public ModelAndView helloWorld() {
processContext();
String message = "<br><div style='text-align:center;'>" + "<h3>Normal " + greeterService.greet() + "</h3></div>";
return new ModelAndView("welcome", "message", message);
}
}

View File

@@ -0,0 +1,49 @@
package com.baeldung.contexts.secure;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import com.baeldung.contexts.services.ApplicationContextUtilService;
import com.baeldung.contexts.services.GreeterService;
@Controller
public class HelloWorldSecureController {
@Autowired
WebApplicationContext webApplicationContext;
@Autowired
private GreeterService greeterService;
@Autowired
@Qualifier("contextAware")
private ApplicationContextUtilService contextUtilService;
private void processContext() {
ApplicationContext context = contextUtilService.getApplicationContext();
System.out.println("application context : " + context);
System.out.println("application context Beans: " + Arrays.asList(context.getBeanDefinitionNames()));
WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext();
System.out.println("context : " + rootContext);
System.out.println("context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames()));
System.out.println("context : " + webApplicationContext);
System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames()));
}
@RequestMapping(path = "/welcome")
public ModelAndView helloWorld() {
processContext();
String message = "<br><div style='text-align:center;'>" + "<h3>Secure " + greeterService.greet() + "</h3></div>";
return new ModelAndView("welcome", "message", message);
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.contexts.services;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Service(value="contextAware")
public class ApplicationContextUtilService implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.contexts.services;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.baeldung.contexts.Greeting;
@Service
public class GreeterService {
@Resource
private Greeting greeting;
public String greet(){
return greeting.getMessage();
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.controller.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class StudentControllerConfig //implements WebApplicationInitializer
{
//uncomment to run the student controller example
//@Override
public void onStartup(ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(WebConfig.class);
root.setServletContext(sc);
sc.addListener(new ContextLoaderListener(root));
DispatcherServlet dv = new DispatcherServlet(root);
ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv);
appServlet.setLoadOnStartup(1);
appServlet.addMapping("/test/*");
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.controller.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.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.controller", "com.baeldung.optionalpathvars" })
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/");
bean.setSuffix(".jsp");
return bean;
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.controller.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* In this controller, Model, ModelMap and ModelAndView are shown as examples.
* They are all used to pass parameters to JSP pages.
* 04/09/2017
*
* @author Ahmet Cetin
*/
@Controller
public class PassParametersController {
@GetMapping("/showViewPage")
public String passParametersWithModel(Model model) {
model.addAttribute("message", "Baeldung");
return "viewPage";
}
@GetMapping("/printViewPage")
public String passParametersWithModelMap(ModelMap map) {
map.addAttribute("welcomeMessage", "welcome");
map.addAttribute("message", "Baeldung");
return "viewPage";
}
@GetMapping("/goToViewPage")
public ModelAndView passParametersWithModelAndView() {
ModelAndView modelAndView = new ModelAndView("viewPage");
modelAndView.addObject("message", "Baeldung");
return modelAndView;
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.controller.controller;
import com.baeldung.controller.student.Student;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestAnnotatedController {
@GetMapping(value = "/annotated/student/{studentId}")
public Student getData(@PathVariable Integer studentId) {
Student student = new Student();
student.setName("Peter");
student.setId(studentId);
return student;
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.controller.controller;
import com.baeldung.controller.student.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class RestController {
@GetMapping(value = "/student/{studentId}")
public @ResponseBody
Student getTestData(@PathVariable Integer studentId) {
Student student = new Student();
student.setName("Peter");
student.setId(studentId);
return student;
}
}

View File

@@ -0,0 +1,24 @@
/**
* @author Prashant Dutta
*/
package com.baeldung.controller.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = "/test")
public class TestController {
@GetMapping
public ModelAndView getTestData() {
ModelAndView mv = new ModelAndView();
mv.setViewName("welcome");
mv.getModel().put("data", "Welcome home man");
return mv;
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.controller.student;
public class Student {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
return this.id;
}
@Override
public boolean equals(Object obj) {
return this.name.equals(((Student) obj).getName());
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.jsonparams.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.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.jsonparams" })
public class JsonParamsConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/");
bean.setSuffix(".jsp");
return bean;
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.jsonparams.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class JsonParamsInit // implements WebApplicationInitializer
{
//uncomment to run the product controller example
//@Override
public void onStartup(ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(JsonParamsConfig.class);
root.setServletContext(sc);
sc.addListener(new ContextLoaderListener(root));
DispatcherServlet dv = new DispatcherServlet(root);
ServletRegistration.Dynamic appServlet = sc.addServlet("jsonparams-mvc", dv);
appServlet.setLoadOnStartup(1);
appServlet.addMapping("/");
}
}

View File

@@ -0,0 +1,57 @@
package com.baeldung.jsonparams.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baeldung.jsonparams.model.Product;
import com.baeldung.jsonparams.propertyeditor.ProductEditor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
@RequestMapping("/products")
public class ProductController {
private ObjectMapper objectMapper;
@Autowired
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Product.class, new ProductEditor(objectMapper));
}
@PostMapping("/create")
@ResponseBody
public Product createProduct(@RequestBody Product product) {
// custom logic
return product;
}
@GetMapping("/get")
@ResponseBody
public Product getProduct(@RequestParam String product) throws JsonMappingException, JsonProcessingException {
final Product prod = objectMapper.readValue(product, Product.class);
return prod;
}
@GetMapping("/get2")
@ResponseBody
public Product get2Product(@RequestParam Product product) {
// custom logic
return product;
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.jsonparams.model;
public class Product {
private int id;
private String name;
private double price;
public Product() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String nom) {
this.name = nom;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.jsonparams.propertyeditor;
import java.beans.PropertyEditorSupport;
import org.springframework.util.StringUtils;
import com.baeldung.jsonparams.model.Product;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ProductEditor extends PropertyEditorSupport {
private ObjectMapper objectMapper;
public ProductEditor(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (StringUtils.isEmpty(text)) {
setValue(null);
} else {
Product prod = new Product();
try {
prod = objectMapper.readValue(text, Product.class);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
setValue(prod);
}
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.optionalpathvars;
public class Article {
public static final Article DEFAULT_ARTICLE = new Article(12);
private Integer id;
public Article(Integer articleId) {
this.id = articleId;
}
public Integer getId() {
return id;
}
@Override
public String toString() {
return "Article [id=" + id + "]";
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.optionalpathvars;
import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ArticleViewerController {
@RequestMapping(value = {"/article", "/article/{id}"})
public Article getArticle(@PathVariable(name = "id") Integer articleId) {
if (articleId != null) {
return new Article(articleId);
} else {
return DEFAULT_ARTICLE;
}
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.optionalpathvars;
import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE;
import java.util.Map;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/mapParam")
public class ArticleViewerWithMapParamController {
@RequestMapping(value = {"/article", "/article/{id}"})
public Article getArticle(@PathVariable Map<String, String> pathVarsMap) {
String articleId = pathVarsMap.get("id");
if (articleId != null) {
return new Article(Integer.valueOf(articleId));
} else {
return DEFAULT_ARTICLE;
}
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.optionalpathvars;
import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE;
import java.util.Optional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;;
@RestController
@RequestMapping("/optionalParam")
public class ArticleViewerWithOptionalParamController {
@RequestMapping(value = {"/article", "/article/{id}"})
public Article getArticle(@PathVariable(name = "id") Optional<Integer> optionalArticleId) {
if(optionalArticleId.isPresent()) {
Integer articleId = optionalArticleId.get();
return new Article(articleId);
}else {
return DEFAULT_ARTICLE;
}
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.optionalpathvars;
import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;;
@RestController
@RequestMapping(value = "/requiredAttribute")
public class ArticleViewerWithRequiredAttributeController {
@RequestMapping(value = {"/article", "/article/{id}"})
public Article getArticle(@PathVariable(name = "id", required = false) Integer articleId) {
if (articleId != null) {
return new Article(articleId);
} else {
return DEFAULT_ARTICLE;
}
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.optionalpathvars;
import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/seperateMethods")
public class ArticleViewerWithTwoSeparateMethodsController {
@RequestMapping(value = "/article/{id}")
public Article getArticle(@PathVariable(name = "id") Integer articleId) {
return new Article(articleId);
}
@RequestMapping(value = "/article")
public Article getDefaultArticle() {
return DEFAULT_ARTICLE;
}
}

View File

@@ -0,0 +1 @@
spring.main.allow-bean-definition-overriding=true

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.baeldung.controller.controller"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,11 @@
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="greeting" class="com.baeldung.contexts.Greeting">
<property name="message" value="Hello World !!"/>
</bean>
</beans>

View File

@@ -0,0 +1,5 @@
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

View File

@@ -0,0 +1,16 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.baeldung.contexts.normal"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>

View File

@@ -0,0 +1,14 @@
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.baeldung.contexts.services"/>
<import resource="greeting.xml"/>
</beans>

View File

@@ -0,0 +1,16 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.baeldung.contexts.secure"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/secure/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>

View File

@@ -0,0 +1,11 @@
<html>
<head>
<title>Spring Web Contexts</title>
</head>
<body>
<br>
<div style="padding: 10px; border-radius: 10px; font-size: 30px; text-align: center;">
Secure Web Application : ${message}
</div>
</body>
</html>

View File

@@ -0,0 +1,7 @@
<html>
<head></head>
<body>
<h1>This is the body of the sample view</h1>
</body>
</html>

View File

@@ -0,0 +1,10 @@
<html>
<head></head>
<body>
<h1>Bean Scopes Examples</h1>
<br> Previous Message: ${previousMessage }
<br> Current Message: ${currentMessage }
<br>
</body>
</html>

View File

@@ -0,0 +1,9 @@
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<div>Web Application. Passed parameter : th:text="${message}"</div>
</body>
</html>

View File

@@ -0,0 +1,11 @@
<html>
<head>
<title>Spring Web Contexts</title>
</head>
<body>
<br>
<div style="padding: 10px; border-radius: 10px; font-size: 30px; text-align: center;">
Normal Web Application : ${message}
</div>
</body>
</html>

View File

@@ -0,0 +1,88 @@
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- Uncommented, this disallows org.springframework.web.SpringServletContainerInitializer to run and execute
application initializers. -->
<!--<absolute-ordering>
</absolute-ordering>-->
<!-- root application context -->
<!--<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>-->
<!--<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rootApplicationContext.xml</param-value>
</context-param>-->
<!--<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.baeldung.contexts.config.RootApplicationConfig, com.baeldung.contexts.config.NormalWebAppConfig</param-value>
</context-param>-->
<!--<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.baeldung.bean.config</param-value>
</context-param>-->
<!-- secure web app context -->
<!--<servlet>
<servlet-name>secure-webapp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/secure-webapp-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>secure-webapp</servlet-name>
<url-pattern>/s/api/*</url-pattern>
</servlet-mapping>-->
<!-- normal web app context -->
<!--<servlet>
<servlet-name>normal-webapp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>normal-webapp</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>-->
<!-- normal webapp with annotations-based context -->
<servlet>
<servlet-name>normal-webapp-annotations</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.baeldung.contexts.config.NormalWebAppConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>normal-webapp-annotations</servlet-name>
<url-pattern>/api-ann/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/index.jsp</welcome-file>
</welcome-file-list>
</web-app>

View File

@@ -0,0 +1,12 @@
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Data returned is ${data}
</body>
</html>

View File

@@ -0,0 +1,5 @@
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

View File

@@ -0,0 +1,79 @@
package com.baeldung.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.baeldung.controller.config.WebConfig;
import com.baeldung.controller.student.Student;
import org.junit.Assert;
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.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class)
public class ControllerAnnotationIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
private Student selectedStudent;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
selectedStudent = new Student();
selectedStudent.setId(1);
selectedStudent.setName("Peter");
}
@Test
public void testTestController() throws Exception {
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
// validate modal data
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
// validate view name
Assert.assertSame(mv.getViewName(), "welcome");
}
@Test
public void testRestController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
Student studentDetails = reader.readValue(responseBody, Student.class);
Assert.assertEquals(selectedStudent, studentDetails);
}
@Test
public void testRestAnnotatedController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
Student studentDetails = reader.readValue(responseBody, Student.class);
Assert.assertEquals(selectedStudent, studentDetails);
}
}

View File

@@ -0,0 +1,77 @@
package com.baeldung.controller;
import org.junit.Assert;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import com.baeldung.controller.student.Student;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({ "classpath:test-mvc.xml" })
public class ControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
private Student selectedStudent;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
selectedStudent = new Student();
selectedStudent.setId(1);
selectedStudent.setName("Peter");
}
@Test
public void testTestController() throws Exception {
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
// validate modal data
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
// validate view name
Assert.assertSame(mv.getViewName(), "welcome");
}
@Test
public void testRestController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
Student studentDetails = reader.readValue(responseBody, Student.class);
Assert.assertEquals(selectedStudent, studentDetails);
}
@Test
public void testRestAnnotatedController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
Student studentDetails = reader.readValue(responseBody, Student.class);
Assert.assertEquals(selectedStudent, studentDetails);
}
}

View File

@@ -0,0 +1,69 @@
package com.baeldung.controller;
import org.junit.Assert;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
/**
* This is the test class for {@link com.baeldung.controller.controller.PassParametersController} class.
* 09/09/2017
*
* @author Ahmet Cetin
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:test-mvc.xml"})
public class PassParametersControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testPassParametersWithModel() throws Exception {
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/showViewPage")).andReturn().getModelAndView();
//Validate view
Assert.assertEquals(mv.getViewName(), "viewPage");
//Validate attribute
Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung");
}
@Test
public void testPassParametersWithModelMap() throws Exception {
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/printViewPage")).andReturn().getModelAndView();
//Validate view
Assert.assertEquals(mv.getViewName(), "viewPage");
//Validate attribute
Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung");
}
@Test
public void testPassParametersWithModelAndView() throws Exception {
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/goToViewPage")).andReturn().getModelAndView();
//Validate view
Assert.assertEquals(mv.getViewName(), "viewPage");
//Validate attribute
Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung");
}
}

View File

@@ -0,0 +1,71 @@
package com.baeldung.jsonparams;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.baeldung.jsonparams.config.JsonParamsConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { JsonParamsConfig.class }, loader = AnnotationConfigWebContextLoader.class)
public class JsonParamsIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.build();
}
@Test
public void whenJsonIsPassedWithPost_thenResponseOK() throws Exception {
this.mockMvc.perform(post("/products/create").accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"id\": 1,\"name\": \"Asus Zenbook\",\"price\": 800}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("1"))
.andExpect(jsonPath("$.name").value("Asus Zenbook"));
}
@Test
public void whenJsonIsPassedWithGet_thenResponseOK() throws Exception {
this.mockMvc.perform(get("/products/get").contentType(MediaType.APPLICATION_JSON)
.queryParam("product", "{\"id\": 2,\"name\": \"HP EliteBook\",\"price\": 700}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("2"))
.andExpect(jsonPath("$.name").value("HP EliteBook"));
}
@Test
public void whenJsonIsPassedWithGet2_thenResponseOK() throws Exception {
this.mockMvc.perform(get("/products/get2").contentType(MediaType.APPLICATION_JSON)
.queryParam("product", "{\"id\": 3,\"name\": \"Dell G5 15\",\"price\": 1200}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("3"))
.andExpect(jsonPath("$.name").value("Dell G5 15"));
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.optionalpathvars;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.controller.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class })
public class ArticleViewerControllerIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void whenIdPathVariableIsPassed_thenResponseOK() throws Exception {
int articleId = 5;
this.mockMvc
.perform(MockMvcRequestBuilders.get("/article/{id}", articleId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId));
}
@Test
public void whenIdPathVariableIsNotPassed_thenResponse500() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/article"))
.andExpect(MockMvcResultMatchers.status().isInternalServerError());
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.optionalpathvars;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.controller.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class })
public class ArticleViewerControllerWithOptionalParamIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenOPtionalParam_whenIdPathVariableIsPassed_thenResponseOK() throws Exception {
int articleId = 154;
this.mockMvc
.perform(MockMvcRequestBuilders.get("/optionalParam/article/{id}", articleId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId));
}
@Test
public void givenOPtionalParam_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/optionalParam/article"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId()));
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.optionalpathvars;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.controller.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class })
public class ArticleViewerControllerWithRequiredAttributeIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenRequiredAttributeIsFalse_whenIdPathVariableIsPassed_thenResponseOK() throws Exception {
int articleId = 154;
this.mockMvc
.perform(MockMvcRequestBuilders.get("/requiredAttribute/article/{id}", articleId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId));
}
@Test
public void givenRequiredAttributeIsFalse_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/requiredAttribute/article"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId()));
}
}

View File

@@ -0,0 +1,55 @@
package com.baeldung.optionalpathvars;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.controller.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class })
public class ArticleViewerWithMapParamIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenPathVarsMapParam_whenIdPathVariableIsPassed_thenResponseOK() throws Exception {
int articleId = 5;
this.mockMvc
.perform(MockMvcRequestBuilders.get("/mapParam/article/{id}", articleId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId));
}
@Test
public void givenPathVarsMapParam_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/mapParam/article"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId()));
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.optionalpathvars;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.controller.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class })
public class ArticleViewerWithTwoSeparateMethodsIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenTwoSeparateMethods_whenIdPathVariableIsPassed_thenResponseOK() throws Exception {
int articleId = 5;
this.mockMvc
.perform(MockMvcRequestBuilders.get("/seperateMethods/article/{id}", articleId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId));
}
@Test
public void givenTwoSeparateMethods_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/seperateMethods/article"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId()));
}
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.baeldung.controller.controller" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>