JAVA-3525: Moved spring-mvc-java-2 inside spring-web-modules

This commit is contained in:
sampadawagde
2020-12-29 23:44:51 +05:30
parent 9b1344a054
commit 613d5d1c91
29 changed files with 1 additions and 1 deletions

View File

@@ -0,0 +1,54 @@
package com.baeldung.cache;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.TimeUnit;
@Controller
public class CacheControlController {
@GetMapping(value = "/hello/{name}")
public ResponseEntity<String> hello(@PathVariable String name) {
CacheControl cacheControl = CacheControl.maxAge(60, TimeUnit.SECONDS)
.noTransform()
.mustRevalidate();
return ResponseEntity.ok()
.cacheControl(cacheControl)
.body("Hello " + name);
}
@GetMapping(value = "/home/{name}")
public String home(@PathVariable String name, final HttpServletResponse response) {
response.addHeader("Cache-Control", "max-age=60, must-revalidate, no-transform");
return "home";
}
@GetMapping(value = "/login/{name}")
public ResponseEntity<String> intercept(@PathVariable String name) {
return ResponseEntity.ok().body("Hello " + name);
}
@GetMapping(value = "/productInfo/{name}")
public ResponseEntity<String> validate(@PathVariable String name, WebRequest request) {
ZoneId zoneId = ZoneId.of("GMT");
long lastModifiedTimestamp = LocalDateTime.of(2020, 02, 4, 19, 57, 45)
.atZone(zoneId).toInstant().toEpochMilli();
if (request.checkNotModified(lastModifiedTimestamp)) {
return ResponseEntity.status(304).build();
}
return ResponseEntity.ok().body("Hello " + name);
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.cache;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.WebContentInterceptor;
import java.util.concurrent.TimeUnit;
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = {"com.baeldung.cache"})
public class CacheWebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/")
.setCacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)
.noTransform()
.mustRevalidate());
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebContentInterceptor interceptor = new WebContentInterceptor();
interceptor.addCacheMapping(CacheControl.maxAge(60, TimeUnit.SECONDS)
.noTransform()
.mustRevalidate(), "/login/*");
registry.addInterceptor(interceptor);
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.datetime;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.format.number.NumberFormatAnnotationFormatterFactory;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.time.format.DateTimeFormatter;
@Configuration
public class DateTimeConfig extends WebMvcConfigurationSupport {
@Bean
@Override
public FormattingConversionService mvcConversionService() {
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false);
conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
DateTimeFormatterRegistrar dateTimeRegistrar = new DateTimeFormatterRegistrar();
dateTimeRegistrar.setDateFormatter(DateTimeFormatter.ofPattern("dd.MM.yyyy"));
dateTimeRegistrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"));
dateTimeRegistrar.registerFormatters(conversionService);
DateFormatterRegistrar dateRegistrar = new DateFormatterRegistrar();
dateRegistrar.setFormatter(new DateFormatter("dd.MM.yyyy"));
dateRegistrar.registerFormatters(conversionService);
return conversionService;
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.datetime;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
@RestController
public class DateTimeController {
@PostMapping("/date")
public void date(@RequestParam("date") @DateTimeFormat(pattern = "dd.MM.yyyy") Date date) {
// ...
}
@PostMapping("/localdate")
public void localDate(@RequestParam("localDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate localDate) {
// ...
}
@PostMapping("/localdatetime")
public void dateTime(@RequestParam("localDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime localDateTime) {
// ...
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.matrix.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;
@Configuration
public class MatrixWebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
final UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}

View File

@@ -0,0 +1,56 @@
package com.baeldung.matrix.controller;
import com.baeldung.matrix.model.Company;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@Controller
public class CompanyController {
Map<Long, Company> companyMap = new HashMap<>();
@RequestMapping(value = "/company", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("companyHome", "company", new Company());
}
@RequestMapping(value = "/company/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Company getCompanyById(@PathVariable final long Id) {
return companyMap.get(Id);
}
@RequestMapping(value = "/addCompany", method = RequestMethod.POST)
public String submit(@ModelAttribute("company") final Company company, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", company.getName());
model.addAttribute("id", company.getId());
companyMap.put(company.getId(), company);
return "companyView";
}
@RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getEmployeeDataFromCompany(@MatrixVariable(pathVar = "employee") final Map<String, String> matrixVars) {
return new ResponseEntity<>(matrixVars, HttpStatus.OK);
}
@RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getCompanyName(@MatrixVariable(value = "name", pathVar = "company") final String name) {
final Map<String, String> result = new HashMap<String, String>();
result.put("name", name);
return new ResponseEntity<>(result, HttpStatus.OK);
}
}

View File

@@ -0,0 +1,102 @@
package com.baeldung.matrix.controller;
import com.baeldung.matrix.model.Employee;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.*;
@SessionAttributes("employees")
@Controller
public class EmployeeController {
public Map<Long, Employee> 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", 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";
}
@RequestMapping(value = "/employees/{name}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Employee>> getEmployeeByNameAndBeginContactNumber(@PathVariable final String name, @MatrixVariable final String beginContactNumber) {
final List<Employee> employeesList = new ArrayList<Employee>();
for (final Map.Entry<Long, Employee> employeeEntry : employeeMap.entrySet()) {
final Employee employee = employeeEntry.getValue();
if (employee.getName().equalsIgnoreCase(name) && employee.getContactNumber().startsWith(beginContactNumber)) {
employeesList.add(employee);
}
}
return new ResponseEntity<>(employeesList, HttpStatus.OK);
}
@RequestMapping(value = "/employeesContacts/{contactNumber}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Employee>> getEmployeeBycontactNumber(@MatrixVariable(required = true) final String contactNumber) {
final List<Employee> employeesList = new ArrayList<Employee>();
for (final Map.Entry<Long, Employee> employeeEntry : employeeMap.entrySet()) {
final Employee employee = employeeEntry.getValue();
if (employee.getContactNumber().equalsIgnoreCase(contactNumber)) {
employeesList.add(employee);
}
}
return new ResponseEntity<>(employeesList, HttpStatus.OK);
}
@RequestMapping(value = "employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getEmployeeData(@MatrixVariable final Map<String, String> matrixVars) {
return new ResponseEntity<>(matrixVars, HttpStatus.OK);
}
@RequestMapping(value = "employeeArea/{workingArea}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Employee>> getEmployeeByWorkingArea(@MatrixVariable final Map<String, LinkedList<String>> matrixVars) {
final List<Employee> employeesList = new ArrayList<Employee>();
final LinkedList<String> workingArea = matrixVars.get("workingArea");
for (final Map.Entry<Long, Employee> employeeEntry : employeeMap.entrySet()) {
final Employee employee = employeeEntry.getValue();
for (final String area : workingArea) {
if (employee.getWorkingArea().equalsIgnoreCase(area)) {
employeesList.add(employee);
break;
}
}
}
return new ResponseEntity<>(employeesList, HttpStatus.OK);
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.matrix.model;
public class Company {
private long id;
private String name;
public Company() {
super();
}
public Company(final long id, final String name) {
this.id = id;
this.name = name;
}
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;
}
@Override
public String toString() {
return "Company [id=" + id + ", name=" + name + "]";
}
}

View File

@@ -0,0 +1,61 @@
package com.baeldung.matrix.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 + "]";
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.multiparttesting;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class MultipartPostRequestController {
@PostMapping(path = "/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
return file.isEmpty() ? new ResponseEntity<String>(HttpStatus.NOT_FOUND) : new ResponseEntity<String>(HttpStatus.OK);
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.pathvariable.dottruncated;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class CustomWebMvcConfigurationSupport extends WebMvcConfigurationSupport {
@Override
protected PathMatchConfigurer getPathMatchConfigurer() {
PathMatchConfigurer pathMatchConfigurer = super.getPathMatchConfigurer();
pathMatchConfigurer.setUseSuffixPatternMatch(false);
return pathMatchConfigurer;
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.pathvariable.dottruncated;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/site")
public class SiteController {
@GetMapping("/{firstValue}/{secondValue}")
public String requestWithError(@PathVariable("firstValue") String firstValue,
@PathVariable("secondValue") String secondValue) {
return firstValue + " - " + secondValue;
}
@GetMapping("/{firstValue}/{secondValue:.+}")
public String requestWithRegex(@PathVariable("firstValue") String firstValue,
@PathVariable("secondValue") String secondValue) {
return firstValue + " - " + secondValue;
}
@GetMapping("/{firstValue}/{secondValue}/")
public String requestWithSlash(@PathVariable("firstValue") String firstValue,
@PathVariable("secondValue") String secondValue) {
return firstValue + " - " + secondValue;
}
}

View File

@@ -0,0 +1,89 @@
package com.baeldung.pathvariable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.Optional;
@RestController
public class PathVariableAnnotationController {
@GetMapping("/api/employees/{id}")
@ResponseBody
public String getEmployeesById(@PathVariable String id) {
return "ID: " + id;
}
@GetMapping("/api/employeeswithvariable/{id}")
@ResponseBody
public String getEmployeesByIdWithVariableName(@PathVariable("id") String employeeId) {
return "ID: " + employeeId;
}
@GetMapping("/api/employees/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable String name) {
return "ID: " + id + ", name: " + name;
}
@GetMapping("/api/employeeswithmapvariable/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndNameWithMapVariable(@PathVariable Map<String, String> pathVarsMap) {
String id = pathVarsMap.get("id");
String name = pathVarsMap.get("name");
if (id != null && name != null) {
return "ID: " + id + ", name: " + name;
} else {
return "Missing Parameters";
}
}
@GetMapping(value = { "/api/employeeswithrequired", "/api/employeeswithrequired/{id}" })
@ResponseBody
public String getEmployeesByIdWithRequired(@PathVariable String id) {
return "ID: " + id;
}
@GetMapping(value = { "/api/employeeswithrequiredfalse", "/api/employeeswithrequiredfalse/{id}" })
@ResponseBody
public String getEmployeesByIdWithRequiredFalse(@PathVariable(required = false) String id) {
if (id != null) {
return "ID: " + id;
} else {
return "ID missing";
}
}
@GetMapping(value = { "/api/employeeswithoptional", "/api/employeeswithoptional/{id}" })
@ResponseBody
public String getEmployeesByIdWithOptional(@PathVariable Optional<String> id) {
if (id.isPresent()) {
return "ID: " + id.get();
} else {
return "ID missing";
}
}
@GetMapping(value = { "/api/defaultemployeeswithoptional", "/api/defaultemployeeswithoptional/{id}" })
@ResponseBody
public String getDefaultEmployeesByIdWithOptional(@PathVariable Optional<String> id) {
if (id.isPresent()) {
return "ID: " + id.get();
} else {
return "ID: Default Employee";
}
}
@GetMapping(value = { "/api/employeeswithmap/{id}", "/api/employeeswithmap" })
@ResponseBody
public String getEmployeesByIdWithMap(@PathVariable Map<String, String> pathVarsMap) {
String id = pathVarsMap.get("id");
if (id != null) {
return "ID: " + id;
} else {
return "ID missing";
}
}
}

View File

@@ -0,0 +1 @@
Hello World

View File

@@ -0,0 +1,27 @@
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- <mvc:annotation-driven/>-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<context:component-scan base-package="com.baeldung"/>
</beans>

View File

@@ -0,0 +1,31 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form Example - Register a Company</title>
</head>
<body>
<h3>Welcome, Enter The Company Details</h3>
<form:form method="POST" action="/spring-mvc-java/addCompany"
modelAttribute="company">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name"/></td>
</tr>
<tr>
<td><form:label path="id">Id</form:label></td>
<td><form:input path="id"/></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>

View File

@@ -0,0 +1,20 @@
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Company Information</h2>
<table>
<tr>
<td>Name :</td>
<td>${name}</td>
</tr>
<tr>
<td>ID :</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>

View File

@@ -0,0 +1,37 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form Example - Register an Employee</title>
</head>
<body>
<h3>Welcome, Enter The Employee Details</h3>
<form:form method="POST" action="/spring-mvc-basics/addEmployee" modelAttribute="employee">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="id">Id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td><form:label path="contactNumber">Contact Number</form:label></td>
<td><form:input path="contactNumber" /></td>
</tr>
<tr>
<td><form:label path="workingArea">Working Area</form:label></td>
<td><form:input path="workingArea" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

View File

@@ -0,0 +1,24 @@
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Employee Information</h2>
<table>
<tr>
<td>Name :</td>
<td>${name}</td>
</tr>
<tr>
<td>ID :</td>
<td>${id}</td>
</tr>
<tr>
<td>Contact Number :</td>
<td>${contactNumber}</td>
</tr>
</table>
</body>
</html>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Spring MVC Application 2</display-name>
<!-- Add Spring MVC DispatcherServlet as front controller -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

View File

@@ -0,0 +1,81 @@
package com.baeldung.cache;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
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.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.http.HttpHeaders.IF_UNMODIFIED_SINCE;
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration(classes = {CacheWebConfig.class, CacheWebConfig.class})
public class CacheControlControllerIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@BeforeEach
void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
void whenResponseBody_thenReturnCacheHeader() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/hello/baeldung"))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header()
.string("Cache-Control","max-age=60, must-revalidate, no-transform"));
}
@Test
void whenViewName_thenReturnCacheHeader() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/home/baeldung"))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Cache-Control","max-age=60, must-revalidate, no-transform"))
.andExpect(MockMvcResultMatchers.view().name("home"));
}
@Test
void whenStaticResources_thenReturnCacheHeader() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/resources/hello.css"))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Cache-Control","max-age=60, must-revalidate, no-transform"));
}
@Test
void whenInterceptor_thenReturnCacheHeader() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/login/baeldung"))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Cache-Control","max-age=60, must-revalidate, no-transform"));
}
@Test
void whenValidate_thenReturnCacheHeader() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(IF_UNMODIFIED_SINCE, "Tue, 04 Feb 2020 19:57:25 GMT");
this.mockMvc.perform(MockMvcRequestBuilders.get("/productInfo/baeldung").headers(headers))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().is(304));
}
}

