[JAVA-8295] Split spring-mvc-xml module

This commit is contained in:
Haroon Khan
2021-12-13 20:26:29 +00:00
parent a0e52c907b
commit f3983e8cba
26 changed files with 363 additions and 37 deletions

View File

@@ -12,12 +12,10 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Returning Image/Media Data with Spring MVC](https://www.baeldung.com/spring-mvc-image-media-data)
- [Geolocation by IP in Java](https://www.baeldung.com/geolocation-by-ip-with-maxmind)
- [Guide to JavaServer Pages (JSP)](https://www.baeldung.com/jsp)
- [Exploring SpringMVCs Form Tag Library](https://www.baeldung.com/spring-mvc-form-tags)
- [web.xml vs Initializer with Spring](https://www.baeldung.com/spring-xml-vs-java-config)
- [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml)
- [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable)
- [Debugging the Spring MVC 404 “No mapping found for HTTP request” Error](https://www.baeldung.com/spring-mvc-404-error)
- [Introduction to Servlets and Servlet Containers](https://www.baeldung.com/java-servlets-containers-intro)
- More articles: [[more -->]](../spring-mvc-xml-2)
## Spring MVC with XML Configuration Example Project

View File

@@ -39,11 +39,6 @@
<version>${jstl.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<!-- Json conversion -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>

View File

@@ -1,62 +0,0 @@
package com.baeldung.spring;
import java.util.Locale;
import java.util.ResourceBundle;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.MessageSourceResourceBundle;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
//@EnableWebMvc
//@Configuration
@ComponentScan("com.baeldung.spring")
public class ClientWebConfigJava implements WebMvcConfigurer {
public ClientWebConfigJava() {
super();
}
@Bean
public MessageSource messageSource() {
final ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
ms.setBasenames("messages");
return ms;
}
@Bean
public ResourceBundle getBeanResourceBundle() {
final Locale locale = Locale.getDefault();
return new MessageSourceResourceBundle(messageSource(), locale);
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}

View File

@@ -1,21 +0,0 @@
package com.baeldung.spring.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.validation.ConstraintViolationException;
@ControllerAdvice
public class ConstraintViolationExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {ConstraintViolationException.class})
protected ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException e, WebRequest request) {
return handleExceptionInternal(e, e.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
}

View File

@@ -1,83 +0,0 @@
package com.baeldung.spring.controller;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import com.baeldung.spring.form.Person;
import com.baeldung.spring.validator.PersonValidator;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class PersonController {
@Autowired
PersonValidator validator;
@RequestMapping(value = "/person", method = RequestMethod.GET)
public ModelAndView showForm(final Model model) {
initData(model);
return new ModelAndView("personForm", "person", new Person());
}
@RequestMapping(value = "/addPerson", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, final ModelMap modelMap, final Model model) {
validator.validate(person, result);
if (result.hasErrors()) {
initData(model);
return "personForm";
}
modelMap.addAttribute("person", person);
return "personView";
}
private void initData(final Model model) {
final List<String> favouriteLanguageItem = new ArrayList<String>();
favouriteLanguageItem.add("Java");
favouriteLanguageItem.add("C++");
favouriteLanguageItem.add("Perl");
model.addAttribute("favouriteLanguageItem", favouriteLanguageItem);
final List<String> jobItem = new ArrayList<String>();
jobItem.add("Full time");
jobItem.add("Part time");
model.addAttribute("jobItem", jobItem);
final Map<String, String> countryItems = new LinkedHashMap<String, String>();
countryItems.put("US", "United Stated");
countryItems.put("IT", "Italy");
countryItems.put("UK", "United Kingdom");
countryItems.put("FR", "Grance");
model.addAttribute("countryItems", countryItems);
final List<String> fruit = new ArrayList<String>();
fruit.add("Banana");
fruit.add("Mango");
fruit.add("Apple");
model.addAttribute("fruit", fruit);
final List<String> books = new ArrayList<String>();
books.add("The Great Gatsby");
books.add("Nineteen Eighty-Four");
books.add("The Lord of the Rings");
model.addAttribute("books", books);
}
}

View File

@@ -1,31 +0,0 @@
package com.baeldung.spring.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.*;
@Controller
@RequestMapping("/public/api/1")
@Validated
public class RequestAndPathVariableValidationController {
@GetMapping("/name-for-day")
public String getNameOfDayByNumberRequestParam(@RequestParam @Min(1) @Max(7) Integer dayOfWeek) {
return dayOfWeek + "";
}
@GetMapping("/name-for-day/{dayOfWeek}")
public String getNameOfDayByPathVariable(@PathVariable("dayOfWeek") @Min(1) @Max(7) Integer dayOfWeek) {
return dayOfWeek + "";
}
@GetMapping("/valid-name")
public void validStringRequestParam(@RequestParam @NotBlank @Size(max = 10) @Pattern(regexp = "^[A-Z][a-zA-Z0-9]+$") String name) {
}
}

View File

@@ -1,153 +0,0 @@
package com.baeldung.spring.form;
import java.util.List;
import javax.validation.constraints.NotEmpty;
import org.springframework.web.multipart.MultipartFile;
public class Person {
private long id;
private String name;
private String email;
private String dateOfBirth;
@NotEmpty
private String password;
private String sex;
private String country;
private String book;
private String job;
private boolean receiveNewsletter;
private String[] hobbies;
private List<String> favouriteLanguage;
private List<String> fruit;
private String notes;
private MultipartFile file;
public Person() {
super();
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(final String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(final String sex) {
this.sex = sex;
}
public String getCountry() {
return country;
}
public void setCountry(final String country) {
this.country = country;
}
public String getJob() {
return job;
}
public void setJob(final String job) {
this.job = job;
}
public boolean isReceiveNewsletter() {
return receiveNewsletter;
}
public void setReceiveNewsletter(final boolean receiveNewsletter) {
this.receiveNewsletter = receiveNewsletter;
}
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(final String[] hobbies) {
this.hobbies = hobbies;
}
public List<String> getFavouriteLanguage() {
return favouriteLanguage;
}
public void setFavouriteLanguage(final List<String> favouriteLanguage) {
this.favouriteLanguage = favouriteLanguage;
}
public String getNotes() {
return notes;
}
public void setNotes(final String notes) {
this.notes = notes;
}
public List<String> getFruit() {
return fruit;
}
public void setFruit(final List<String> fruit) {
this.fruit = fruit;
}
public String getBook() {
return book;
}
public void setBook(final String book) {
this.book = book;
}
public MultipartFile getFile() {
return file;
}
public void setFile(final MultipartFile file) {
this.file = file;
}
}

View File

@@ -1,22 +0,0 @@
package com.baeldung.spring.validator;
import com.baeldung.spring.form.Person;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Component
public class PersonValidator implements Validator {
@Override
public boolean supports(final Class calzz) {
return Person.class.isAssignableFrom(calzz);
}
@Override
public void validate(final Object obj, final Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name");
}
}

View File

@@ -1,120 +0,0 @@
<%@ 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 Person</title>
</head>
<style>
.error {
color: #ff0000;
}
.errorbox {
background-color: #ffEEEE;
border: 2px solid #ff0000;
}
</style>
<body>
<h3>Welcome, Enter the Person Details</h3>
<form:form method="POST" action="/spring-mvc-xml/addPerson" modelAttribute="person">
<form:errors path="*" cssClass="errorbox" element="div" />
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssClass="error" element="div"/></td>
</tr>
<tr>
<td><form:label path="email">E-mail</form:label></td>
<td><form:input type="email" path="email" /></td>
<td><form:errors path="email" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="dateOfBirth">Date of birth</form:label></td>
<td><form:input type="date" path="dateOfBirth" /></td>
</tr>
<tr>
<td><form:label path="password">Password</form:label></td>
<td><form:password path="password" /></td>
<td><form:errors path="password" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="sex">Sex</form:label></td>
<td>
Male: <form:radiobutton path="sex" value="M"/> <br/>
Female: <form:radiobutton path="sex" value="F"/>
</td>
</tr>
<tr>
<td><form:label path="job">Job</form:label></td>
<td>
<form:radiobuttons items="${jobItem}" path="job" />
</td>
</tr>
<tr>
<td><form:label path="country">Country</form:label></td>
<td>
<form:select path="country" items="${countryItems}" />
</td>
</tr>
<tr>
<td><form:label path="book">Book</form:label></td>
<td>
<form:select path="book">
<form:option value="-" label="--Please Select"/>
<form:options items="${books}" />
</form:select>
</td>
</tr>
<tr>
<td><form:label path="fruit">Fruit</form:label></td>
<td>
<form:select path="fruit" items="${fruit}" multiple="true"/>
</td>
</tr>
<tr>
<td><form:label path="receiveNewsletter">Receive newsletter</form:label></td>
<td><form:checkbox path="receiveNewsletter" rows="3" cols="20"/></td>
</tr>
<tr>
<td><form:label path="hobbies">Hobbies</form:label></td>
<td>
Bird watching: <form:checkbox path="hobbies" value="Bird watching"/>
Astronomy: <form:checkbox path="hobbies" value="Astronomy"/>
Snowboarding: <form:checkbox path="hobbies" value="Snowboarding"/>
</td>
</tr>
<tr>
<td><form:label path="favouriteLanguage">Favourite languages</form:label></td>
<td>
<form:checkboxes items="${favouriteLanguageItem}" path="favouriteLanguage" />
</td>
</tr>
<tr>
<td><form:label path="notes">Notes</form:label></td>
<td><form:textarea path="notes" rows="3" cols="20"/></td>
</tr>
<tr>
<td><form:hidden path="id" value="12345"/></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

View File

@@ -1,65 +0,0 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Person Information</h2>
<table>
<tr>
<td>Id :</td>
<td>${person.id}</td>
</tr>
<tr>
<td>Name :</td>
<td>${person.name}</td>
</tr>
<tr>
<td>Date of birth :</td>
<td>${person.dateOfBirth}</td>
</tr>
<tr>
<td>Password :</td>
<td>${person.password}</td>
</tr>
<tr>
<td>Sex :</td>
<td>${person.sex}</td>
</tr>
<tr>
<td>Job :</td>
<td>${person.job}</td>
</tr>
<tr>
<td>Country :</td>
<td>${person.country}</td>
</tr>
<tr>
<td>Fruit :</td>
<td><c:forEach items="${person.fruit}" var="current">[<c:out value="${current}" />]</c:forEach></td>
</tr>
<tr>
<td>Book :</td>
<td>${person.book}</td>
</tr>
<tr>
<td>Receive Newsletter :</td>
<td>${person.receiveNewsletter}</td>
</tr>
<tr>
<td>Hobbies :</td>
<td><c:forEach items="${person.hobbies}" var="current">[<c:out value="${current}" />]</c:forEach></td>
</tr>
<tr>
<td>Favourite Languages :</td>
<td><c:forEach items="${person.favouriteLanguage}" var="current">[<c:out value="${current}" />]</c:forEach></td>
</tr>
<tr>
<td>Notes :</td>
<td>${person.notes}</td>
</tr>
</table>
</body>
</html>

View File

@@ -1,73 +0,0 @@
package com.baeldung.spring.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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.spring.ClientWebConfig;
import com.baeldung.spring.ClientWebConfigJava;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ClientWebConfigJava.class)
@WebAppConfiguration
public class RequestAndPathVariableValidationControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void getNameOfDayByNumberRequestParam_whenGetWithProperRequestParam_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day").param("dayOfWeek", Integer.toString(5)))
.andExpect(status().isOk());
}
@Test
public void getNameOfDayByNumberRequestParam_whenGetWithRequestParamOutOfRange_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day").param("dayOfWeek", Integer.toString(15)))
.andExpect(status().isBadRequest());
}
@Test
public void getNameOfDayByPathVariable_whenGetWithProperRequestParam_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day/{dayOfWeek}", Integer.toString(5))).andExpect(status().isOk());
}
@Test
public void getNameOfDayByPathVariable_whenGetWithRequestParamOutOfRange_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day/{dayOfWeek}", Integer.toString(15)))
.andExpect(status().isBadRequest());
}
@Test
public void validStringRequestParam_whenGetWithProperRequestParam_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/1/valid-name").param("name", "John")).andExpect(status().isOk());
}
@Test
public void validStringRequestParam_whenGetWithTooLongRequestParam_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/valid-name").param("name", "asdfghjklqw"))
.andExpect(status().isBadRequest());
}
@Test
public void validStringRequestParam_whenGetWithLowerCaseRequestParam_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/valid-name").param("name", "john")).andExpect(status().isBadRequest());
}
}