Initial commit for merging modules spring-mvc-forms into (#1222)

spring-mvc-simple.
This commit is contained in:
Parth Joshi
2017-03-21 15:54:57 +05:30
committed by Grzegorz Piwowarek
parent b5ef48a1d8
commit 07c0e84bf4
22 changed files with 661 additions and 80 deletions

View File

@@ -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;
}
}

View File

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

View File

@@ -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";
}
}

View File

@@ -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<Long, Employee> 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";
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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.");
}
}