* BAEL-86

* Added Themes and Beans

* Improvements and fully tested locally
This commit is contained in:
Adam InTae Gerard
2017-04-21 22:00:42 -05:00
committed by KevinGilmore
parent caab7829e7
commit 7a96484ba3
42 changed files with 384 additions and 1203 deletions
+3
View File
@@ -0,0 +1,3 @@
## Relevant articles:
- [Spring DispatcherServlet](http://www.baeldung.com/spring-dispatcher-servlet)
+79 -79
View File
@@ -1,96 +1,96 @@
<?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">
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-dispatcher-servlet</artifactId>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<version>1.0.0</version>
<name>spring-dispatcher-servlet</name>
<properties>
<springframework.version>4.3.7.RELEASE</springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet.version}</version>
<scope>provided</scope>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${thymeleaf.version}</version>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-maven-plugin.version}</version>
<configuration>
<webApp>
<contextPath>/</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat8-maven-plugin</artifactId>
<version>3.0-r1655215</version>
<configuration>
<path>/springdispatcherservlet</path>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>springdispatcherservlet</finalName>
</build>
<properties>
<!-- Spring -->
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<!-- various -->
<javax.servlet.version>3.1.0</javax.servlet.version>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-war-plugin.version>3.0.0</maven-war-plugin.version>
<jetty-maven-plugin.version>9.3.14.v20161028</jetty-maven-plugin.version>
</properties>
</project>
</project>
@@ -1,30 +0,0 @@
package com.baeldung.spring.dispatcher.servlet;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class DispatcherServletApplication implements org.springframework.web.WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(RootConfiguration.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext webContext =
new AnnotationConfigWebApplicationContext();
webContext.register(WebConfiguration.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",
dispatcherServlet);
servlet.addMapping("/*");
MultipartConfigElement multipartConfigElement =
new MultipartConfigElement("/tmp");
servlet.setMultipartConfig(multipartConfigElement);
}
}
@@ -1,19 +0,0 @@
package com.baeldung.spring.dispatcher.servlet;
import com.baeldung.spring.dispatcher.servlet.models.Task;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.*;
@Configuration
public class RootConfiguration {
@Bean
public Map<String, List<Task>> taskList() {
Map<String, List<Task>> taskMap = new HashMap<>();
List<Task> taskList = new ArrayList<>();
taskList.add(new Task("Clean the dishes!", new Date()));
taskMap.put("Cid", taskList);
return taskMap;
}
}
@@ -1,129 +0,0 @@
package com.baeldung.spring.dispatcher.servlet;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.ui.context.support.ResourceBundleThemeSource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
import org.springframework.web.servlet.theme.CookieThemeResolver;
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import javax.servlet.ServletContext;
import java.util.Locale;
@Configuration
@ComponentScan("com.baeldung.spring.dispatcher.servlet.web")
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/public/**")
.addResourceLocations("/public/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
registry.addInterceptor(themeChangeInterceptor());
}
@Bean
public ServletContextTemplateResolver templateResolver(ServletContext servletContext) {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine(ServletContextTemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
messageSource.setFallbackToSystemLocale(false);
return messageSource;
}
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setDefaultLocale(Locale.ENGLISH);
localeResolver.setCookieName("locale");
localeResolver.setCookieMaxAge(-1);
return localeResolver;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
localeChangeInterceptor.setIgnoreInvalidLocale(true);
return localeChangeInterceptor;
}
@Bean
public ResourceBundleThemeSource themeSource() {
ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
themeSource.setBasenamePrefix("theme-");
themeSource.setFallbackToSystemLocale(false);
return themeSource;
}
@Bean
public ThemeResolver themeResolver() {
CookieThemeResolver themeResolver = new CookieThemeResolver();
themeResolver.setDefaultThemeName("robotask");
themeResolver.setCookieName("theme");
themeResolver.setCookieMaxAge(-1);
return themeResolver;
}
@Bean
public ThemeChangeInterceptor themeChangeInterceptor() {
ThemeChangeInterceptor themeChangeInterceptor = new ThemeChangeInterceptor();
themeChangeInterceptor.setParamName("theme");
return themeChangeInterceptor;
}
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
@Bean
public HandlerExceptionResolver handlerExceptionResolver() {
return new ExceptionHandlerExceptionResolver();
}
}
@@ -1,58 +0,0 @@
package com.baeldung.spring.dispatcher.servlet.models;
import java.util.UUID;
public class Attachment {
private String id;
private String name;
private String description;
public Attachment() {
this.id = UUID.randomUUID().toString();
}
public Attachment(String name, String description) {
this();
this.name = name;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Attachment that = (Attachment) o;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}
@@ -1,52 +0,0 @@
package com.baeldung.spring.dispatcher.servlet.models;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Task {
private String description;
@DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm")
private Date due;
private Set<Attachment> attachments = new HashSet<>();
public Task() {
}
public Task(Date due) {
this.due = due;
}
public Task(String description, Date due) {
this.description = description;
this.due = due;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDue() {
return due;
}
public void setDue(Date due) {
this.due = due;
}
public Set<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(Set<Attachment> attachments) {
this.attachments = attachments;
}
}
@@ -1,17 +0,0 @@
package com.baeldung.spring.dispatcher.servlet.web;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@RequestMapping("/attachments")
public interface AttachmentController {
@GetMapping("/{attachmentId}")
ResponseEntity<FileSystemResource> getAttachment(
@PathVariable("attachmentId") String attachmentId,
@RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload
);
}
@@ -1,45 +0,0 @@
package com.baeldung.spring.dispatcher.servlet.web;
import com.baeldung.spring.dispatcher.servlet.models.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.net.URLConnection;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@Controller
public class AttachmentControllerImpl implements AttachmentController {
@Autowired
private Map<String, List<Task>> taskMap;
@Override
public ResponseEntity<FileSystemResource> getAttachment(
@PathVariable("attachmentId") String attachmentId,
@RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload
) {
FileSystemResource resource = new FileSystemResource("/tmp/" + attachmentId);
HttpHeaders headers = new HttpHeaders();
taskMap.values().stream()
.flatMap(Collection::stream)
.flatMap(t -> t.getAttachments().stream())
.filter(a -> a.getId().equals(attachmentId))
.findFirst()
.ifPresent(a -> {
headers.add("Content-Disposition",
"attachment; filename=" + a.getName());
headers.add("Content-Type", forcedDownload ?
MediaType.APPLICATION_OCTET_STREAM_VALUE :
URLConnection.guessContentTypeFromName(a.getName()));
});
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
}
@@ -1,19 +0,0 @@
package com.baeldung.spring.dispatcher.servlet.web;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
@ExceptionHandler(Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e);
modelAndView.addObject("url", request.getRequestURL());
modelAndView.setViewName("error");
return modelAndView;
}
}
@@ -1,13 +0,0 @@
package com.baeldung.spring.dispatcher.servlet.web;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/")
public interface HomeController {
@GetMapping("/*")
String home(
Model model
);
}
@@ -1,25 +0,0 @@
package com.baeldung.spring.dispatcher.servlet.web;
import com.baeldung.spring.dispatcher.servlet.models.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Controller
public class HomeControllerImpl implements HomeController {
@Autowired
private Map<String, List<Task>> taskMap;
@Override
public String home(Model model) {
List<String> users = taskMap.keySet().stream()
.sorted()
.collect(Collectors.toList());
model.addAttribute("users", users);
return "home";
}
}
@@ -1,49 +0,0 @@
package com.baeldung.spring.dispatcher.servlet.web;
import com.baeldung.spring.dispatcher.servlet.models.Task;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RequestMapping("/tasks")
public interface TaskController {
@GetMapping("/{username}/list")
String listTasks(
@PathVariable("username") String username,
Model model
);
@GetMapping("/{username}/add")
String addTask(
@PathVariable("username") String username,
Model model
);
@PostMapping("/{username}/add")
String addTask(
@PathVariable("username") String username,
@ModelAttribute Task task
);
@GetMapping("/{username}/get/{id}")
String getTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
Model model
);
@GetMapping("/{username}/get/{id}/attach")
String attachToTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
Model model
);
@PostMapping("/{username}/get/{id}/attach")
String attachToTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
@RequestParam("attachment") MultipartFile attachment,
@RequestParam("description") String description
);
}
@@ -1,111 +0,0 @@
package com.baeldung.spring.dispatcher.servlet.web;
import com.baeldung.spring.dispatcher.servlet.models.Attachment;
import com.baeldung.spring.dispatcher.servlet.models.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
@Controller
public class TaskControllerImpl implements TaskController {
@Autowired
private Map<String, List<Task>> taskMap;
@Override
public String listTasks(
@PathVariable("username") String username,
Model model
) {
List<Task> tasks = taskMap.get(username).stream()
.sorted(Comparator.comparing(Task::getDue))
.collect(Collectors.toList());
model.addAttribute("username", username);
model.addAttribute("tasks", tasks);
return "task-list";
}
@Override
public String addTask(
@PathVariable("username") String username,
Model model
) {
model.addAttribute("username", username);
model.addAttribute("task", new Task(new Date()));
return "task-add";
}
@Override
public String addTask(
@PathVariable("username") String username,
@ModelAttribute Task task
) {
List<Task> taskList = taskMap.get(username);
if (taskList == null) {
taskList = new ArrayList<>();
}
taskList.add(task);
taskMap.put(username, taskList);
return "redirect:list";
}
@Override
public String getTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
Model model
) {
Task task = taskMap.get(username).get(id);
model.addAttribute("username", username);
model.addAttribute("id", id);
model.addAttribute("task", task);
return "task-get";
}
@Override
public String attachToTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
Model model
) {
model.addAttribute("username", username);
model.addAttribute("id", id);
return "task-attach";
}
@Override
public String attachToTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
@RequestParam("attachment") MultipartFile multipartFile,
@RequestParam("description") String description
) {
Task task = taskMap.get(username).get(id);
Attachment attachment = new Attachment(multipartFile.getOriginalFilename(),
description);
task.getAttachments().add(attachment);
try (InputStream inputStream =
new BufferedInputStream(multipartFile.getInputStream());
OutputStream outputStream =
new BufferedOutputStream(Files.newOutputStream(
Paths.get("/tmp", attachment.getId())))) {
byte[] buf = new byte[1024 * 16];
int len;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
} catch (IOException e) {
throw new RuntimeException("Failed to upload file!", e);
}
return "redirect:./";
}
}
@@ -0,0 +1,83 @@
package com.baeldung.springdispatcherservlet.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.context.support.ResourceBundleThemeSource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.*;
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.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import java.io.IOException;
@Configuration
@EnableWebMvc
@ComponentScan("com.baeldung.springdispatcherservlet")
public class AppConfig extends WebMvcConfigurerAdapter {
public void addViewControllers(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;
}
/** View resolver for JSP */
@Bean
public UrlBasedViewResolver viewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
/** 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 */
}
@@ -0,0 +1,23 @@
package com.baeldung.springdispatcherservlet.configuration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
context.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(context));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
@@ -0,0 +1,41 @@
package com.baeldung.springdispatcherservlet.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());
int ch;
while ((ch = in.read()) != -1) {
f.write(ch);
}
f.flush();
f.close();
modelAndView.getModel().put("message", "File uploaded successfully!");
} catch (Exception e) {
System.out.println("Exception uploading multipart: " + e);
}
return modelAndView;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.springdispatcherservlet.controller;
import com.baeldung.springdispatcherservlet.domain.User;
import com.baeldung.springdispatcherservlet.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);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.springdispatcherservlet.controller;
import com.baeldung.springdispatcherservlet.domain.User;
import com.baeldung.springdispatcherservlet.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);
}
}
@@ -0,0 +1,41 @@
package com.baeldung.springdispatcherservlet.domain;
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;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.springdispatcherservlet.services;
import org.springframework.stereotype.Service;
import com.baeldung.springdispatcherservlet.domain.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");
}
}
@@ -1,3 +0,0 @@
## Info ##
- The diagram is created with [yed](http://www.yworks.com/products/yed)
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

@@ -1,22 +0,0 @@
home.title=Welcome to TaskTools!
task.add.description=description
task.add.due=due
task.add.header=Adding a task to {0}''s list:
task.add.submit=Submit
task.add.title={0}: task add
task.attach.attachment=attached file
task.attach.description=description
task.attach.header=task #{0}: attach file
task.attach.submit=Submit
task.attach.title=#{0}: Attach file
task.get.attach=Attach file
task.get.attachments=attachments:
task.get.download=Download
task.get.header=task #{0}:
task.get.list=Back
task.get.title={0}: task details
task.list.add-new=Add new
task.list.details=Details
task.list.header={0}''s tasks:
task.list.home=Home
task.list.title={0}: task list
@@ -1,22 +0,0 @@
home.title=Willkommen bei TaskTools!
task.add.description=Beschreibung
task.add.due=f\u00e4llig
task.add.header=F\u00fcge eine Aufgabe zu {0}''s Liste hinzu:
task.add.submit=Senden
task.add.title={0}: Task hinzuf\u00fcgen
task.attach.attachment=Angeh\u00e4ngte Datei
task.attach.description=Beschreibung
task.attach.header=Task #{0}: Datei anh\u00e4ngen
task.attach.submit=Senden
task.attach.title=#{0}: Datei anh\u00e4ngen
task.get.attach=Datei anh\u00e4ngen
task.get.attachments=Anh\u00e4nge:
task.get.download=Download
task.get.header=Task #{0}:
task.get.list=Zur\u00fcck
task.get.title={0}: Task Details
task.list.add-new=Neuer Task
task.list.details=Details
task.list.header={0}''s Tasks:
task.list.home=Startseite
task.list.title={0}: Task Liste
@@ -1 +0,0 @@
stylesheet=/public/css/themes/post_it.css
@@ -1 +0,0 @@
stylesheet=/public/css/themes/robotask.css
@@ -0,0 +1 @@
styleSheet=/resources/css/default.css
@@ -0,0 +1 @@
styleSheet=/resources/css/example.css

Some files were not shown because too many files have changed in this diff Show More