View File

@@ -0,0 +1,40 @@
package com.baeldung.matrix;
import com.baeldung.matrix.config.MatrixWebConfig;
import com.baeldung.matrix.controller.EmployeeController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
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.*;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { MatrixWebConfig.class, EmployeeController.class })
public class EmployeeMvcIntegrationTest {
@Autowired
private WebApplicationContext webAppContext;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
}
@Test
public void whenEmployeeGETisPerformed_thenRetrievedStatusAndViewNameAndAttributeAreCorrect() throws Exception {
mockMvc.perform(get("/employee")).andExpect(status().isOk()).andExpect(view().name("employeeHome")).andExpect(model().attributeExists("employee")).andDo(print());
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.matrix;
import com.baeldung.matrix.config.MatrixWebConfig;
import com.baeldung.matrix.controller.EmployeeController;
import com.baeldung.matrix.model.Employee;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { MatrixWebConfig.class, EmployeeController.class })
public class EmployeeNoMvcIntegrationTest {
@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"));
}
}

View File

@@ -0,0 +1,73 @@
package com.baeldung.multipart.file;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
public class ConvertMultipartFileUnitTest {
/**
* Example of converting a {@link MultipartFile} to a {@link File} using {@link MultipartFile#getBytes()}.
*
* @throws IOException
*/
@Test
public void whenGetBytes_thenOK() throws IOException {
MultipartFile multipartFile = new MockMultipartFile("sourceFile.tmp", "Hello World".getBytes());
File file = new File("src/main/resources/targetFile.tmp");
try (OutputStream os = new FileOutputStream(file)) {
os.write(multipartFile.getBytes());
}
assertThat(FileUtils.readFileToString(new File("src/main/resources/targetFile.tmp"), "UTF-8")).isEqualTo("Hello World");
}
/**
* Example of converting a {@link MultipartFile} to a {@link File} using {@link MultipartFile#getInputStream()}.
*
* @throws IOException
*/
@Test
public void whenGetInputStream_thenOK() throws IOException {
MultipartFile multipartFile = new MockMultipartFile("sourceFile.tmp", "Hello World".getBytes());
InputStream initialStream = multipartFile.getInputStream();
byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
File targetFile = new File("src/main/resources/targetFile.tmp");
try (OutputStream outStream = new FileOutputStream(targetFile)) {
outStream.write(buffer);
}
assertThat(FileUtils.readFileToString(new File("src/main/resources/targetFile.tmp"), "UTF-8")).isEqualTo("Hello World");
}
/**
* Example of converting a {@link MultipartFile} to a {@link File} using {@link MultipartFile#transferTo(File)}.
*
* @throws IOException
*/
@Test
public void whenTransferTo_thenOK() throws IllegalStateException, IOException {
MultipartFile multipartFile = new MockMultipartFile("sourceFile.tmp", "Hello World".getBytes());
File file = new File("src/main/resources/targetFile.tmp");
multipartFile.transferTo(file);
assertThat(FileUtils.readFileToString(new File("src/main/resources/targetFile.tmp"), "UTF-8")).isEqualTo("Hello World");
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.multiparttesting;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.matrix.config.MatrixWebConfig;
@WebAppConfiguration
@ContextConfiguration(classes = { MatrixWebConfig.class, MultipartPostRequestController.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class MultipartPostRequestControllerUnitTest {
@Autowired
private WebApplicationContext webApplicationContext;
@Test
public void whenFileUploaded_thenVerifyStatus() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "hello.txt", MediaType.TEXT_PLAIN_VALUE, "Hello, World!".getBytes());
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
mockMvc.perform(multipart("/upload").file(file)).andExpect(status().isOk());
}
}