Merge pull request #7032 from rozagerardo/rozagerardo/BAEL-10914_Create-spring-mvc-basics-from-spring-mvc-java

Rozagerardo/bael 10914 create spring mvc basics from spring mvc java
This commit is contained in:
Loredana Crusoveanu 2019-07-14 18:51:27 +03:00 committed by GitHub
commit cc00051d31
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
68 changed files with 1138 additions and 482 deletions

4
.gitignore vendored
View File

@ -1,4 +1,5 @@
*/bin/*
bin/
*.class
@ -21,6 +22,9 @@
*.iws
out/
# VSCode
.vscode/
# Mac
.DS_Store

13
spring-mvc-basics/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,18 @@
=========
## Spring MVC Basics with Java Configuration Example Project
### The Course
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)
- [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)
- [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)
- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation)

54
spring-mvc-basics/pom.xml Normal file
View File

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-mvc-basics</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-mvc-basics</name>
<packaging>jar</packaging>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- to enable JSP -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.Application</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -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);
}
}

View File

@ -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("/");
}
}

View File

@ -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<? extends Payload>[] 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<? extends Payload>[] payload() default {};
}

View File

@ -1,17 +1,17 @@
package com.baeldung.customvalidator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class ContactNumberValidator implements ConstraintValidator<ContactNumberConstraint, String> {
@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<ContactNumberConstraint, String> {
@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);
}
}

View File

@ -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;
}
}

View File

@ -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 + "]";
}
}

View File

@ -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;

View File

@ -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;
}
}

View File

@ -0,0 +1,67 @@
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;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
import org.springframework.web.servlet.view.XmlViewResolver;
//@EnableWebMvc
//@ComponentScan(basePackages = { "com.baeldung.web.controller" })
@Configuration
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(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;
}
/**
* 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);
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.web.controller;
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;
@Controller
public class EmployeeController {
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";
}
@ModelAttribute
public void addAttributes(final Model model) {
model.addAttribute("msg", "Welcome to the Netherlands!");
}
}

View File

@ -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<String> get() {
return new ResponseEntity<String>("GET Response", HttpStatus.OK);
}
@GetMapping("/get/{id}")
public @ResponseBody ResponseEntity<String> getById(@PathVariable String id) {
return new ResponseEntity<String>("GET Response : " + id, HttpStatus.OK);
}
@PostMapping("/post")
public @ResponseBody ResponseEntity<String> post() {
return new ResponseEntity<String>("POST Response", HttpStatus.OK);
}
@PutMapping("/put")
public @ResponseBody ResponseEntity<String> put() {
return new ResponseEntity<String>("PUT Response", HttpStatus.OK);
}
@DeleteMapping("/delete")
public @ResponseBody ResponseEntity<String> delete() {
return new ResponseEntity<String>("DELETE Response", HttpStatus.OK);
}
@PatchMapping("/patch")
public @ResponseBody ResponseEntity<String> patch() {
return new ResponseEntity<String>("PATCH Response", HttpStatus.OK);
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,24 @@
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";
}
@GetMapping("/sample2")
public String showForm2() {
return "sample2";
}
@GetMapping("/sample3")
public String showForm3() {
return "sample3";
}
}

View File

@ -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";
}
}

View File

@ -0,0 +1,7 @@
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

View File

@ -0,0 +1,20 @@
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="org.baeldung.controller.xml" />
<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>
</beans>

View File

@ -0,0 +1,3 @@
sample2.(class)=org.springframework.web.servlet.view.JstlView
sample2.url=/WEB-INF/view2/sample2.jsp

View File

@ -1,10 +1,10 @@
<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-4.2.xsd">
<bean id="sample" class="org.springframework.web.servlet.view.JstlView">
<property name="url" value="/WEB-INF/view/sample.jsp" />
</bean>
<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-4.2.xsd">
<bean id="sample3" class="org.springframework.web.servlet.view.JstlView">
<property name="url" value="/WEB-INF/view3/sample3.jsp" />
</bean>
</beans>

View File

@ -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"%>
<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><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

View File

@ -0,0 +1,25 @@
<%@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>
<h3>${msg}</h3>
<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,7 @@
<html>
<head></head>
<body>
<h1>This is the body of the index view</h1>
</body>
</html>

View File

@ -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" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Sample Form</title>
<style>
body { background-color: #eee; font: helvetica; }
#container { width: 500px; background-color: #fff; margin: 30px auto; padding: 30px; border-radius: 5px; }
.green { font-weight: bold; color: green; }
.message { margin-bottom: 10px; }
label {width:70px; display:inline-block;}
input { display:inline-block; margin-right: 10px; }
form {line-height: 160%; }
.hide { display: none; }
.error { color: red; font-size: 0.9em; font-weight: bold; }
</style>
</head>
<body>
<div id="container">
<h2>Phone Number</h2>
<c:if test="${not empty message}"><div class="message green">${message}</div></c:if>
<form:form action="/spring-mvc-java/addValidatePhone" modelAttribute="validatedPhone">
<label for="phoneInput">Phone: </label>
<form:input path="phone" id="phoneInput" />
<form:errors path="phone" cssClass="error" />
<br/>
<input type="submit" value="Submit" />
</form:form>
</div>
</body>
</html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Sample Form</title>
<style>
body { background-color: #eee; font: helvetica; }
#container { width: 500px; background-color: #fff; margin: 30px auto; padding: 30px; border-radius: 5px; }
.green { font-weight: bold; color: green; }
.message { margin-bottom: 10px; }
label {width:70px; display:inline-block;}
input { display:inline-block; margin-right: 10px; }
form {line-height: 160%; }
.hide { display: none; }
.error { color: red; font-size: 0.9em; font-weight: bold; }
</style>
</head>
<body>
<div id="container">
<h2>Phone Number</h2>
<c:if test="${not empty message}"><div class="message green">${message}</div></c:if>
<form:form action="/spring-mvc-basics/addValidatePhone" modelAttribute="validatedPhone">
<label for="phoneInput">Phone: </label>
<form:input path="phone" id="phoneInput" />
<form:errors path="phone" cssClass="error" />
<br/>
<input type="submit" value="Submit" />
</form:form>
</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,7 @@
<html>
<head></head>
<body>
<h1>This is the body of the sample2 view</h1>
</body>
</html>

View File

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

View File

@ -0,0 +1,13 @@
package com.baeldung;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -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();
}

View File

@ -16,7 +16,7 @@ public class HandlerMappingDefaultConfig {
}
@Bean
public WelcomeController welcome() {
public WelcomeController welcomeDefaultMappingConfig() {
return new WelcomeController();
}

View File

@ -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<String, Object> urlMap = new HashMap<>();
@ -37,7 +37,7 @@ public class HandlerMappingPrioritiesConfig {
return new SimpleUrlMappingController();
}
@Bean("/welcome")
@Bean("/welcome-priorities")
public BeanNameHandlerMappingController beanNameHandlerMapping() {
return new BeanNameHandlerMappingController();
}

View File

@ -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<String, Object> 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();
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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));
}
}

View File

@ -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<NameValuePair> 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!"));
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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();
}

View File

@ -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));

View File

@ -9,26 +9,16 @@ 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)
- [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)
- [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)
- [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)
- [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)

View File

@ -12,13 +12,11 @@ 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;
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;
@ -26,8 +24,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;
@ -97,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() {
@ -110,22 +101,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<HttpMessageConverter<?>> converters) {

View File

@ -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<Long, Employee> 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<List<Employee>> getEmployeeByNameAndBeginContactNumber(@PathVariable final String name, @MatrixVariable final String beginContactNumber) {

View File

@ -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<String> get() {
return new ResponseEntity<String>("GET Response", HttpStatus.OK);
}
@GetMapping("/get/{id}")
public @ResponseBody ResponseEntity<String> getById(@PathVariable String id) {
return new ResponseEntity<String>("GET Response : " + id, HttpStatus.OK);
}
@PostMapping("/post")
public @ResponseBody ResponseEntity<String> post() {
return new ResponseEntity<String>("POST Response", HttpStatus.OK);
}
@PutMapping("/put")
public @ResponseBody ResponseEntity<String> put() {
return new ResponseEntity<String>("PUT Response", HttpStatus.OK);
}
@DeleteMapping("/delete")
public @ResponseBody ResponseEntity<String> delete() {
return new ResponseEntity<String>("DELETE Response", HttpStatus.OK);
}
@PatchMapping("/patch")
public @ResponseBody ResponseEntity<String> patch() {
return new ResponseEntity<String>("PATCH Response", HttpStatus.OK);
}
}

View File

@ -1,3 +0,0 @@
sample.(class)=org.springframework.web.servlet.view.JstlView
sample.url=/WEB-INF/view/sample.jsp

View File

@ -8,7 +8,7 @@
<body>
<h3>Welcome, Enter The Employee Details</h3>
<form:form method="POST" action="/spring-mvc-java/addEmployee" modelAttribute="employee">
<form:form method="POST" action="/spring-mvc-basics/addEmployee" modelAttribute="employee">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>

View File

@ -6,7 +6,6 @@
<body>
<h2>Submitted Employee Information</h2>
<h3>${msg}</h3>
<table>
<tr>
<td>Name :</td>
@ -20,10 +19,6 @@
<td>Contact Number :</td>
<td>${contactNumber}</td>
</tr>
<tr>
<td>Working Area :</td>
<td>${workingArea}</td>
</tr>
</table>
</body>
</html>

View File

@ -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"));
}
}

View File

@ -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());
}
}