[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

@@ -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 XML
This module contains articles about Spring MVC with XML configuration
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Exploring SpringMVCs Form Tag Library](https://www.baeldung.com/spring-mvc-form-tags)
- [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)
- More articles: [[<-- prev]](../spring-mvc-xml)

View File

@@ -0,0 +1,101 @@
<?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-xml-2</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-mvc-xml-2</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-web-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<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>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>${javax.el.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-mvc-xml</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<spring-boot.version>1.5.10.RELEASE</spring-boot.version>
<mysql-connector-java.version>5.1.40</mysql-connector-java.version>
<httpcore.version>4.4.5</httpcore.version>
<httpclient.version>4.5.2</httpclient.version>
<hibernate-validator.version>6.0.10.Final</hibernate-validator.version>
<javax.el.version>3.0.1-b08</javax.el.version>
<guava.version>19.0</guava.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>
</project>

View File

@@ -0,0 +1,17 @@
package com.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ImportResource("classpath:webMvcConfig.xml")
@Configuration
@ComponentScan
public class ClientWebConfig implements WebMvcConfigurer {
public ClientWebConfig() {
super();
}
}

View File

@@ -0,0 +1,63 @@
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.annotation.Configuration;
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

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

@@ -0,0 +1,16 @@
package com.baeldung.spring.nomapping;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class GreetingController {
@RequestMapping(value = "/greeting", method = RequestMethod.GET)
public String get(ModelMap model) {
model.addAttribute("message", "Hello, World!");
return "greeting";
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.spring.paramsvalidation;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@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

@@ -0,0 +1,153 @@
package com.baeldung.spring.taglibrary;
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

@@ -0,0 +1,80 @@
package com.baeldung.spring.taglibrary;
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;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@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

@@ -0,0 +1,21 @@
package com.baeldung.spring.taglibrary;
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

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,3 @@
required.name = Name is required!
NotEmpty.person.password = Password is required!

View File

@@ -0,0 +1,40 @@
<?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"
>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>image/jpeg</value>
<value>image/png</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<context:component-scan base-package="com.baeldung.spring"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:view-controller path="/sample.html" view-name="sample"/>
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
<property name="basename" value="messages" />
</bean>
<bean id="validationProcessor" class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor" />
</beans>

View File

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

View File

@@ -0,0 +1,9 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Greeting</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>

View File

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

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

@@ -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,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
>
<display-name>Spring MVC XML Application</display-name>
<!-- Spring root -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring child -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- additional config -->
<session-config>
<session-timeout>10</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<location>/errors</location>
</error-page>
</web-app>

View File

@@ -0,0 +1,15 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Examples</title>
</head>
<body>
<h1>Spring MVC Examples</h1>
</body>
</html>

View File

@@ -0,0 +1,19 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.baeldung.spring.ClientWebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ClientWebConfig.class)
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@@ -0,0 +1,71 @@
package com.baeldung.spring.paramsvalidation;
import com.baeldung.spring.ClientWebConfigJava;
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 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());
}
}