[JAVA-8285] Split spring-mvc-basics into a new module

This commit is contained in:
Haroon Khan 2021-12-11 19:48:40 +00:00
parent 17981c9036
commit e3a777298f
36 changed files with 606 additions and 31 deletions

View File

@ -12,5 +12,4 @@ This module contains articles about Spring MVC
- [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405)
- [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param)
- [Spring @RequestParam vs @PathVariable Annotations](https://www.baeldung.com/spring-requestparam-vs-pathvariable)
- More articles: [[more -->]](/spring-mvc-basics-3)
- More articles: [[<-- prev]](/spring-mvc-basics)
- More articles: [[<-- prev]](../spring-mvc-basics)[[more -->]](../spring-mvc-basics-3)

View File

@ -10,4 +10,4 @@ This module contains articles about Spring MVC
- [Using Enums as Request Parameters in Spring](https://www.baeldung.com/spring-enum-request-param)
- [Guide to Flash Attributes in a Spring Web Application](https://www.baeldung.com/spring-web-flash-attributes)
- [Reading HttpServletRequest Multiple Times in Spring](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times)
- More articles: [[<-- prev]](/spring-mvc-basics-2)[[more -->]](/spring-mvc-basics-4)
- More articles: [[<-- prev]](../spring-mvc-basics-2)[[more -->]](../spring-mvc-basics-4)

View File

@ -10,4 +10,4 @@ The "REST With Spring" Classes: https://bit.ly/restwithspring
- [Spring Optional Path variables](https://www.baeldung.com/spring-optional-path-variables)
- [JSON Parameters with Spring MVC](https://www.baeldung.com/spring-mvc-send-json-parameters)
- [How to Set JSON Content Type In Spring MVC](https://www.baeldung.com/spring-mvc-set-json-content-type)
- More articles: [[<-- prev]](/spring-mvc-basics-3)
- More articles: [[<-- prev]](../spring-mvc-basics-3)[[more -->]](../spring-mvc-basics-5)

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,14 @@
## Spring MVC Basics
This module contains articles about the basics of Spring MVC. Articles about more specific areas of Spring MVC have
their own module.
### The Course
The "REST With Spring" Classes: https://bit.ly/restwithspring
### Relevant Articles:
- [Spring MVC Custom Validation](https://www.baeldung.com/spring-mvc-custom-validator)
- [Using Spring @ResponseStatus to Set HTTP Status Code](https://www.baeldung.com/spring-response-status)
- [Spring MVC and the @ModelAttribute Annotation](https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation)
- [The HttpMediaTypeNotAcceptableException in Spring MVC](https://www.baeldung.com/spring-httpmediatypenotacceptable)
- More articles: [[<-- prev]](../spring-mvc-basics-4)

View File

@ -0,0 +1,57 @@
<?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>
<artifactId>spring-mvc-basics-5</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-mvc-basics-5</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- to enable JSP -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</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>
<finalName>spring-mvc-basics</finalName>
<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

@ -1,6 +1,4 @@
package com.baeldung.web.controller;
import javax.validation.Valid;
package com.baeldung.customvalidator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
@ -8,7 +6,7 @@ import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import com.baeldung.model.NewUserForm;
import javax.validation.Valid;
@Controller
public class NewUserController {

View File

@ -1,4 +1,4 @@
package com.baeldung.model;
package com.baeldung.customvalidator;
import com.baeldung.customvalidator.FieldsValueMatch;

View File

@ -1,4 +1,4 @@
package com.baeldung.model;
package com.baeldung.customvalidator;
import com.baeldung.customvalidator.ContactNumberConstraint;

View File

@ -1,4 +1,4 @@
package com.baeldung.web.controller;
package com.baeldung.customvalidator;
import javax.validation.Valid;
@ -8,8 +8,6 @@ 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 {

View File

@ -0,0 +1,61 @@
package com.baeldung.modelattribute;
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,58 @@
package com.baeldung.modelattribute;
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 java.util.HashMap;
import java.util.Map;
@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,42 @@
package com.baeldung.responsestatus;
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,47 @@
package com.baeldung.responsestatus;
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;
@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,49 @@
package com.baeldung.spring.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
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.resource.PathResourceResolver;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@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;
}
/** Static resource locations */
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**/*")
.addResourceLocations("/", "/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
@Bean
public BeanNameViewResolver beanNameViewResolver(){
BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver();
beanNameViewResolver.setOrder(1);
return beanNameViewResolver;
}
}

View File

@ -0,0 +1 @@
server.servlet.context-path=/spring-mvc-basics

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

@ -0,0 +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-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,55 @@
<%@ 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>User 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:160px; 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>New User</h2>
<c:if test="${not empty message}"><div class="message green">${message}</div></c:if>
<form:form action="/spring-mvc-basics/user" modelAttribute="newUserForm">
<form:errors path="" cssClass="error"/>
<br />
<label for="email">Email: </label>
<form:input path="email" id="emailInput" />
<form:errors path="email" cssClass="error" />
<br/>
<label for="verifyEmail">Verify email: </label>
<form:input path="verifyEmail" id="verifyEmailInput" />
<form:errors path="verifyEmail" cssClass="error" />
<br/>
<label for="password">Password: </label>
<form:input path="password" type="password" id="passwordInput" />
<form:errors path="password" cssClass="error" />
<br/>
<label for="verifyPassword">Verify password: </label>
<form:input path="verifyPassword" type="password" id="verifyPasswordInput" />
<form:errors path="verifyPassword" cssClass="error" />
<br/>
<input type="submit" value="Submit" />
</form:form>
</div>
</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 SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.web.controller;
package com.baeldung.customvalidator;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;

View File

@ -1,10 +1,4 @@
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;
package com.baeldung.customvalidator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -13,6 +7,12 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
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;
public class CustomMVCValidatorIntegrationTest {
private MockMvc mockMvc;

View File

@ -1,4 +1,4 @@
package com.baeldung.web.controller;
package com.baeldung.modelattribute;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;

View File

@ -0,0 +1,52 @@
package com.baeldung.responsestatus;
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 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;
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,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -14,8 +14,4 @@ The "REST With Spring" Classes: https://bit.ly/restwithspring
- [Guide to Spring Handler Mappings](https://www.baeldung.com/spring-handler-mappings)
- [Spring MVC Content Negotiation](https://www.baeldung.com/spring-mvc-content-negotiation-json-xml)
- [Spring @RequestMapping New Shortcut Annotations](https://www.baeldung.com/spring-new-requestmapping-shortcuts)
- [Spring MVC Custom Validation](https://www.baeldung.com/spring-mvc-custom-validator)
- [Using Spring @ResponseStatus to Set HTTP Status Code](https://www.baeldung.com/spring-response-status)
- [Spring MVC and the @ModelAttribute Annotation](https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation)
- [The HttpMediaTypeNotAcceptableException in Spring MVC](https://www.baeldung.com/spring-httpmediatypenotacceptable)
- More articles: [[more -->]](/spring-mvc-basics-2)
- More articles: [[more -->]](../spring-mvc-basics-2)

View File

@ -20,10 +20,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>