diff --git a/spring-mvc-forms/README.md b/spring-mvc-forms/README.md index 51dbef9856..745851a102 100644 --- a/spring-mvc-forms/README.md +++ b/spring-mvc-forms/README.md @@ -2,3 +2,4 @@ ### Relevant Articles - [MaxUploadSizeExceededException in Spring](http://www.baeldung.com/spring-maxuploadsizeexceeded) +- [Getting Started with Forms in Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial) diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 4ab5bd9d1e..a004eae4d9 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -12,6 +12,13 @@ 4.3.4.RELEASE 3.5.1 2.6 + 1.2 + 2.3.1 + 3.1.0 + 1.8 + 5.3.3.Final + enter-location-of-server + 1.3.2 @@ -40,6 +47,33 @@ spring-core ${springframework.version} + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax.servlet.jsp-api.version} + + + + javax.servlet + jstl + ${jstl.version} + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + org.springframework + spring-webmvc + ${springframework.version} + + + commons-fileupload + commons-fileupload + ${fileupload.version} + @@ -61,6 +95,7 @@ src/main/webapp springMvcSimple false + ${deploy-path} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java new file mode 100644 index 0000000000..9ace968bbe --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.multipart.MultipartResolver; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.springmvcforms") +class ApplicationConfiguration extends WebMvcConfigurerAdapter { + + @Override + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Bean + public InternalResourceViewResolver jspViewResolver() { + InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setPrefix("/WEB-INF/views/"); + bean.setSuffix(".jsp"); + return bean; + } + + @Bean + public MultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(5242880); + return multipartResolver; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java new file mode 100644 index 0000000000..d6bbf5eabd --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -0,0 +1,48 @@ +package com.baeldung.spring.configuration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class WebInitializer implements WebApplicationInitializer { + + public void onStartup(ServletContext container) throws ServletException { + + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(ApplicationConfiguration.class); + ctx.setServletContext(container); + + // Manage the lifecycle of the root application context + container.addListener(new ContextLoaderListener(ctx)); + + ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx)); + + servlet.setLoadOnStartup(1); + servlet.addMapping("/"); + + } +// @Override +// public void onStartup(ServletContext container) { +// // Create the 'root' Spring application context +// AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); +// rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class); +// +// // Manage the lifecycle of the root application context +// container.addListener(new ContextLoaderListener(rootContext)); +// +// // Create the dispatcher servlet's Spring application context +// AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext(); +// dispatcherServlet.register(MvcConfig.class); +// +// // Register and map the dispatcher servlet +// ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet)); +// dispatcher.setLoadOnStartup(1); +// dispatcher.addMapping("/"); +// +// } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/CustomerController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/CustomerController.java new file mode 100644 index 0000000000..8ecfce58e3 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/CustomerController.java @@ -0,0 +1,42 @@ +package com.baeldung.spring.controller; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.baeldung.spring.domain.Customer; +import com.baeldung.spring.validator.CustomerValidator; + +@Controller +public class CustomerController { + + @Autowired + CustomerValidator validator; + + @RequestMapping(value = "/customer", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("customerHome", "customer", new Customer()); + } + + @PostMapping("/addCustomer") + public String submit(@Valid @ModelAttribute("customer") final Customer customer, final BindingResult result, final ModelMap model) { + validator.validate(customer, result); + if (result.hasErrors()) { + return "customerHome"; + } + model.addAttribute("customerId", customer.getCustomerId()); + model.addAttribute("customerName", customer.getCustomerName()); + model.addAttribute("customerContact", customer.getCustomerContact()); + model.addAttribute("customerEmail", customer.getCustomerEmail()); + return "customerView"; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/EmployeeController.java new file mode 100644 index 0000000000..6543a98af1 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/EmployeeController.java @@ -0,0 +1,47 @@ +package com.baeldung.spring.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.validation.Valid; + +import org.springframework.stereotype.Controller; +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.spring.domain.Employee; + +@Controller +public class EmployeeController { + + Map employeeMap = new HashMap<>(); + + @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(@Valid @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("id", employee.getId()); + employeeMap.put(employee.getId(), employee); + return "employeeView"; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/FileUploadController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/FileUploadController.java new file mode 100644 index 0000000000..47af2ab50d --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/FileUploadController.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.controller; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.multipart.MaxUploadSizeExceededException; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.servlet.HandlerExceptionResolver; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class FileUploadController implements HandlerExceptionResolver { + + @RequestMapping(value = "/uploadFile", method = RequestMethod.GET) + public String getImageView() { + return "file"; + } + + @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) + public ModelAndView uploadFile(MultipartFile file) throws IOException{ + ModelAndView modelAndView = new ModelAndView("file"); + + InputStream in = file.getInputStream(); + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + FileOutputStream f = new FileOutputStream(path.substring(0, path.length()-1)+ file.getOriginalFilename()); + int ch = 0; + while ((ch = in.read()) != -1) { + f.write(ch); + } + f.flush(); + f.close(); + + modelAndView.getModel().put("message", "File uploaded successfully!"); + return modelAndView; + } + + @Override + public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exc) { + ModelAndView modelAndView = new ModelAndView("file"); + if (exc instanceof MaxUploadSizeExceededException) { + modelAndView.getModel().put("message", "File size exceeds limit!"); + } + return modelAndView; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/Customer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/Customer.java new file mode 100644 index 0000000000..09322105f8 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/Customer.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.domain; + +public class Customer { + private String customerId; + private String customerName; + private String customerContact; + private String customerEmail; + + public Customer() { + super(); + } + + public String getCustomerId() { + return customerId; + } + + public void setCustomerId(String customerId) { + this.customerId = customerId; + } + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } + + public String getCustomerContact() { + return customerContact; + } + + public void setCustomerContact(String customerContact) { + this.customerContact = customerContact; + } + + public String getCustomerEmail() { + return customerEmail; + } + + public void setCustomerEmail(String customerEmail) { + this.customerEmail = customerEmail; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/Employee.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/Employee.java new file mode 100644 index 0000000000..900770b873 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/Employee.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.domain; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +public class Employee { + + private long id; + + @NotNull + @Size(min = 5) + private String name; + + @NotNull + @Size(min = 7) + private String contactNumber; + + public Employee() { + super(); + } + + 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; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/interceptor/FileUploadExceptionAdvice.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/interceptor/FileUploadExceptionAdvice.java new file mode 100644 index 0000000000..2f3c44cf12 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/interceptor/FileUploadExceptionAdvice.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.interceptor; + +import org.springframework.web.servlet.ModelAndView; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.web.multipart.MaxUploadSizeExceededException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +public class FileUploadExceptionAdvice { + + @ExceptionHandler(MaxUploadSizeExceededException.class) + public ModelAndView handleMaxSizeException(MaxUploadSizeExceededException exc, HttpServletRequest request, HttpServletResponse response){ + ModelAndView modelAndView = new ModelAndView("file"); + modelAndView.getModel().put("message", "File too large!"); + return modelAndView; + } +} \ No newline at end of file diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/validator/CustomerValidator.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/validator/CustomerValidator.java new file mode 100644 index 0000000000..2515e8d31f --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/validator/CustomerValidator.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.validator; + +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.validation.ValidationUtils; +import org.springframework.validation.Validator; + +import com.baeldung.spring.domain.Customer; + +@Component +public class CustomerValidator implements Validator { + + @Override + public boolean supports(Class clazz) { + return Customer.class.isAssignableFrom(clazz); + } + + @Override + public void validate(Object target, Errors errors) { + + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerId", "error.customerId", "Customer Id is required."); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerName", "error.customerName", "Customer Name is required."); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerContact", "error.customerNumber", "Customer Contact is required."); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerEmail", "error.customerEmail", "Customer Email is required."); + + } + +} diff --git a/spring-mvc-simple/src/main/resources/spring-servlet_AnnotationMethodHandlerAdapter.xml b/spring-mvc-simple/src/main/resources/spring-servlet_AnnotationMethodHandlerAdapter.xml index a8071a622f..430b849012 100644 --- a/spring-mvc-simple/src/main/resources/spring-servlet_AnnotationMethodHandlerAdapter.xml +++ b/spring-mvc-simple/src/main/resources/spring-servlet_AnnotationMethodHandlerAdapter.xml @@ -1,26 +1,26 @@ - - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/resources/spring-servlet_RequestMappingHandlerAdapter.xml b/spring-mvc-simple/src/main/resources/spring-servlet_RequestMappingHandlerAdapter.xml index b32a213eb3..d3783c2e67 100644 --- a/spring-mvc-simple/src/main/resources/spring-servlet_RequestMappingHandlerAdapter.xml +++ b/spring-mvc-simple/src/main/resources/spring-servlet_RequestMappingHandlerAdapter.xml @@ -1,28 +1,28 @@ - - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/resources/spring-servlet_SimpleControllerHandlerAdapter.xml b/spring-mvc-simple/src/main/resources/spring-servlet_SimpleControllerHandlerAdapter.xml index 60c9b9e3df..1d6e5628df 100644 --- a/spring-mvc-simple/src/main/resources/spring-servlet_SimpleControllerHandlerAdapter.xml +++ b/spring-mvc-simple/src/main/resources/spring-servlet_SimpleControllerHandlerAdapter.xml @@ -1,25 +1,25 @@ - - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/Greeting.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/Greeting.jsp index 820d2f380f..7f7fbccccd 100644 --- a/spring-mvc-simple/src/main/webapp/WEB-INF/Greeting.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/Greeting.jsp @@ -1,5 +1,6 @@ - - -

