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
68 changed files with 1138 additions and 482 deletions

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

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

@@ -1,31 +0,0 @@
package com.baeldung.customvalidator;
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;
@Constraint(validatedBy = FieldsValueMatchValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldsValueMatch {
String message() default "Fields values don't match!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String field();
String fieldMatch();
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface List {
FieldsValueMatch[] value();
}
}

View File

@@ -1,31 +0,0 @@
package com.baeldung.customvalidator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.BeanWrapperImpl;
public class FieldsValueMatchValidator implements ConstraintValidator<FieldsValueMatch, Object> {
private String field;
private String fieldMatch;
public void initialize(FieldsValueMatch constraintAnnotation) {
this.field = constraintAnnotation.field();
this.fieldMatch = constraintAnnotation.fieldMatch();
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
Object fieldValue = new BeanWrapperImpl(value).getPropertyValue(field);
Object fieldMatchValue = new BeanWrapperImpl(value).getPropertyValue(fieldMatch);
if (fieldValue != null) {
return fieldValue.equals(fieldMatchValue);
} else {
return fieldMatchValue == null;
}
}
}

View File

@@ -1,58 +0,0 @@
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!")
})
public class NewUserForm {
private String email;
private String verifyEmail;
private String password;
private String verifyPassword;
public NewUserForm() {
}
public NewUserForm(String email, String verifyEmail, String password, String verifyPassword) {
super();
this.email = email;
this.verifyEmail = verifyEmail;
this.password = password;
this.verifyPassword = verifyPassword;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getVerifyEmail() {
return verifyEmail;
}
public void setVerifyEmail(String verifyEmail) {
this.verifyEmail = verifyEmail;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getVerifyPassword() {
return verifyPassword;
}
public void setVerifyPassword(String verifyPassword) {
this.verifyPassword = verifyPassword;
}
}

View File

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

@@ -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,31 +0,0 @@
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.NewUserForm;
@Controller
public class NewUserController {
@GetMapping("/user")
public String loadFormPage(Model model) {
model.addAttribute("newUserForm", new NewUserForm());
return "userHome";
}
@PostMapping("/user")
public String submitForm(@Valid NewUserForm newUserForm, BindingResult result, Model model) {
if (result.hasErrors()) {
return "userHome";
}
model.addAttribute("message", "Valid form");
return "userHome";
}
}

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,31 +0,0 @@
package com.baeldung.web.controller;
import org.springframework.stereotype.Controller;
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 com.baeldung.model.Book;
@Controller
@RequestMapping("books")
public class SimpleBookController {
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody Book getBook(@PathVariable int id) {
return findBookById(id);
}
private Book findBookById(int id) {
Book book = null;
if (id == 42) {
book = new Book();
book.setId(id);
book.setAuthor("Douglas Adamas");
book.setTitle("Hitchhiker's guide to the galaxy");
}
return book;
}
}

View File

@@ -1,29 +0,0 @@
package com.baeldung.web.controller;
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.RestController;
import com.baeldung.model.Book;
@RestController
@RequestMapping("books-rest")
public class SimpleBookRestController {
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
public Book getBook(@PathVariable int id) {
return findBookById(id);
}
private Book findBookById(int id) {
Book book = null;
if (id == 42) {
book = new Book();
book.setId(id);
book.setAuthor("Douglas Adamas");
book.setTitle("Hitchhiker's guide to the galaxy");
}
return book;
}
}

View File

@@ -1,32 +0,0 @@
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";
}
}

View File

@@ -1,16 +0,0 @@
package com.baeldung.web.controller.handlermapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BeanNameHandlerMappingController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("bean-name-handler-mapping");
return model;
}
}

View File

@@ -1,16 +0,0 @@
package com.baeldung.web.controller.handlermapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SimpleUrlMappingController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("simple-url-handler-mapping");
return model;
}
}

View File

@@ -1,17 +0,0 @@
package com.baeldung.web.controller.handlermapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class WelcomeController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
return new ModelAndView("welcome");
}
}

View File

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

View File

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

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

View File

@@ -1,23 +0,0 @@
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;
@Configuration
public class BeanNameUrlHandlerMappingConfig {
@Bean
BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() {
return new BeanNameUrlHandlerMapping();
}
@Bean("/beanNameUrl")
public WelcomeController welcome() {
return new WelcomeController();
}
}

View File

@@ -1,23 +0,0 @@
package com.baeldung.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baeldung.web.controller.handlermapping.BeanNameHandlerMappingController;
import com.baeldung.web.controller.handlermapping.WelcomeController;
@Configuration
public class HandlerMappingDefaultConfig {
@Bean("/welcome")
public BeanNameHandlerMappingController beanNameHandlerMapping() {
return new BeanNameHandlerMappingController();
}
@Bean
public WelcomeController welcome() {
return new WelcomeController();
}
}

View File

