JAVA-3509: Moved spring-mvc-basics inside spring-web-modules
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -0,0 +1,21 @@
|
||||
## 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: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial)
|
||||
- [An Intro to the Spring DispatcherServlet](https://www.baeldung.com/spring-dispatcherservlet)
|
||||
- [The Spring @Controller and @RestController Annotations](https://www.baeldung.com/spring-controller-vs-restcontroller)
|
||||
- [A Guide to the ViewResolver in Spring MVC](https://www.baeldung.com/spring-mvc-view-resolver-tutorial)
|
||||
- [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)
|
||||
@@ -0,0 +1,64 @@
|
||||
<?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</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>spring-mvc-basics</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>
|
||||
<dependency>
|
||||
<groupId>commons-fileupload</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
<version>${commons-fileupload.version}</version>
|
||||
</dependency>
|
||||
<!-- to enable JSP -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat.embed</groupId>
|
||||
<artifactId>tomcat-embed-jasper</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<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>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
import org.springframework.web.WebApplicationInitializer;
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
|
||||
public class MainWebAppInitializer implements WebApplicationInitializer {
|
||||
|
||||
@Override
|
||||
public void onStartup(ServletContext container) throws ServletException {
|
||||
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
|
||||
|
||||
context.scan("com.baeldung");
|
||||
|
||||
container.addListener(new ContextLoaderListener(context));
|
||||
|
||||
ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context));
|
||||
dispatcher.setLoadOnStartup(1);
|
||||
dispatcher.addMapping("/");
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.customvalidator;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
|
||||
@Documented
|
||||
@Constraint(validatedBy = ContactNumberValidator.class)
|
||||
@Target({ ElementType.METHOD, ElementType.FIELD })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface ContactNumberConstraint {
|
||||
|
||||
String message() default "Invalid phone number";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.customvalidator;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
|
||||
public class ContactNumberValidator implements ConstraintValidator<ContactNumberConstraint, String> {
|
||||
|
||||
@Override
|
||||
public void initialize(ContactNumberConstraint contactNumber) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(String contactField, ConstraintValidatorContext cxt) {
|
||||
return contactField != null && contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14);
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.exception;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.HttpMediaTypeNotAcceptableException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@ControllerAdvice
|
||||
public class HttpMediaTypeNotAcceptableExceptionExampleController {
|
||||
|
||||
@PostMapping(value = "/test", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Map<String, String> test() {
|
||||
return Collections.singletonMap("key", "value");
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
|
||||
public String handleHttpMediaTypeNotAcceptableException() {
|
||||
return "acceptable MIME type:" + MediaType.APPLICATION_JSON_VALUE;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
public class Book {
|
||||
|
||||
private int id;
|
||||
private String author;
|
||||
private String title;
|
||||
|
||||
public Book() {
|
||||
}
|
||||
|
||||
public Book(int id, String author, String title) {
|
||||
this.id = id;
|
||||
this.author = author;
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
@XmlRootElement
|
||||
public class Employee {
|
||||
|
||||
private long id;
|
||||
private String name;
|
||||
private String contactNumber;
|
||||
private String workingArea;
|
||||
|
||||
public Employee() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Employee(final long id, final String name, final String contactNumber, final String workingArea) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.contactNumber = contactNumber;
|
||||
this.workingArea = workingArea;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getContactNumber() {
|
||||
return contactNumber;
|
||||
}
|
||||
|
||||
public void setContactNumber(final String contactNumber) {
|
||||
this.contactNumber = contactNumber;
|
||||
}
|
||||
|
||||
public String getWorkingArea() {
|
||||
return workingArea;
|
||||
}
|
||||
|
||||
public void setWorkingArea(final String workingArea) {
|
||||
this.workingArea = workingArea;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Employee [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + ", workingArea=" + workingArea + "]";
|
||||
}
|
||||
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
|
||||
public class User {
|
||||
private long id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public User(long id, String firstName, String lastName) {
|
||||
this.id = id;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
import com.baeldung.customvalidator.ContactNumberConstraint;
|
||||
|
||||
public class ValidatedPhone {
|
||||
|
||||
@ContactNumberConstraint
|
||||
private String phone;
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return phone;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.services;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.model.User;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
|
||||
public User fetchUserByFirstName(String firstName) {
|
||||
return new User(1, firstName, "Everyperson");
|
||||
}
|
||||
|
||||
public User exampleUser() {
|
||||
return new User(1, "Example", "Everyperson");
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package com.baeldung.spring.web.config;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.ui.context.support.ResourceBundleThemeSource;
|
||||
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.InterceptorRegistry;
|
||||
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.theme.CookieThemeResolver;
|
||||
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
import org.springframework.web.servlet.view.JstlView;
|
||||
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
|
||||
import org.springframework.web.servlet.view.XmlViewResolver;
|
||||
|
||||
//@EnableWebMvc
|
||||
//@ComponentScan(basePackages = { "com.baeldung.web.controller" })
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||
registry.addViewController("/")
|
||||
.setViewName("index");
|
||||
}
|
||||
|
||||
/** Multipart file uploading configuratioin */
|
||||
@Bean
|
||||
public CommonsMultipartResolver multipartResolver() throws IOException {
|
||||
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
|
||||
resolver.setMaxUploadSize(10000000);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@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 including themes*/
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**/*")
|
||||
.addResourceLocations("/", "/resources/")
|
||||
.setCachePeriod(3600)
|
||||
.resourceChain(true)
|
||||
.addResolver(new PathResourceResolver());
|
||||
}
|
||||
|
||||
/** BEGIN theme configuration */
|
||||
@Bean
|
||||
public ResourceBundleThemeSource themeSource() {
|
||||
ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
|
||||
themeSource.setDefaultEncoding("UTF-8");
|
||||
themeSource.setBasenamePrefix("themes.");
|
||||
return themeSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CookieThemeResolver themeResolver() {
|
||||
CookieThemeResolver resolver = new CookieThemeResolver();
|
||||
resolver.setDefaultThemeName("default");
|
||||
resolver.setCookieName("example-theme-cookie");
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ThemeChangeInterceptor themeChangeInterceptor() {
|
||||
ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor();
|
||||
interceptor.setParamName("theme");
|
||||
return interceptor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(themeChangeInterceptor());
|
||||
}
|
||||
|
||||
/** END theme configuration */
|
||||
|
||||
@Bean
|
||||
public ViewResolver resourceBundleViewResolver() {
|
||||
final ResourceBundleViewResolver bean = new ResourceBundleViewResolver();
|
||||
bean.setBasename("views");
|
||||
bean.setOrder(0);
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver xmlViewResolver() {
|
||||
final XmlViewResolver bean = new XmlViewResolver();
|
||||
bean.setLocation(new ClassPathResource("views.xml"));
|
||||
bean.setOrder(1);
|
||||
return bean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spring Boot allows configuring Content Negotiation using properties
|
||||
*/
|
||||
@Override
|
||||
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
|
||||
configurer.favorPathExtension(true)
|
||||
.favorParameter(true)
|
||||
.parameterName("mediaType")
|
||||
.ignoreAcceptHeader(false)
|
||||
.useRegisteredExtensionsOnly(false)
|
||||
.defaultContentType(MediaType.APPLICATION_JSON)
|
||||
.mediaType("xml", MediaType.APPLICATION_XML)
|
||||
.mediaType("json", MediaType.APPLICATION_JSON);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.ui.ModelMap;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import com.baeldung.model.Employee;
|
||||
|
||||
@Controller
|
||||
public class EmployeeController {
|
||||
|
||||
Map<Long, Employee> employeeMap = new HashMap<>();
|
||||
|
||||
@ModelAttribute("employees")
|
||||
public void initEmployees() {
|
||||
employeeMap.put(1L, new Employee(1L, "John", "223334411", "rh"));
|
||||
employeeMap.put(2L, new Employee(2L, "Peter", "22001543", "informatics"));
|
||||
employeeMap.put(3L, new Employee(3L, "Mike", "223334411", "admin"));
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/employee", method = RequestMethod.GET)
|
||||
public ModelAndView showForm() {
|
||||
return new ModelAndView("employeeHome", "employee", new Employee());
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
|
||||
public @ResponseBody Employee getEmployeeById(@PathVariable final Long Id) {
|
||||
return employeeMap.get(Id);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
|
||||
public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
|
||||
if (result.hasErrors()) {
|
||||
return "error";
|
||||
}
|
||||
model.addAttribute("name", employee.getName());
|
||||
model.addAttribute("contactNumber", employee.getContactNumber());
|
||||
model.addAttribute("workingArea", employee.getWorkingArea());
|
||||
model.addAttribute("id", employee.getId());
|
||||
|
||||
employeeMap.put(employee.getId(), employee);
|
||||
|
||||
return "employeeView";
|
||||
}
|
||||
|
||||
@ModelAttribute
|
||||
public void addAttributes(final Model model) {
|
||||
model.addAttribute("msg", "Welcome to the Netherlands!");
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
|
||||
@Controller
|
||||
public class MultipartController {
|
||||
|
||||
@Autowired
|
||||
ServletContext context;
|
||||
|
||||
@RequestMapping(value = "/upload", method = RequestMethod.POST)
|
||||
public ModelAndView FileuploadController(@RequestParam("file") MultipartFile file) {
|
||||
ModelAndView modelAndView = new ModelAndView("index");
|
||||
try {
|
||||
InputStream in = file.getInputStream();
|
||||
String path = new File(".").getAbsolutePath();
|
||||
FileOutputStream f = new FileOutputStream(path.substring(0, path.length() - 1) + "/uploads/" + file.getOriginalFilename());
|
||||
try {
|
||||
int ch;
|
||||
while ((ch = in.read()) != -1) {
|
||||
f.write(ch);
|
||||
}
|
||||
modelAndView.getModel().put("message", "File uploaded successfully!");
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception uploading multipart: " + e);
|
||||
} finally {
|
||||
f.flush();
|
||||
f.close();
|
||||
in.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception uploading multipart: " + e);
|
||||
}
|
||||
return modelAndView;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
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";
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class RequestMappingShortcutsController {
|
||||
|
||||
@GetMapping("/get")
|
||||
public @ResponseBody ResponseEntity<String> get() {
|
||||
return new ResponseEntity<String>("GET Response", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/get/{id}")
|
||||
public @ResponseBody ResponseEntity<String> getById(@PathVariable String id) {
|
||||
return new ResponseEntity<String>("GET Response : " + id, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PostMapping("/post")
|
||||
public @ResponseBody ResponseEntity<String> post() {
|
||||
return new ResponseEntity<String>("POST Response", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PutMapping("/put")
|
||||
public @ResponseBody ResponseEntity<String> put() {
|
||||
return new ResponseEntity<String>("PUT Response", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete")
|
||||
public @ResponseBody ResponseEntity<String> delete() {
|
||||
return new ResponseEntity<String>("DELETE Response", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PatchMapping("/patch")
|
||||
public @ResponseBody ResponseEntity<String> patch() {
|
||||
return new ResponseEntity<String>("PATCH Response", HttpStatus.OK);
|
||||
}
|
||||
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.model.Book;
|
||||
|
||||
@RestController
|
||||
public class ResponseStatusRestController {
|
||||
|
||||
@GetMapping("/teapot")
|
||||
@ResponseStatus(HttpStatus.I_AM_A_TEAPOT)
|
||||
public void teaPot() {
|
||||
}
|
||||
|
||||
@GetMapping("empty")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void emptyResponse() {
|
||||
}
|
||||
|
||||
@GetMapping("empty-no-responsestatus")
|
||||
public void emptyResponseWithoutResponseStatus() {
|
||||
}
|
||||
|
||||
@PostMapping("create")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public Book createEntity() {
|
||||
// here we would create and persist an entity
|
||||
int randomInt = ThreadLocalRandom.current()
|
||||
.nextInt(1, 100);
|
||||
Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@PostMapping("create-no-responsestatus")
|
||||
public Book createEntityWithoutResponseStatus() {
|
||||
// here we would create and persist an entity
|
||||
int randomInt = ThreadLocalRandom.current()
|
||||
.nextInt(1, 100);
|
||||
Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt);
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class SampleController {
|
||||
|
||||
@GetMapping("/sample")
|
||||
public String showForm() {
|
||||
return "sample";
|
||||
}
|
||||
|
||||
@GetMapping("/sample2")
|
||||
public String showForm2() {
|
||||
return "sample2";
|
||||
}
|
||||
|
||||
@GetMapping("/sample3")
|
||||
public String showForm3() {
|
||||
return "sample3";
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import com.baeldung.model.User;
|
||||
import com.baeldung.services.UserService;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/user")
|
||||
public class UserController {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@RequestMapping(value = "/example", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public User fetchUserExample() {
|
||||
return userService.exampleUser();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/name", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public User fetchUserByFirstName(@RequestParam(value = "firstName") String firstName) {
|
||||
return userService.fetchUserByFirstName(firstName);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import com.baeldung.model.User;
|
||||
import com.baeldung.services.UserService;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/rest/user")
|
||||
public class UserRestController {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@RequestMapping(value = "/example", method = RequestMethod.GET)
|
||||
public User fetchUserExample() {
|
||||
return userService.exampleUser();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/name", method = RequestMethod.GET)
|
||||
public User fetchUserByFirstName(@RequestParam(value = "firstName") String firstName) {
|
||||
return userService.fetchUserByFirstName(firstName);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
|
||||
import com.baeldung.model.ValidatedPhone;
|
||||
|
||||
@Controller
|
||||
public class ValidatedPhoneController {
|
||||
|
||||
@GetMapping("/validatePhone")
|
||||
public String loadFormPage(Model m) {
|
||||
m.addAttribute("validatedPhone", new ValidatedPhone());
|
||||
return "phoneHome";
|
||||
}
|
||||
|
||||
@PostMapping("/addValidatePhone")
|
||||
public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) {
|
||||
if (result.hasErrors()) {
|
||||
return "phoneHome";
|
||||
}
|
||||
|
||||
m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString());
|
||||
return "phoneHome";
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user