Hello ${message}

- + + +

Hello ${message}

+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/Greeting.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/Greeting.jsp new file mode 100644 index 0000000000..efd48179f9 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/Greeting.jsp @@ -0,0 +1,5 @@ + + +

Hello ${message}

+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/customerHome.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/customerHome.jsp new file mode 100644 index 0000000000..df34a47cc0 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/customerHome.jsp @@ -0,0 +1,47 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Add Customer + + + +

Welcome, Enter The Customer Details

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Customer Id
Customer Name
Customer Contact
Customer Email
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/customerView.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/customerView.jsp new file mode 100644 index 0000000000..ab2631bd02 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/customerView.jsp @@ -0,0 +1,28 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Customer Information

+ + + + + + + + + + + + + + + + + +
Customer Id :${customerId}
Customer Name :${customerName}
Customer Contact :${customerContact}
Customer Email :${customerEmail}
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/employeeHome.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/employeeHome.jsp new file mode 100644 index 0000000000..5ed572000a --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/employeeHome.jsp @@ -0,0 +1,33 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Register an Employee + + +

Welcome, Enter The Employee Details

+ + + + + + + + + + + + + + + + + + +
Name
Id
Contact Number
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/employeeView.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/employeeView.jsp new file mode 100644 index 0000000000..1457bc5fc8 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/employeeView.jsp @@ -0,0 +1,24 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Employee Information

+ + + + + + + + + + + + + +
Name :${name}
ID :${id}
Contact Number :${contactNumber}
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/error.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/error.jsp new file mode 100644 index 0000000000..8f3d83af17 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/error.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +SpringMVCExample + + + +

Pleas enter the correct details

+ + + + +
Retry
+ + + + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/file.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/file.jsp new file mode 100644 index 0000000000..0ed8dae5ed --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/file.jsp @@ -0,0 +1,23 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + +Upload file + + + +
+ + +
+
+${message } +

+
+ +
+ + \ No newline at end of file