@@ -1,44 +0,0 @@
package com.baeldung.config;
import java.util.HashMap;
import java.util.Map;
import com.baeldung.web.controller.handlermapping.SimpleUrlMappingController;
import com.baeldung.web.controller.handlermapping.BeanNameHandlerMappingController;
import com.baeldung.web.controller.handlermapping.WelcomeController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
@Configuration
public class HandlerMappingPrioritiesConfig {
@Bean
BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() {
BeanNameUrlHandlerMapping beanNameUrlHandlerMapping = new BeanNameUrlHandlerMapping();
beanNameUrlHandlerMapping.setOrder(1);
return beanNameUrlHandlerMapping;
}
@Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
simpleUrlHandlerMapping.setOrder(0);
Map<String, Object> urlMap = new HashMap<>();
urlMap.put("/welcome", simpleUrlMapping());
simpleUrlHandlerMapping.setUrlMap(urlMap);
return simpleUrlHandlerMapping;
}
@Bean
public SimpleUrlMappingController simpleUrlMapping() {
return new SimpleUrlMappingController();
}
@Bean("/welcome")
public BeanNameHandlerMappingController beanNameHandlerMapping() {
return new BeanNameHandlerMappingController();
}
}

View File

@@ -1,43 +0,0 @@
package com.baeldung.config;
import java.util.HashMap;
import java.util.Map;
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.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
public class SimpleUrlHandlerMappingConfig {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
Map<String, Object> urlMap = new HashMap<>();
urlMap.put("/simpleUrlWelcome", welcome());
simpleUrlHandlerMapping.setUrlMap(urlMap);
return simpleUrlHandlerMapping;
}
@Bean
public WelcomeController welcome() {
return new WelcomeController();
}
}

View File

@@ -1,41 +0,0 @@
package com.baeldung.handlermappings;
import com.baeldung.config.BeanNameUrlHandlerMappingConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = BeanNameUrlHandlerMappingConfig.class)
public class BeanNameMappingConfigIntegrationTest {
@Autowired
private WebApplicationContext webAppContext;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
}
@Test
public void whenBeanNameMapping_thenMappedOK() throws Exception {
mockMvc.perform(get("/beanNameUrl")).andExpect(status().isOk()).andExpect(view().name("welcome")).andDo(print());
}
}

View File

@@ -1,41 +0,0 @@
package com.baeldung.handlermappings;
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.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.config.HandlerMappingDefaultConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = HandlerMappingDefaultConfig.class)
public class HandlerMappingDefaultConfigIntegrationTest {
@Autowired
private WebApplicationContext webAppContext;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
}
@Test
public void whenDefaultConfig_thenMappedOK() throws Exception {
mockMvc.perform(get("/welcome")).andExpect(status().isOk()).andExpect(view().name("bean-name-handler-mapping")).andDo(print());
}
}

View File

@@ -1,40 +0,0 @@
package com.baeldung.handlermappings;
import com.baeldung.config.HandlerMappingPrioritiesConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = HandlerMappingPrioritiesConfig.class)
public class HandlerMappingPriorityConfigIntegrationTest {
@Autowired
private WebApplicationContext webAppContext;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
}
@Test
public void whenConfiguringPriorities_thenMappedOK() throws Exception {
mockMvc.perform(get("/welcome")).andExpect(status().isOk()).andExpect(view().name("simple-url-handler-mapping")).andDo(print());
}
}

View File

@@ -1,40 +0,0 @@
package com.baeldung.handlermappings;
import com.baeldung.config.SimpleUrlHandlerMappingConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = SimpleUrlHandlerMappingConfig.class)
public class SimpleUrlMappingConfigIntegrationTest {
@Autowired
private WebApplicationContext webAppContext;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
}
@Test
public void whenSimpleUrlMapping_thenMappedOK() throws Exception {
mockMvc.perform(get("/simpleUrlWelcome")).andExpect(status().isOk()).andExpect(view().name("welcome")).andDo(print());
}
}

View File

@@ -1,50 +0,0 @@
package com.baeldung.web.controller;
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 ClassValidationMvcIntegrationTest {
private MockMvc mockMvc;
@Before
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());
}
@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());
}
}

View File

@@ -1,41 +0,0 @@
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());
}
}

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

View File

@@ -1,35 +0,0 @@
package com.baeldung.web.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
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.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
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build();
}
@Test
public void givenBookId_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc
.perform(get("/books/42"))
.andExpect(status().isOk())
.andExpect(content().contentType(CONTENT_TYPE))
.andExpect(jsonPath("$.id").value(42));
}
}

View File

@@ -1,35 +0,0 @@
package com.baeldung.web.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
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.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
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build();
}
@Test
public void givenBookId_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc
.perform(get("/books/42"))
.andExpect(status().isOk())
.andExpect(content().contentType(CONTENT_TYPE))
.andExpect(jsonPath("$.id").value(42));
}
}

View File

@@ -1,32 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:cache="http://www.springframework.org/schema/cache"
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
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
</bean>
<bean name="beanNameUrl" class="com.baeldung.WelcomeController" />
</beans>

View File

@@ -1,35 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:cache="http://www.springframework.org/schema/cache"
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
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
</bean>
<!-- register beans -->
<bean class="com.baeldung.WelcomeController" />
</beans>

View File

@@ -1,45 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:cache="http://www.springframework.org/schema/cache"
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
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="order" value="2" />
</bean>
<bean name="/welcome" class="com.baeldung.BaeldungController" />
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/welcome=test
/*/welcome=test
</value>
</property>
<property name="order" value="0" />
</bean>
<bean id="test" class="com.baeldung.TestController" />
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="order" value="1" />
</bean>
<bean class="com.baeldung.WelcomeController" />
</beans>

View File

@@ -1,38 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:cache="http://www.springframework.org/schema/cache"
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
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/simpleUrlWelcome=welcome
/*/simpleUrlWelcome=welcome
</value>
</property>
</bean>
<bean id="welcome" class="com.baeldung.WelcomeController" />
</beans>