Merge remote-tracking branch 'upstream/master' into JAVA-3570
This commit is contained in:
@@ -15,6 +15,15 @@
|
||||
|
||||
<modules>
|
||||
<module>spring-mvc-basics</module>
|
||||
<module>spring-mvc-basics-2</module>
|
||||
<module>spring-mvc-basics-3</module>
|
||||
<module>spring-mvc-basics-4</module>
|
||||
<module>spring-mvc-crash</module>
|
||||
<module>spring-mvc-forms-jsp</module>
|
||||
<module>spring-rest-http</module>
|
||||
<module>spring-thymeleaf</module>
|
||||
<module>spring-thymeleaf-2</module>
|
||||
<module>spring-thymeleaf-3</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
## Spring MVC Basics 2
|
||||
|
||||
This module contains articles about Spring MVC
|
||||
|
||||
## Relevant articles:
|
||||
- [HandlerAdapters in Spring MVC](https://www.baeldung.com/spring-mvc-handler-adapters)
|
||||
- [Template Engines for Spring](https://www.baeldung.com/spring-template-engines)
|
||||
- [Spring 5 and Servlet 4 – The PushBuilder](https://www.baeldung.com/spring-5-push)
|
||||
- [Servlet Redirect vs Forward](https://www.baeldung.com/servlet-redirect-forward)
|
||||
- [Guide to Spring Email](https://www.baeldung.com/spring-email)
|
||||
- [Using ThymeLeaf and FreeMarker Emails Templates with Spring](https://www.baeldung.com/spring-email-templates)
|
||||
- [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405)
|
||||
- [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param)
|
||||
- [Spring @RequestParam vs @PathVariable Annotations](https://www.baeldung.com/spring-requestparam-vs-pathvariable)
|
||||
- More articles: [[more -->]](/spring-mvc-basics-3)
|
||||
- More articles: [[<-- prev]](/spring-mvc-basics)
|
||||
@@ -0,0 +1,184 @@
|
||||
<?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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-mvc-basics-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>spring-mvc-basics-2</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-spring-5</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-spring-5</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-oxm</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.mail</groupId>
|
||||
<artifactId>javax.mail</artifactId>
|
||||
<version>${javax.mail.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet.jsp</groupId>
|
||||
<artifactId>javax.servlet.jsp-api</artifactId>
|
||||
<version>${javax.servlet.jsp-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-fileupload</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
<version>${commons-fileupload.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- thymeleaf dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf</groupId>
|
||||
<artifactId>thymeleaf</artifactId>
|
||||
<version>${org.thymeleaf-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf</groupId>
|
||||
<artifactId>thymeleaf-spring5</artifactId>
|
||||
<version>${org.thymeleaf-version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- freemarker dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.freemarker</groupId>
|
||||
<artifactId>freemarker</artifactId>
|
||||
<version>${freemarker.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context-support</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-freemarker</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- groovy template dependency -->
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-templates</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- jade dependency -->
|
||||
<dependency>
|
||||
<groupId>de.neuland-bfi</groupId>
|
||||
<artifactId>spring-jade4j</artifactId>
|
||||
<version>${jade.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Testing -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.rometools</groupId>
|
||||
<artifactId>rome</artifactId>
|
||||
<version>${rome.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.thoughtworks.xstream</groupId>
|
||||
<artifactId>xstream</artifactId>
|
||||
<version>${xstream.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.scribejava</groupId>
|
||||
<artifactId>scribejava-apis</artifactId>
|
||||
<version>${scribejava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>${json.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.surefire</groupId>
|
||||
<artifactId>surefire-logger-api</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<!-- to get around bug https://github.com/junit-team/junit5/issues/1367 -->
|
||||
<scope>test</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>spring-mvc-basics-2</finalName>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
<configuration>
|
||||
<warSourceDirectory>src/main/webapp</warSourceDirectory>
|
||||
<warName>springMvcSimple</warName>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
<outputDirectory>${deploy-path}</outputDirectory>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<javax.servlet.jsp-api.version>2.3.2-b02</javax.servlet.jsp-api.version>
|
||||
<javax.servlet-api.version>4.0.0</javax.servlet-api.version>
|
||||
<hibernate-validator.version>6.0.10.Final</hibernate-validator.version>
|
||||
<deploy-path>enter-location-of-server</deploy-path>
|
||||
<commons-fileupload.version>1.3.2</commons-fileupload.version>
|
||||
<org.thymeleaf-version>3.0.11.RELEASE</org.thymeleaf-version>
|
||||
<groovy.version>2.4.12</groovy.version>
|
||||
<freemarker.version>2.3.27-incubating</freemarker.version>
|
||||
<jade.version>1.2.5</jade.version>
|
||||
<rome.version>1.9.0</rome.version>
|
||||
<xstream.version>1.4.9</xstream.version>
|
||||
<scribejava.version>5.1.0</scribejava.version>
|
||||
<json.version>20180130</json.version>
|
||||
<javax.mail.version>1.6.1</javax.mail.version>
|
||||
<spring-boot.version>2.3.4.RELEASE</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.spring.configuration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.http.converter.feed.RssChannelHttpMessageConverter;
|
||||
import org.springframework.web.accept.ContentNegotiationManager;
|
||||
import org.springframework.web.multipart.MultipartResolver;
|
||||
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
|
||||
import com.baeldung.spring.controller.rss.ArticleRssFeedViewResolver;
|
||||
import com.baeldung.spring.controller.rss.JsonChannelHttpMessageConverter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator", "com.baeldung.spring.mail", "com.baeldung.spring.service" })
|
||||
public class ApplicationConfiguration implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||
configurer.enable();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ContentNegotiatingViewResolver viewResolver(ContentNegotiationManager cnManager) {
|
||||
ContentNegotiatingViewResolver cnvResolver = new ContentNegotiatingViewResolver();
|
||||
cnvResolver.setContentNegotiationManager(cnManager);
|
||||
List<ViewResolver> resolvers = new ArrayList<>();
|
||||
|
||||
InternalResourceViewResolver bean = new InternalResourceViewResolver("/WEB-INF/views/",".jsp");
|
||||
ArticleRssFeedViewResolver articleRssFeedViewResolver = new ArticleRssFeedViewResolver();
|
||||
|
||||
resolvers.add(bean);
|
||||
resolvers.add(articleRssFeedViewResolver);
|
||||
|
||||
cnvResolver.setViewResolvers(resolvers);
|
||||
return cnvResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MultipartResolver multipartResolver() {
|
||||
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
|
||||
multipartResolver.setMaxUploadSize(5242880);
|
||||
return multipartResolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
|
||||
converters.add(new StringHttpMessageConverter());
|
||||
converters.add(new RssChannelHttpMessageConverter());
|
||||
converters.add(new JsonChannelHttpMessageConverter());
|
||||
}
|
||||
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.baeldung.spring.configuration;
|
||||
|
||||
import freemarker.cache.ClassTemplateLoader;
|
||||
import freemarker.cache.TemplateLoader;
|
||||
import freemarker.template.Configuration;
|
||||
import java.util.Properties;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.context.support.ResourceBundleMessageSource;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
|
||||
import org.thymeleaf.spring5.SpringTemplateEngine;
|
||||
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
|
||||
import org.thymeleaf.templateresolver.ITemplateResolver;
|
||||
|
||||
@ComponentScan(basePackages = { "com.baeldung.spring.mail" })
|
||||
@PropertySource(value={"classpath:application.properties"})
|
||||
public class EmailConfiguration {
|
||||
|
||||
@Value("${spring.mail.host}")
|
||||
private String mailServerHost;
|
||||
|
||||
@Value("${spring.mail.port}")
|
||||
private Integer mailServerPort;
|
||||
|
||||
@Value("${spring.mail.username}")
|
||||
private String mailServerUsername;
|
||||
|
||||
@Value("${spring.mail.password}")
|
||||
private String mailServerPassword;
|
||||
|
||||
@Value("${spring.mail.properties.mail.smtp.auth}")
|
||||
private String mailServerAuth;
|
||||
|
||||
@Value("${spring.mail.properties.mail.smtp.starttls.enable}")
|
||||
private String mailServerStartTls;
|
||||
|
||||
@Value("${spring.mail.templates.path}")
|
||||
private String mailTemplatesPath;
|
||||
|
||||
@Bean
|
||||
public JavaMailSender getJavaMailSender() {
|
||||
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
|
||||
|
||||
mailSender.setHost(mailServerHost);
|
||||
mailSender.setPort(mailServerPort);
|
||||
|
||||
mailSender.setUsername(mailServerUsername);
|
||||
mailSender.setPassword(mailServerPassword);
|
||||
|
||||
Properties props = mailSender.getJavaMailProperties();
|
||||
props.put("mail.transport.protocol", "smtp");
|
||||
props.put("mail.smtp.auth", mailServerAuth);
|
||||
props.put("mail.smtp.starttls.enable", mailServerStartTls);
|
||||
props.put("mail.debug", "true");
|
||||
|
||||
return mailSender;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SimpleMailMessage templateSimpleMessage() {
|
||||
SimpleMailMessage message = new SimpleMailMessage();
|
||||
message.setText("This is the test email template for your email:\n%s\n");
|
||||
return message;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SpringTemplateEngine thymeleafTemplateEngine(ITemplateResolver templateResolver) {
|
||||
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
|
||||
templateEngine.setTemplateResolver(templateResolver);
|
||||
templateEngine.setTemplateEngineMessageSource(emailMessageSource());
|
||||
return templateEngine;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ITemplateResolver thymeleafClassLoaderTemplateResolver() {
|
||||
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
|
||||
templateResolver.setPrefix(mailTemplatesPath + "/");
|
||||
templateResolver.setSuffix(".html");
|
||||
templateResolver.setTemplateMode("HTML");
|
||||
templateResolver.setCharacterEncoding("UTF-8");
|
||||
return templateResolver;
|
||||
}
|
||||
|
||||
// @Bean
|
||||
// public ITemplateResolver thymeleafFilesystemTemplateResolver() {
|
||||
// FileTemplateResolver templateResolver = new FileTemplateResolver();
|
||||
// templateResolver.setPrefix(mailTemplatesPath + "/");
|
||||
// templateResolver.setSuffix(".html");
|
||||
// templateResolver.setTemplateMode("HTML");
|
||||
// templateResolver.setCharacterEncoding("UTF-8");
|
||||
// return templateResolver;
|
||||
// }
|
||||
|
||||
@Bean
|
||||
public FreeMarkerConfigurer freemarkerClassLoaderConfig() {
|
||||
Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);
|
||||
TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), "/" + mailTemplatesPath);
|
||||
configuration.setTemplateLoader(templateLoader);
|
||||
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
|
||||
freeMarkerConfigurer.setConfiguration(configuration);
|
||||
return freeMarkerConfigurer;
|
||||
}
|
||||
|
||||
// @Bean
|
||||
// public FreeMarkerConfigurer freemarkerFilesystemConfig() throws IOException {
|
||||
// Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);
|
||||
// TemplateLoader templateLoader = new FileTemplateLoader(new File(mailTemplatesPath));
|
||||
// configuration.setTemplateLoader(templateLoader);
|
||||
// FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
|
||||
// freeMarkerConfigurer.setConfiguration(configuration);
|
||||
// return freeMarkerConfigurer;
|
||||
// }
|
||||
|
||||
@Bean
|
||||
public ResourceBundleMessageSource emailMessageSource() {
|
||||
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
|
||||
messageSource.setBasename("mailMessages");
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
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.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
|
||||
public class FreemarkerConfiguration {
|
||||
@Bean
|
||||
public FreeMarkerConfigurer freemarkerConfig() {
|
||||
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
|
||||
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/");
|
||||
return freeMarkerConfigurer;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FreeMarkerViewResolver freemarkerViewResolver() {
|
||||
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
|
||||
resolver.setCache(true);
|
||||
resolver.setPrefix("");
|
||||
resolver.setSuffix(".ftl");
|
||||
return resolver;
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
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.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer;
|
||||
import org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
|
||||
public class GroovyConfiguration {
|
||||
|
||||
@Bean
|
||||
public GroovyMarkupConfigurer groovyMarkupConfigurer() {
|
||||
GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
|
||||
configurer.setResourceLoaderPath("/WEB-INF/views/");
|
||||
return configurer;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public GroovyMarkupViewResolver thymeleafViewResolver() {
|
||||
GroovyMarkupViewResolver viewResolver = new GroovyMarkupViewResolver();
|
||||
viewResolver.setSuffix(".tpl");
|
||||
return viewResolver;
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
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.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
import de.neuland.jade4j.JadeConfiguration;
|
||||
import de.neuland.jade4j.spring.template.SpringTemplateLoader;
|
||||
import de.neuland.jade4j.spring.view.JadeViewResolver;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
|
||||
public class JadeTemplateConfiguration {
|
||||
@Bean
|
||||
public SpringTemplateLoader templateLoader() {
|
||||
SpringTemplateLoader templateLoader = new SpringTemplateLoader();
|
||||
templateLoader.setBasePath("/WEB-INF/views/");
|
||||
templateLoader.setSuffix(".jade");
|
||||
return templateLoader;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JadeConfiguration jadeConfiguration() {
|
||||
JadeConfiguration configuration = new JadeConfiguration();
|
||||
configuration.setCaching(false);
|
||||
configuration.setTemplateLoader(templateLoader());
|
||||
return configuration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
JadeViewResolver viewResolver = new JadeViewResolver();
|
||||
viewResolver.setConfiguration(jadeConfiguration());
|
||||
return viewResolver;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
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.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
|
||||
// needs HTTP 2 https://github.com/spring-projects/spring-framework/wiki/HTTP-2-support
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages = "com.baeldung.spring.push.controller")
|
||||
public class PushConfiguration implements WebMvcConfigurer {
|
||||
|
||||
@Bean
|
||||
public InternalResourceViewResolver jspViewResolver() {
|
||||
InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||
bean.setPrefix("/WEB-INF/views/");
|
||||
bean.setSuffix(".jsp");
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**")
|
||||
.addResourceLocations("/resources/");
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
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.servlet.config.annotation.EnableWebMvc;
|
||||
import org.thymeleaf.spring5.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
|
||||
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
|
||||
public class ThymeleafConfiguration {
|
||||
@Bean
|
||||
public SpringTemplateEngine templateEngine() {
|
||||
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
|
||||
templateEngine.setTemplateResolver(thymeleafTemplateResolver());
|
||||
return templateEngine;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SpringResourceTemplateResolver thymeleafTemplateResolver() {
|
||||
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
|
||||
templateResolver.setPrefix("/WEB-INF/views/");
|
||||
templateResolver.setSuffix(".html");
|
||||
templateResolver.setTemplateMode("HTML5");
|
||||
return templateResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ThymeleafViewResolver thymeleafViewResolver() {
|
||||
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
|
||||
viewResolver.setTemplateEngine(templateEngine());
|
||||
return viewResolver;
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
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.register(ThymeleafConfiguration.class);
|
||||
// ctx.register(FreemarkerConfiguration.class);
|
||||
// ctx.register(GroovyConfiguration.class);
|
||||
// ctx.register(JadeTemplateConfiguration.class);
|
||||
// ctx.register(PushConfiguration.class);
|
||||
ctx.register(EmailConfiguration.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("/");
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.spring.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
@Controller
|
||||
public class AnnotationMethodHandlerAdapterExample {
|
||||
@RequestMapping("/annotedName")
|
||||
public ModelAndView getEmployeeName() {
|
||||
ModelAndView model = new ModelAndView("Greeting");
|
||||
model.addObject("message", "Dinesh");
|
||||
return model;
|
||||
}
|
||||
}
|
||||
+42
@@ -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";
|
||||
}
|
||||
|
||||
}
|
||||
+47
@@ -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";
|
||||
}
|
||||
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
package com.baeldung.spring.controller;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.mail.MessagingException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
import com.baeldung.spring.domain.MailObject;
|
||||
import com.baeldung.spring.mail.EmailService;
|
||||
|
||||
import freemarker.template.TemplateException;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/mail")
|
||||
public class MailController {
|
||||
|
||||
@Autowired
|
||||
public EmailService emailService;
|
||||
|
||||
@Value("${attachment.invoice}")
|
||||
private String attachmentPath;
|
||||
|
||||
private static final Map<String, Map<String, String>> labels;
|
||||
|
||||
static {
|
||||
labels = new HashMap<>();
|
||||
|
||||
//Simple email
|
||||
Map<String, String> props = new HashMap<>();
|
||||
props.put("headerText", "Send Simple Email");
|
||||
props.put("messageLabel", "Message");
|
||||
props.put("additionalInfo", "");
|
||||
labels.put("send", props);
|
||||
|
||||
//Email with template
|
||||
props = new HashMap<>();
|
||||
props.put("headerText", "Send Email Using Text Template");
|
||||
props.put("messageLabel", "Template Parameter");
|
||||
props.put("additionalInfo",
|
||||
"The parameter value will be added to the following message template:<br>" +
|
||||
"<b>This is the test email template for your email:<br>'Template Parameter'</b>"
|
||||
);
|
||||
labels.put("sendTemplate", props);
|
||||
|
||||
//Email with attachment
|
||||
props = new HashMap<>();
|
||||
props.put("headerText", "Send Email With Attachment");
|
||||
props.put("messageLabel", "Message");
|
||||
props.put("additionalInfo", "To make sure that you send an attachment with this email, change the value for the 'attachment.invoice' in the application.properties file to the path to the attachment.");
|
||||
labels.put("sendAttachment", props);
|
||||
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET)
|
||||
public String showEmailsPage() {
|
||||
return "emails";
|
||||
}
|
||||
|
||||
@RequestMapping(value = {"/send", "/sendTemplate", "/sendAttachment"}, method = RequestMethod.GET)
|
||||
public String createMail(Model model,
|
||||
HttpServletRequest request) {
|
||||
String action = request.getRequestURL().substring(
|
||||
request.getRequestURL().lastIndexOf("/") + 1
|
||||
);
|
||||
Map<String, String> props = labels.get(action);
|
||||
Set<String> keys = props.keySet();
|
||||
Iterator<String> iterator = keys.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
String key = iterator.next();
|
||||
model.addAttribute(key, props.get(key));
|
||||
}
|
||||
|
||||
model.addAttribute("mailObject", new MailObject());
|
||||
return "mail/send";
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = "/send", method = RequestMethod.POST)
|
||||
public String createMail(Model model,
|
||||
@ModelAttribute("mailObject") @Valid MailObject mailObject,
|
||||
Errors errors) {
|
||||
if (errors.hasErrors()) {
|
||||
return "mail/send";
|
||||
}
|
||||
emailService.sendSimpleMessage(mailObject.getTo(),
|
||||
mailObject.getSubject(), mailObject.getText());
|
||||
|
||||
return "emails";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/sendTemplate", method = RequestMethod.POST)
|
||||
public String createMailWithTemplate(Model model,
|
||||
@ModelAttribute("mailObject") @Valid MailObject mailObject,
|
||||
Errors errors) {
|
||||
if (errors.hasErrors()) {
|
||||
return "mail/send";
|
||||
}
|
||||
emailService.sendSimpleMessageUsingTemplate(mailObject.getTo(),
|
||||
mailObject.getSubject(),
|
||||
mailObject.getText());
|
||||
|
||||
return "redirect:/mail";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/sendAttachment", method = RequestMethod.POST)
|
||||
public String createMailWithAttachment(Model model,
|
||||
@ModelAttribute("mailObject") @Valid MailObject mailObject,
|
||||
Errors errors) {
|
||||
if (errors.hasErrors()) {
|
||||
return "mail/send";
|
||||
}
|
||||
emailService.sendMessageWithAttachment(
|
||||
mailObject.getTo(),
|
||||
mailObject.getSubject(),
|
||||
mailObject.getText(),
|
||||
attachmentPath
|
||||
);
|
||||
|
||||
return "redirect:/mail";
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = {"/sendHtml"}, method = RequestMethod.GET)
|
||||
public String getHtmlMailView(Model model,
|
||||
HttpServletRequest request) {
|
||||
|
||||
Map<String, String> templateEngines = new HashMap<>();
|
||||
templateEngines.put("Thymeleaf", "Thymeleaf");
|
||||
templateEngines.put("Freemarker", "Freemarker");
|
||||
model.addAttribute("mailObject", new MailObject());
|
||||
model.addAttribute("templateEngines", templateEngines);
|
||||
return "mail/sendHtml";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/sendHtml", method = RequestMethod.POST)
|
||||
public String createHtmlMail(Model model,
|
||||
@ModelAttribute("mailObject") @Valid MailObject mailObject,
|
||||
Errors errors) throws IOException, MessagingException, TemplateException {
|
||||
if (errors.hasErrors()) {
|
||||
return "mail/send";
|
||||
}
|
||||
|
||||
Map<String, Object> templateModel = new HashMap<>();
|
||||
templateModel.put("recipientName", mailObject.getRecipientName());
|
||||
templateModel.put("text", mailObject.getText());
|
||||
templateModel.put("senderName", mailObject.getSenderName());
|
||||
|
||||
if (mailObject.getTemplateEngine().equalsIgnoreCase("thymeleaf")) {
|
||||
emailService.sendMessageUsingThymeleafTemplate(
|
||||
mailObject.getTo(),
|
||||
mailObject.getSubject(),
|
||||
templateModel);
|
||||
} else {
|
||||
emailService.sendMessageUsingFreemarkerTemplate(
|
||||
mailObject.getTo(),
|
||||
mailObject.getSubject(),
|
||||
templateModel);
|
||||
}
|
||||
|
||||
return "redirect:/mail";
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.spring.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
@Controller
|
||||
public class RequestMappingHandlerAdapterExample {
|
||||
@RequestMapping("/requestName")
|
||||
public ModelAndView getEmployeeName() {
|
||||
ModelAndView model = new ModelAndView("Greeting");
|
||||
model.addObject("message", "Madhwal");
|
||||
return model;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.spring.controller;
|
||||
|
||||
import com.baeldung.spring.domain.Employee;
|
||||
import com.baeldung.spring.exception.InvalidRequestException;
|
||||
import com.baeldung.spring.service.EmployeeService;
|
||||
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.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(value="/api")
|
||||
public class RequestMethodController {
|
||||
|
||||
@Autowired
|
||||
EmployeeService service;
|
||||
|
||||
@RequestMapping(value = "/employees", produces = "application/json", method={RequestMethod.GET,RequestMethod.POST})
|
||||
public List<Employee> findEmployees()
|
||||
throws InvalidRequestException {
|
||||
return service.getEmployeeList();
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.spring.controller;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.mvc.AbstractController;
|
||||
|
||||
public class SimpleControllerHandlerAdapterExample extends AbstractController {
|
||||
@Override
|
||||
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
ModelAndView model = new ModelAndView("Greeting");
|
||||
model.addObject("message", "Dinesh Madhwal");
|
||||
return model;
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.spring.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import com.baeldung.spring.domain.User;
|
||||
|
||||
@Controller
|
||||
public class UserController {
|
||||
|
||||
@GetMapping("/registration")
|
||||
public String getRegistration(Model model) {
|
||||
model.addAttribute("user", new User());
|
||||
return "registration";
|
||||
}
|
||||
|
||||
@GetMapping("/registration-thymeleaf")
|
||||
public String getRegistrationThymeleaf(Model model) {
|
||||
model.addAttribute("user", new User());
|
||||
return "registration-thymeleaf";
|
||||
}
|
||||
|
||||
@GetMapping("/registration-freemarker")
|
||||
public String getRegistrationFreemarker(Model model) {
|
||||
model.addAttribute("user", new User());
|
||||
return "registration-freemarker";
|
||||
}
|
||||
|
||||
@GetMapping("/registration-groovy")
|
||||
public String getRegistrationGroovy(Model model) {
|
||||
model.addAttribute("user", new User());
|
||||
return "registration-groovy";
|
||||
}
|
||||
|
||||
@GetMapping("/registration-jade")
|
||||
public String getRegistrationJade(Model model) {
|
||||
model.addAttribute("user", new User());
|
||||
return "registration-jade";
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
@ResponseBody
|
||||
public void register(User user){
|
||||
System.out.println(user.getEmail());
|
||||
}
|
||||
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.spring.controller.rss;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
public class Article implements Serializable {
|
||||
private String link;
|
||||
private String title;
|
||||
private String description;
|
||||
private Date publishedDate;
|
||||
private String author;
|
||||
|
||||
public String getLink() {
|
||||
return link;
|
||||
}
|
||||
|
||||
public void setLink(String link) {
|
||||
this.link = link;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Date getPublishedDate() {
|
||||
return publishedDate;
|
||||
}
|
||||
|
||||
public void setPublishedDate(Date publishedDate) {
|
||||
this.publishedDate = publishedDate;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Article{" +
|
||||
"link='" + link + '\'' +
|
||||
", title='" + title + '\'' +
|
||||
", description='" + description + '\'' +
|
||||
", publishedDate=" + publishedDate +
|
||||
", author='" + author + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.spring.controller.rss;
|
||||
|
||||
import com.rometools.rome.feed.rss.Channel;
|
||||
import com.rometools.rome.feed.rss.Description;
|
||||
import com.rometools.rome.feed.rss.Item;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.servlet.view.feed.AbstractRssFeedView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service("articleFeedView")
|
||||
public class ArticleFeedView extends AbstractRssFeedView {
|
||||
|
||||
protected Channel newFeed() {
|
||||
Channel channel = new Channel("rss_2.0");
|
||||
channel.setLink("http://localhost:8080/spring-mvc-simple/rss");
|
||||
channel.setTitle("Article Feed");
|
||||
channel.setDescription("Article Feed Description");
|
||||
channel.setPubDate(new Date());
|
||||
return channel;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<Item> buildFeedItems(Map<String, Object> map, HttpServletRequest httpStRequest, HttpServletResponse httpStResponse) throws Exception {
|
||||
List list = new ArrayList<Item>();
|
||||
|
||||
Item item1 = new Item();
|
||||
item1.setLink("http://www.baeldung.com/netty-exception-handling");
|
||||
item1.setTitle("Exceptions in Netty");
|
||||
Description description1 = new Description();
|
||||
description1.setValue("In this quick article, we’ll be looking at exception handling in Netty.");
|
||||
item1.setDescription(description1);
|
||||
item1.setPubDate(new Date());
|
||||
item1.setAuthor("Carlos");
|
||||
|
||||
Item item2 = new Item();
|
||||
item2.setLink("http://www.baeldung.com/cockroachdb-java");
|
||||
item2.setTitle("Guide to CockroachDB in Java");
|
||||
Description description2 = new Description();
|
||||
description2.setValue("This tutorial is an introductory guide to using CockroachDB with Java.");
|
||||
item2.setDescription(description2);
|
||||
item2.setPubDate(new Date());
|
||||
item2.setAuthor("Baeldung");
|
||||
|
||||
list.add(item1);
|
||||
list.add(item2);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.spring.controller.rss;
|
||||
|
||||
import com.rometools.rome.feed.rss.Channel;
|
||||
import com.rometools.rome.feed.rss.Description;
|
||||
import com.rometools.rome.feed.rss.Item;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@Controller
|
||||
public class ArticleRssController {
|
||||
|
||||
@GetMapping(value = "/rss1")
|
||||
public String articleMvcFeed() {
|
||||
return "articleFeedView";
|
||||
}
|
||||
|
||||
@GetMapping(value = "/rss2", produces = {"application/rss+xml", "application/rss+json"})
|
||||
@ResponseBody
|
||||
public Channel articleHttpFeed() {
|
||||
List<Article> items = new ArrayList<>();
|
||||
Article item1 = new Article();
|
||||
item1.setLink("http://www.baeldung.com/netty-exception-handling");
|
||||
item1.setTitle("Exceptions in Netty");
|
||||
item1.setDescription("In this quick article, we’ll be looking at exception handling in Netty.");
|
||||
item1.setPublishedDate(new Date());
|
||||
item1.setAuthor("Carlos");
|
||||
|
||||
Article item2 = new Article();
|
||||
item2.setLink("http://www.baeldung.com/cockroachdb-java");
|
||||
item2.setTitle("Guide to CockroachDB in Java");
|
||||
item2.setDescription("This tutorial is an introductory guide to using CockroachDB with Java.");
|
||||
item2.setPublishedDate(new Date());
|
||||
item2.setAuthor("Baeldung");
|
||||
|
||||
items.add(item1);
|
||||
items.add(item2);
|
||||
Channel channelData = buildChannel(items);
|
||||
|
||||
return channelData;
|
||||
}
|
||||
|
||||
private Channel buildChannel(List<Article> articles){
|
||||
Channel channel = new Channel("rss_2.0");
|
||||
channel.setLink("http://localhost:8080/spring-mvc-simple/rss");
|
||||
channel.setTitle("Article Feed");
|
||||
channel.setDescription("Article Feed Description");
|
||||
channel.setPubDate(new Date());
|
||||
|
||||
List<Item> items = new ArrayList<>();
|
||||
for (Article article : articles) {
|
||||
Item item = new Item();
|
||||
item.setLink(article.getLink());
|
||||
item.setTitle(article.getTitle());
|
||||
Description description1 = new Description();
|
||||
description1.setValue(article.getDescription());
|
||||
item.setDescription(description1);
|
||||
item.setPubDate(article.getPublishedDate());
|
||||
item.setAuthor(article.getAuthor());
|
||||
items.add(item);
|
||||
}
|
||||
|
||||
channel.setItems(items);
|
||||
return channel;
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.spring.controller.rss;
|
||||
|
||||
import org.springframework.web.servlet.View;
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public class ArticleRssFeedViewResolver implements ViewResolver {
|
||||
|
||||
@Override
|
||||
public View resolveViewName(String s, Locale locale) throws Exception {
|
||||
ArticleFeedView articleFeedView = new ArticleFeedView();
|
||||
return articleFeedView;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.spring.controller.rss;
|
||||
|
||||
import com.rometools.rome.feed.rss.Channel;
|
||||
import com.rometools.rome.io.FeedException;
|
||||
import com.rometools.rome.io.WireFeedOutput;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.json.XML;
|
||||
import org.springframework.http.HttpInputMessage;
|
||||
import org.springframework.http.HttpOutputMessage;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.AbstractHttpMessageConverter;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.http.converter.HttpMessageNotWritableException;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class JsonChannelHttpMessageConverter extends AbstractHttpMessageConverter<Channel> {
|
||||
public JsonChannelHttpMessageConverter(){
|
||||
super(new MediaType("application", "rss+json"));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean supports(Class<?> aClass) {
|
||||
return Channel.class.isAssignableFrom(aClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Channel readInternal(Class<? extends Channel> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void writeInternal(Channel wireFeed, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
|
||||
WireFeedOutput feedOutput = new WireFeedOutput();
|
||||
|
||||
try {
|
||||
String xmlStr = feedOutput.outputString(wireFeed, true);
|
||||
JSONObject xmlJSONObj = XML.toJSONObject(xmlStr);
|
||||
String jsonPrettyPrintString = xmlJSONObj.toString(4);
|
||||
|
||||
outputMessage.getBody().write(jsonPrettyPrintString.getBytes());
|
||||
} catch (JSONException | FeedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.spring.controller.scribe;
|
||||
|
||||
import com.github.scribejava.apis.GitHubApi;
|
||||
import com.github.scribejava.core.builder.ServiceBuilder;
|
||||
import com.github.scribejava.core.model.*;
|
||||
import com.github.scribejava.core.oauth.OAuth20Service;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.servlet.view.RedirectView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("github")
|
||||
public class GithubController {
|
||||
private OAuth20Service createService(String state) {
|
||||
return new ServiceBuilder("e1f8d4f1a5c71467a159")
|
||||
.apiSecret("4851597541a8f33a4f1bf1c70f3cedcfefbeb13b")
|
||||
.state(state)
|
||||
.callback("http://localhost:8080/spring-mvc-simple/github/callback")
|
||||
.build(GitHubApi.instance());
|
||||
}
|
||||
|
||||
@GetMapping(value = "/authorization")
|
||||
public RedirectView authorization(HttpServletRequest servletReq) throws InterruptedException, ExecutionException, IOException {
|
||||
String state = String.valueOf(new Random().nextInt(999_999));
|
||||
OAuth20Service githubService = createService(state);
|
||||
servletReq.getSession().setAttribute("state", state);
|
||||
|
||||
String authorizationUrl = githubService.getAuthorizationUrl();
|
||||
RedirectView redirectView = new RedirectView();
|
||||
redirectView.setUrl(authorizationUrl);
|
||||
return redirectView;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/callback", produces = "text/plain")
|
||||
@ResponseBody
|
||||
public String callback(HttpServletRequest servletReq, @RequestParam("code") String code, @RequestParam("state") String state) throws InterruptedException, ExecutionException, IOException {
|
||||
String initialState = (String) servletReq.getSession().getAttribute("state");
|
||||
if(initialState.equals(state)) {
|
||||
OAuth20Service githubService = createService(initialState);
|
||||
OAuth2AccessToken accessToken = githubService.getAccessToken(code);
|
||||
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.github.com/user");
|
||||
githubService.signRequest(accessToken, request);
|
||||
Response response = githubService.execute(request);
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
return "Error";
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.spring.controller.scribe;
|
||||
|
||||
import com.github.scribejava.apis.TwitterApi;
|
||||
import com.github.scribejava.core.builder.ServiceBuilder;
|
||||
import com.github.scribejava.core.model.*;
|
||||
import com.github.scribejava.core.oauth.OAuth10aService;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.servlet.view.RedirectView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("twitter")
|
||||
public class TwitterController {
|
||||
|
||||
private OAuth10aService createService() {
|
||||
return new ServiceBuilder("PSRszoHhRDVhyo2RIkThEbWko")
|
||||
.apiSecret("prpJbz03DcGRN46sb4ucdSYtVxG8unUKhcnu3an5ItXbEOuenL")
|
||||
.callback("http://localhost:8080/spring-mvc-simple/twitter/callback")
|
||||
.build(TwitterApi.instance());
|
||||
}
|
||||
|
||||
@GetMapping(value = "/authorization")
|
||||
public RedirectView authorization(HttpServletRequest servletReq) throws InterruptedException, ExecutionException, IOException {
|
||||
OAuth10aService twitterService = createService();
|
||||
|
||||
OAuth1RequestToken requestToken = twitterService.getRequestToken();
|
||||
String authorizationUrl = twitterService.getAuthorizationUrl(requestToken);
|
||||
servletReq.getSession().setAttribute("requestToken", requestToken);
|
||||
|
||||
RedirectView redirectView = new RedirectView();
|
||||
redirectView.setUrl(authorizationUrl);
|
||||
return redirectView;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/callback", produces = "text/plain")
|
||||
@ResponseBody
|
||||
public String callback(HttpServletRequest servletReq, @RequestParam("oauth_verifier") String oauthV) throws InterruptedException, ExecutionException, IOException {
|
||||
OAuth10aService twitterService = createService();
|
||||
OAuth1RequestToken requestToken = (OAuth1RequestToken) servletReq.getSession().getAttribute("requestToken");
|
||||
OAuth1AccessToken accessToken = twitterService.getAccessToken(requestToken, oauthV);
|
||||
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json");
|
||||
twitterService.signRequest(accessToken, request);
|
||||
Response response = twitterService.execute(request);
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
}
|
||||
+45
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+46
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.spring.domain;
|
||||
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
/**
|
||||
* Created by Olga on 7/20/2016.
|
||||
*/
|
||||
public class MailObject {
|
||||
@Email
|
||||
@NotNull
|
||||
@Size(min = 1, message = "Please, set an email address to send the message to it")
|
||||
private String to;
|
||||
private String recipientName;
|
||||
private String subject;
|
||||
private String text;
|
||||
private String senderName;
|
||||
private String templateEngine;
|
||||
|
||||
public String getTo() {
|
||||
return to;
|
||||
}
|
||||
|
||||
public void setTo(String to) {
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
public String getSubject() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public String getRecipientName() {
|
||||
return recipientName;
|
||||
}
|
||||
|
||||
public void setRecipientName(String recipientName) {
|
||||
this.recipientName = recipientName;
|
||||
}
|
||||
|
||||
public String getSenderName() {
|
||||
return senderName;
|
||||
}
|
||||
|
||||
public void setSenderName(String senderName) {
|
||||
this.senderName = senderName;
|
||||
}
|
||||
|
||||
public String getTemplateEngine() {
|
||||
return templateEngine;
|
||||
}
|
||||
|
||||
public void setTemplateEngine(String templateEngine) {
|
||||
this.templateEngine = templateEngine;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.spring.domain;
|
||||
|
||||
public class User {
|
||||
private String email;
|
||||
private String password;
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.spring.exception;
|
||||
|
||||
public class InvalidRequestException extends RuntimeException {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 4088649120307193208L;
|
||||
|
||||
public InvalidRequestException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public InvalidRequestException(final String message, final Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public InvalidRequestException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public InvalidRequestException(final Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
||||
+19
@@ -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;
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.spring.mail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.mail.MessagingException;
|
||||
|
||||
import freemarker.template.TemplateException;
|
||||
|
||||
/**
|
||||
* Created by Olga on 8/22/2016.
|
||||
*/
|
||||
public interface EmailService {
|
||||
void sendSimpleMessage(String to,
|
||||
String subject,
|
||||
String text);
|
||||
void sendSimpleMessageUsingTemplate(String to,
|
||||
String subject,
|
||||
String ...templateModel);
|
||||
void sendMessageWithAttachment(String to,
|
||||
String subject,
|
||||
String text,
|
||||
String pathToAttachment);
|
||||
|
||||
void sendMessageUsingThymeleafTemplate(String to,
|
||||
String subject,
|
||||
Map<String, Object> templateModel)
|
||||
throws IOException, MessagingException;
|
||||
|
||||
void sendMessageUsingFreemarkerTemplate(String to,
|
||||
String subject,
|
||||
Map<String, Object> templateModel)
|
||||
throws IOException, TemplateException, MessagingException;
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package com.baeldung.spring.mail;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
|
||||
import org.thymeleaf.context.Context;
|
||||
import org.thymeleaf.spring5.SpringTemplateEngine;
|
||||
|
||||
import freemarker.template.Template;
|
||||
import freemarker.template.TemplateException;
|
||||
|
||||
/**
|
||||
* Created by Olga on 7/15/2016.
|
||||
*/
|
||||
@Service("EmailService")
|
||||
public class EmailServiceImpl implements EmailService {
|
||||
|
||||
private static final String NOREPLY_ADDRESS = "noreply@baeldung.com";
|
||||
|
||||
@Autowired
|
||||
private JavaMailSender emailSender;
|
||||
|
||||
@Autowired
|
||||
private SimpleMailMessage template;
|
||||
|
||||
@Autowired
|
||||
private SpringTemplateEngine thymeleafTemplateEngine;
|
||||
|
||||
@Autowired
|
||||
private FreeMarkerConfigurer freemarkerConfigurer;
|
||||
|
||||
@Value("classpath:/mail-logo.png")
|
||||
private Resource resourceFile;
|
||||
|
||||
public void sendSimpleMessage(String to, String subject, String text) {
|
||||
try {
|
||||
SimpleMailMessage message = new SimpleMailMessage();
|
||||
message.setFrom(NOREPLY_ADDRESS);
|
||||
message.setTo(to);
|
||||
message.setSubject(subject);
|
||||
message.setText(text);
|
||||
|
||||
emailSender.send(message);
|
||||
} catch (MailException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendSimpleMessageUsingTemplate(String to,
|
||||
String subject,
|
||||
String ...templateModel) {
|
||||
String text = String.format(template.getText(), templateModel);
|
||||
sendSimpleMessage(to, subject, text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessageWithAttachment(String to,
|
||||
String subject,
|
||||
String text,
|
||||
String pathToAttachment) {
|
||||
try {
|
||||
MimeMessage message = emailSender.createMimeMessage();
|
||||
// pass 'true' to the constructor to create a multipart message
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true);
|
||||
|
||||
helper.setFrom(NOREPLY_ADDRESS);
|
||||
helper.setTo(to);
|
||||
helper.setSubject(subject);
|
||||
helper.setText(text);
|
||||
|
||||
FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
|
||||
helper.addAttachment("Invoice", file);
|
||||
|
||||
emailSender.send(message);
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void sendMessageUsingThymeleafTemplate(
|
||||
String to, String subject, Map<String, Object> templateModel)
|
||||
throws MessagingException {
|
||||
|
||||
Context thymeleafContext = new Context();
|
||||
thymeleafContext.setVariables(templateModel);
|
||||
|
||||
String htmlBody = thymeleafTemplateEngine.process("template-thymeleaf.html", thymeleafContext);
|
||||
|
||||
sendHtmlMessage(to, subject, htmlBody);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessageUsingFreemarkerTemplate(
|
||||
String to, String subject, Map<String, Object> templateModel)
|
||||
throws IOException, TemplateException, MessagingException {
|
||||
|
||||
Template freemarkerTemplate = freemarkerConfigurer.getConfiguration().getTemplate("template-freemarker.ftl");
|
||||
String htmlBody = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerTemplate, templateModel);
|
||||
|
||||
sendHtmlMessage(to, subject, htmlBody);
|
||||
}
|
||||
|
||||
private void sendHtmlMessage(String to, String subject, String htmlBody) throws MessagingException {
|
||||
|
||||
MimeMessage message = emailSender.createMimeMessage();
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
|
||||
helper.setFrom(NOREPLY_ADDRESS);
|
||||
helper.setTo(to);
|
||||
helper.setSubject(subject);
|
||||
helper.setText(htmlBody, true);
|
||||
helper.addInline("attachment.png", resourceFile);
|
||||
emailSender.send(message);
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.spring.push.controller;
|
||||
|
||||
import javax.servlet.http.PushBuilder;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class PushController {
|
||||
|
||||
@GetMapping(path = "/demoWithPush")
|
||||
public String demoWithPush(PushBuilder pushBuilder) {
|
||||
if (null != pushBuilder) {
|
||||
pushBuilder.path("resources/logo.png").push();
|
||||
}
|
||||
return "demo";
|
||||
}
|
||||
|
||||
@GetMapping(path = "/demoWithoutPush")
|
||||
public String demoWithoutPush() {
|
||||
return "demo";
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.baeldung.spring.requestparam;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
|
||||
@Controller
|
||||
public class RequestParamController {
|
||||
|
||||
@GetMapping("/api/foos")
|
||||
@ResponseBody
|
||||
public String getFoos(@RequestParam String id){
|
||||
return "ID: " + id;
|
||||
}
|
||||
|
||||
@PostMapping("/api/foos")
|
||||
@ResponseBody
|
||||
public String addFoo(@RequestParam(name = "id") String fooId, @RequestParam String name){
|
||||
return "ID: " + fooId;
|
||||
}
|
||||
|
||||
@GetMapping("/api/foos2")
|
||||
@ResponseBody
|
||||
public String getFoos2(@RequestParam(required = false) String id){
|
||||
return "ID: " + id;
|
||||
}
|
||||
|
||||
@GetMapping("/api/foosOptional")
|
||||
@ResponseBody
|
||||
public String getFoosOptional(@RequestParam Optional<String> id){
|
||||
return "ID: " + id.orElseGet(() -> "not provided");
|
||||
}
|
||||
|
||||
@GetMapping("/api/foos3")
|
||||
@ResponseBody
|
||||
public String getFoos3(@RequestParam(defaultValue = "test") String id){
|
||||
return "ID: " + id;
|
||||
}
|
||||
|
||||
@PostMapping("/api/foos1")
|
||||
@ResponseBody
|
||||
public String updateFoos(@RequestParam Map<String,String> allParams){
|
||||
return "Parameters are " + allParams.entrySet();
|
||||
}
|
||||
|
||||
@GetMapping("/api/foos4")
|
||||
@ResponseBody
|
||||
public String getFoos4(@RequestParam List<String> id){
|
||||
return "IDs are " + id;
|
||||
}
|
||||
|
||||
@GetMapping("/foos/{id}")
|
||||
@ResponseBody
|
||||
public String getFooById(@PathVariable String id){
|
||||
return "ID: " + id;
|
||||
}
|
||||
|
||||
@GetMapping("/foos")
|
||||
@ResponseBody
|
||||
public String getFooByIdUsingQueryParam(@RequestParam String id){
|
||||
return "ID: " + id;
|
||||
}
|
||||
|
||||
@GetMapping({"/myfoos/optional", "/myfoos/optional/{id}"})
|
||||
@ResponseBody
|
||||
public String getFooByOptionalId(@PathVariable(required = false) String id){
|
||||
return "ID: " + id;
|
||||
}
|
||||
|
||||
@GetMapping("/myfoos/optionalParam")
|
||||
@ResponseBody
|
||||
public String getFooByOptionalIdUsingQueryParam(@RequestParam(required = false) String id){
|
||||
return "ID: " + id;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.spring.service;
|
||||
|
||||
import com.baeldung.spring.domain.Employee;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public interface EmployeeService {
|
||||
|
||||
List<Employee> getEmployeeList();
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.spring.service;
|
||||
|
||||
import com.baeldung.spring.domain.Employee;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class EmployeeServiceImpl implements EmployeeService{
|
||||
|
||||
@Override
|
||||
public List<Employee> getEmployeeList() {
|
||||
List<Employee> employeeList = new ArrayList<>();
|
||||
employeeList.add(createEmployee(100L, "Steve Martin", "333-777-999"));
|
||||
employeeList.add(createEmployee(200L, "Adam Schawn", "444-111-777"));
|
||||
return employeeList;
|
||||
}
|
||||
|
||||
private Employee createEmployee(long id, String name, String contactNumber) {
|
||||
Employee employee = new Employee();
|
||||
employee.setId(id);
|
||||
employee.setName(name);
|
||||
employee.setContactNumber(contactNumber);
|
||||
return employee;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.spring.servlets;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
@WebServlet("/forwarded")
|
||||
public class ForwardedServlet extends HttpServlet {
|
||||
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
||||
PrintWriter out = resp.getWriter();
|
||||
out.write("In forwarded servlet page.");
|
||||
out.write("\nWelcome:" + req.getParameter("name"));
|
||||
}
|
||||
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.spring.servlets;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet("/hello")
|
||||
public class HelloServlet extends HttpServlet {
|
||||
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
||||
RequestDispatcher dispatcher = req.getRequestDispatcher("/forwarded");
|
||||
dispatcher.forward(req, resp);
|
||||
}
|
||||
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.spring.servlets;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
@WebServlet("/redirected")
|
||||
public class RedirectedServlet extends HttpServlet {
|
||||
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
||||
PrintWriter out = resp.getWriter();
|
||||
out.write("In redirected servlet page.");
|
||||
out.write("\nWelcome:" + req.getParameter("name"));
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.spring.servlets;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet("/welcome")
|
||||
public class WelcomeServlet extends HttpServlet {
|
||||
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
||||
resp.sendRedirect(req.getContextPath() + "/redirected");
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -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.");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#this property file will have to be loaded explicitly as this is not a Spring Boot project
|
||||
|
||||
# Gmail SMTP
|
||||
spring.mail.host=smtp.gmail.com
|
||||
spring.mail.port=587
|
||||
spring.mail.username=username
|
||||
spring.mail.password=password
|
||||
spring.mail.properties.mail.smtp.auth=true
|
||||
spring.mail.properties.mail.smtp.starttls.enable=false
|
||||
|
||||
# Amazon SES SMTP
|
||||
#spring.mail.host=email-smtp.us-west-2.amazonaws.com
|
||||
#spring.mail.username=username
|
||||
#spring.mail.password=password
|
||||
#spring.mail.properties.mail.transport.protocol=smtp
|
||||
#spring.mail.properties.mail.smtp.port=25
|
||||
#spring.mail.properties.mail.smtp.auth=true
|
||||
#spring.mail.properties.mail.smtp.starttls.enable=true
|
||||
#spring.mail.properties.mail.smtp.starttls.required=true
|
||||
|
||||
# path to attachment file
|
||||
attachment.invoice=path_to_file
|
||||
|
||||
|
||||
#
|
||||
# Mail templates
|
||||
#
|
||||
|
||||
# Templates directory inside main/resources or absolute filesystem path
|
||||
spring.mail.templates.path=mail-templates
|
||||
#spring.mail.templates.path=/path/to/templates
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.2 KiB |
+15
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<p>Hi ${recipientName}</p>
|
||||
<p>${text}</p>
|
||||
<p>Regards,</p>
|
||||
<p>
|
||||
<em>${senderName} at Baeldung</em> <br />
|
||||
<img src="cid:attachment.png" />
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<p th:text="#{greetings(${recipientName})}"></p>
|
||||
<p th:text="${text}"></p>
|
||||
<p th:text="#{regards}"></p>
|
||||
<p>
|
||||
<em th:text="#{signature(${senderName})}"></em> <br />
|
||||
<img src="cid:attachment.png" />
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
greetings=Hi {0},
|
||||
subscriptions=Please find below your current subscriptions to our forum:
|
||||
regards=Regards,
|
||||
unsubscribe=Unsubscribe from these emails here
|
||||
signature={0} at Baeldung
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
greetings=Bonjour {0},
|
||||
subscriptions=Voici vos différentes souscriptions sur notre forum :
|
||||
regards=Cordialement,
|
||||
unsubscribe=Se désinscrire de ces emails ici
|
||||
signature={0} à Baeldung
|
||||
@@ -0,0 +1,6 @@
|
||||
<html>
|
||||
<body>
|
||||
<h1>Hello ${message}</h1>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
<html>
|
||||
<body>
|
||||
<h1>Hello ${message}</h1>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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"%>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Form Example - Add Customer</title>
|
||||
<style>
|
||||
.error {
|
||||
color: #ff0000;
|
||||
font-weight: bold;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h3>Welcome, Enter The Customer Details</h3>
|
||||
|
||||
<form:form method="POST" action="${pageContext.request.contextPath}/addCustomer" modelAttribute="customer">
|
||||
<table>
|
||||
<tr>
|
||||
<td><form:label path="customerId">Customer Id</form:label></td>
|
||||
<td><form:input path="customerId" /></td>
|
||||
<td><form:errors path="customerId" cssClass="error" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><form:label path="customerName">Customer Name</form:label></td>
|
||||
<td><form:input path="customerName" /></td>
|
||||
<td><form:errors path="customerName" cssClass="error" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><form:label path="customerContact">Customer Contact</form:label></td>
|
||||
<td><form:input path="customerContact"/></td>
|
||||
<td><form:errors path="customerContact" cssClass="error" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><form:label path="customerEmail">Customer Email</form:label></td>
|
||||
<td><form:input path="customerEmail" /></td>
|
||||
<td><form:errors path="customerEmail" cssClass="error" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input type="submit" value="Submit" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
</form:form>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,28 @@
|
||||
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
|
||||
<html>
|
||||
<head>
|
||||
<title>Spring MVC Form Handling</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h2>Submitted Customer Information</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Customer Id :</td>
|
||||
<td>${customerId}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Customer Name :</td>
|
||||
<td>${customerName}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Customer Contact :</td>
|
||||
<td>${customerContact}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Customer Email :</td>
|
||||
<td>${customerEmail}</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
<%@ page language="java" contentType="text/html; charset=UTF-8"
|
||||
pageEncoding="UTF-8"%>
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>PushBuilder demo</title>
|
||||
</head>
|
||||
<body>
|
||||
<span>PushBuilder demo</span>
|
||||
<br>
|
||||
<img src="<c:url value="/resources/logo.png"/>" alt="Logo"
|
||||
height="126" width="411">
|
||||
<br>
|
||||
<!-- Content -->
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,48 @@
|
||||
<%--
|
||||
Created by IntelliJ IDEA.
|
||||
User: Olga
|
||||
Date: 1/19/16
|
||||
Time: 3:53 PM
|
||||
To change this template use File | Settings | File Templates.
|
||||
--%>
|
||||
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
|
||||
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
|
||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
|
||||
<html>
|
||||
<head>
|
||||
<title>Home Page</title>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<div>
|
||||
<h4>Select any of the options below to send sample email:</h4>
|
||||
<form method="get" style="width: 200px;">
|
||||
<fieldset style="border: none; padding-left: 0px; padding-top: 0px">
|
||||
<table>
|
||||
<tr>
|
||||
<td>
|
||||
<input type="submit" formaction="mail/send" value="Send Simple Email">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<input type="submit" formaction="mail/sendTemplate" value="Send Email Using Text Template">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<input type="submit" formaction="mail/sendAttachment" value="Send Email With Attachment">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<input type="submit" formaction="mail/sendHtml" value="Send HTML Email">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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"%>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Form Example - Register an Employee</title>
|
||||
</head>
|
||||
<body>
|
||||
<h3>Welcome, Enter The Employee Details</h3>
|
||||
|
||||
<form:form method="POST" action="${pageContext.request.contextPath}/addEmployee" modelAttribute="employee">
|
||||
<table>
|
||||
<tr>
|
||||
<td><form:label path="name">Name</form:label></td>
|
||||
<td><form:input path="name" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><form:label path="id">Id</form:label></td>
|
||||
<td><form:input path="id" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><form:label path="contactNumber">Contact Number</form:label></td>
|
||||
<td><form:input path="contactNumber" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input type="submit" value="Submit" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
</form:form>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,24 @@
|
||||
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
|
||||
<html>
|
||||
<head>
|
||||
<title>Spring MVC Form Handling</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h2>Submitted Employee Information</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Name :</td>
|
||||
<td>${name}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>ID :</td>
|
||||
<td>${id}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Contact Number :</td>
|
||||
<td>${contactNumber}</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,20 @@
|
||||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>SpringMVCExample</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h3>Pleas enter the correct details</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<td><a href="employee">Retry</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -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" %>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Upload file</title>
|
||||
</head>
|
||||
<body>
|
||||
<c:url value="/uploadFile" var="uploadFileUrl" />
|
||||
<form method="post" enctype="multipart/form-data" action="${uploadFileUrl}">
|
||||
<input type="file" name="file"/>
|
||||
<input type="submit" value="Upload file"/>
|
||||
</form>
|
||||
<br />
|
||||
${message }
|
||||
<br /> <br />
|
||||
<form method="GET" action="${uploadFileUrl}" >
|
||||
<input type="submit" value="Reset" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,58 @@
|
||||
<%--
|
||||
Created by IntelliJ IDEA.
|
||||
User: Olga
|
||||
Date: 7/20/2016
|
||||
Time: 1:47 PM
|
||||
To change this template use File | Settings | File Templates.
|
||||
--%>
|
||||
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
|
||||
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
|
||||
<html>
|
||||
<head>
|
||||
<title>Send Email</title>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<h3>${headerText}</h3>
|
||||
<form:form method="POST" modelAttribute="mailObject" >
|
||||
<fieldset>
|
||||
<div style="float:left;">
|
||||
<table cellspacing="0" width="300">
|
||||
<tr>
|
||||
<th><label for="input_to">To</label></th>
|
||||
<td><form:input path="to" id="input_to" type="email"/>
|
||||
<small>Enter email address</small><br/>
|
||||
<form:errors path="to" cssStyle="color:red;font-size:small"/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="input_subject">Subject</label></th>
|
||||
<td><form:input path="subject" id="input_subject"/>
|
||||
<small>Enter the subject</small><br/>
|
||||
<form:errors path="subject" cssStyle="color:red;font-size:small"/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="input_text">${messageLabel}:</label></th>
|
||||
<td><form:textarea path="text"
|
||||
rows="5" cols="50"
|
||||
id="input_text"/>
|
||||
<form:errors path="text" cssStyle="color:red;font-size:small"/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th></th>
|
||||
<td>
|
||||
<input type="submit" value="Send">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
<div style="float:left; word-wrap: break-word; margin-left: 50px; width: 400px; color: grey">
|
||||
${additionalInfo}
|
||||
</div>
|
||||
</fieldset>
|
||||
</form:form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
<%--
|
||||
User: Benjamin CAURE
|
||||
Date: 4/14/2020
|
||||
--%>
|
||||
<%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" language="java" %>
|
||||
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
|
||||
<html>
|
||||
<head>
|
||||
<title>Send HTML Email</title>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<h3>Send Email Using Text Template</h3>
|
||||
<form:form method="POST" modelAttribute="mailObject" >
|
||||
<fieldset>
|
||||
<div style="width: 100%;max-width: 1280px">
|
||||
<table>
|
||||
<tr>
|
||||
<th><label for="input_to">Recipient email</label></th>
|
||||
<td><form:input path="to" id="input_to" type="email"/>
|
||||
<small>Enter email address</small><br/>
|
||||
<form:errors path="to" cssStyle="color:red;font-size:small"/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="input_recipient_name">Recipient name</label></th>
|
||||
<td><form:input path="recipientName" id="input_recipient_name"/>
|
||||
<small>Enter the recipient name</small><br/>
|
||||
<form:errors path="recipientName" cssStyle="color:red;font-size:small"/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="input_subject">Subject</label></th>
|
||||
<td><form:input path="subject" id="input_subject"/>
|
||||
<small>Enter the subject</small><br/>
|
||||
<form:errors path="subject" cssStyle="color:red;font-size:small"/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="input_text">Text</label></th>
|
||||
<td><form:textarea path="text"
|
||||
rows="5" cols="50"
|
||||
id="input_text"/>
|
||||
<form:errors path="text" cssStyle="color:red;font-size:small"/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="input_sender_name">Sender name</label></th>
|
||||
<td><form:input path="senderName" id="input_sender_name"/>
|
||||
<small>Enter the sender name</small><br/>
|
||||
<form:errors path="senderName" cssStyle="color:red;font-size:small"/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="input_template_engine">Template Engine</label></th>
|
||||
<td><form:select path="templateEngine" id="input_template_engine" items="${templateEngines}"/>
|
||||
<small>Select the template engine</small><br/>
|
||||
<form:errors path="templateEngine" cssStyle="color:red;font-size:small"/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th></th>
|
||||
<td>
|
||||
<input type="submit" value="Send">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form:form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Home</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>Welcome to Apache Tiles integration with Spring MVC</h2>
|
||||
</body>
|
||||
</html>
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Spring MVC</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>Spring MVC configured to work with Apache Tiles</h2>
|
||||
</body>
|
||||
</html>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<#import "/spring.ftl" as spring/>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="ISO-8859-1" />
|
||||
<title>User Registration</title>
|
||||
</head>
|
||||
<body>
|
||||
<form action="register" method="post">
|
||||
<@spring.bind path="user" />
|
||||
Email:<@spring.formInput "user.email"/> <br />
|
||||
Password:<@spring.formPasswordInput "user.password"/> <br />
|
||||
<input type="submit" value="Submit" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
yieldUnescaped '<!DOCTYPE html>'
|
||||
html(lang:'en') {
|
||||
head {
|
||||
meta('http-equiv':'"Content-Type" content="text/html; charset=utf-8"')
|
||||
title('User Registration')
|
||||
}
|
||||
body {
|
||||
form (id:'userForm', action:'register', method:'post') {
|
||||
label (for:'email', 'Email')
|
||||
input (name:'email', type:'text', value:user.email?:'')
|
||||
label (for:'password', 'Password')
|
||||
input (name:'password', type:'password', value:user.password?:'')
|
||||
div (class:'form-actions') {
|
||||
input (type:'submit', value:'Submit')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
doctype html
|
||||
html
|
||||
head
|
||||
title User Registration
|
||||
body
|
||||
form(action="register" method="post" )
|
||||
label(for="email") Email:
|
||||
input(type="text" name="email")
|
||||
label(for="password") Password:
|
||||
input(type="password" name="password")
|
||||
input(type="submit" value="Submit")
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="ISO-8859-1" />
|
||||
<title>User Registration</title>
|
||||
</head>
|
||||
<body>
|
||||
<form action="#" th:action="@{/register}" th:object="${user}" method="post">
|
||||
Email:<input type="text" th:field="*{email}" /> <br />
|
||||
Password:<input type="password" th:field="*{password}" /> <br />
|
||||
<input type="submit" value="Submit" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,18 @@
|
||||
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>User Registration</title>
|
||||
</head>
|
||||
<body>
|
||||
<form:form method="POST" modelAttribute="user" action="register">
|
||||
<form:label path="email">Email: </form:label>
|
||||
<form:input path="email" type="text"/>
|
||||
<br />
|
||||
<form:label path="password">Password: </form:label>
|
||||
<form:input path="password" type="password" />
|
||||
<br />
|
||||
<input type="submit" value="Submit" />
|
||||
</form:form>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.2 KiB |
@@ -0,0 +1,36 @@
|
||||
.flex-container {
|
||||
display: -webkit-flex;
|
||||
display: flex;
|
||||
-webkit-flex-flow: row wrap;
|
||||
flex-flow: row wrap;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.flex-container > * {
|
||||
padding: 15px;
|
||||
-webkit-flex: 1 100%;
|
||||
flex: 1 100%;
|
||||
}
|
||||
|
||||
.article {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
header {background: black;color:white;}
|
||||
footer {background: #aaa;color:white;}
|
||||
.nav {background:#eee;}
|
||||
|
||||
.nav ul {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.nav ul a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
@media all and (min-width: 768px) {
|
||||
.nav {text-align:left;-webkit-flex: 1 auto;flex:1 auto;-webkit-order:1;order:1;}
|
||||
.article {-webkit-flex:5 0px;flex:5 0px;-webkit-order:2;order:2;}
|
||||
footer {-webkit-order:3;order:3;}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
import com.baeldung.spring.configuration.ApplicationConfiguration;
|
||||
import com.baeldung.spring.configuration.EmailConfiguration;
|
||||
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes={ApplicationConfiguration.class, EmailConfiguration.class})
|
||||
@WebAppConfiguration
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.controller.push;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.baeldung.spring.configuration.PushConfiguration;
|
||||
|
||||
@SpringJUnitWebConfig(PushConfiguration.class)
|
||||
public class PushControllerIntegrationTest {
|
||||
@Autowired
|
||||
private WebApplicationContext webAppContext;
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDemoWithPushGETisPerformed_thenRetrievedStatusOk() throws Exception {
|
||||
mockMvc.perform(get("/demoWithPush"))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDemoWithoutPushGETisPerformed_thenRetrievedStatusOk() throws Exception {
|
||||
mockMvc.perform(get("/demoWithoutPush"))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.controller.rss;
|
||||
|
||||
import com.baeldung.spring.configuration.ApplicationConfiguration;
|
||||
import com.baeldung.spring.configuration.EmailConfiguration;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@SpringJUnitWebConfig(classes={ApplicationConfiguration.class, EmailConfiguration.class})
|
||||
public class ArticleRssIntegrationTest {
|
||||
public static final String APPLICATION_RSS_XML = "application/rss+xml";
|
||||
public static final String APPLICATION_RSS_JSON = "application/rss+json";
|
||||
public static final String APPLICATION_RSS_XML_CHARSET_UTF_8 = "application/rss+xml;charset=UTF-8";
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webAppContext;
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingXMLFeed_thenContentTypeIsOk() throws Exception {
|
||||
mockMvc.perform(get("/rss2").accept(APPLICATION_RSS_XML))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(APPLICATION_RSS_XML_CHARSET_UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingJSONFeed_thenContentTypeIsOk() throws Exception {
|
||||
mockMvc.perform(get("/rss2").accept(APPLICATION_RSS_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(APPLICATION_RSS_JSON));
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.spring.servlets;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import javax.servlet.ServletException;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class HelloServletIntegrationTest {
|
||||
@Test
|
||||
public void whenRequested_thenForwardToCorrectUrl() throws ServletException, IOException {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hello");
|
||||
request.addParameter("name", "Dennis");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HelloServlet servlet = new HelloServlet();
|
||||
|
||||
servlet.doGet(request, response);
|
||||
|
||||
assertEquals("/forwarded", response.getForwardedUrl());
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.spring.servlets;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import javax.servlet.ServletException;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class WelcomeServletIntegrationTest {
|
||||
@Test
|
||||
public void whenRequested_thenRedirectedToCorrectUrl() throws ServletException, IOException {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome");
|
||||
request.addParameter("name", "Dennis");
|
||||
WelcomeServlet servlet = new WelcomeServlet();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
servlet.doGet(request, response);
|
||||
|
||||
assertEquals("/redirected", response.getRedirectedUrl());
|
||||
assertEquals(302, response.getStatus());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
## Spring MVC Basics 3
|
||||
|
||||
This module contains articles about Spring MVC
|
||||
|
||||
## Relevant articles:
|
||||
- [How to Read HTTP Headers in Spring REST Controllers](https://www.baeldung.com/spring-rest-http-headers)
|
||||
- [A Custom Data Binder in Spring MVC](https://www.baeldung.com/spring-mvc-custom-data-binder)
|
||||
- [Validating Lists in a Spring Controller](https://www.baeldung.com/spring-validate-list-controller)
|
||||
- [Spring Validation Message Interpolation](https://www.baeldung.com/spring-validation-message-interpolation)
|
||||
- [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url)
|
||||
- [Using Enums as Request Parameters in Spring](https://www.baeldung.com/spring-enum-request-param)
|
||||
- [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter)
|
||||
- [Guide to Flash Attributes in a Spring Web Application](https://www.baeldung.com/spring-web-flash-attributes)
|
||||
- [Handling URL Encoded Form Data in Spring REST](https://www.baeldung.com/spring-url-encoded-form-data)
|
||||
- [Reading HttpServletRequest Multiple Times in Spring](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times)
|
||||
- More articles: [[<-- prev]](/spring-mvc-basics-2)[[more -->]](/spring-mvc-basics-4)
|
||||
@@ -0,0 +1,149 @@
|
||||
<?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-3</artifactId>
|
||||
<name>spring-mvc-basics-3</name>
|
||||
<packaging>war</packaging>
|
||||
<description>Demo project for Spring Boot</description>
|
||||
|
||||
<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>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-mail</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.persistence</groupId>
|
||||
<artifactId>javax.persistence-api</artifactId>
|
||||
<version>${jpa.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.subethamail</groupId>
|
||||
<artifactId>subethasmtp</artifactId>
|
||||
<version>${subethasmtp.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
<excludes>
|
||||
<exclude>**/conf.properties</exclude>
|
||||
</excludes>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>autoconfiguration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*IntTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/AutoconfigurationTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- The main class to start by executing java -jar -->
|
||||
<start-class>com.baeldung.boot.Application</start-class>
|
||||
<jquery.version>3.1.1</jquery.version>
|
||||
<bootstrap.version>3.3.7-1</bootstrap.version>
|
||||
<jpa.version>2.2</jpa.version>
|
||||
<guava.version>18.0</guava.version>
|
||||
<subethasmtp.version>3.1.7</subethasmtp.version>
|
||||
<httpclient.version>4.5.8</httpclient.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.boot;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
public static void main(String[] args) {
|
||||
applicationContext = SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.boot.config;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.boot.converter.GenericBigDecimalConverter;
|
||||
import com.baeldung.boot.converter.StringToAbstractEntityConverterFactory;
|
||||
import com.baeldung.boot.converter.StringToEmployeeConverter;
|
||||
import com.baeldung.boot.converter.StringToEnumConverter;
|
||||
import com.baeldung.boot.web.resolver.HeaderVersionArgumentResolver;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.format.FormatterRegistry;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
argumentResolvers.add(new HeaderVersionArgumentResolver());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addFormatters(FormatterRegistry registry) {
|
||||
registry.addConverter(new StringToEmployeeConverter());
|
||||
registry.addConverter(new StringToEnumConverter());
|
||||
registry.addConverterFactory(new StringToAbstractEntityConverterFactory());
|
||||
registry.addConverter(new GenericBigDecimalConverter());
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.boot.controller;
|
||||
|
||||
import com.baeldung.boot.domain.GenericEntity;
|
||||
import com.baeldung.boot.domain.Modes;
|
||||
import com.baeldung.boot.web.resolver.Version;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
public class GenericEntityController {
|
||||
private List<GenericEntity> entityList = new ArrayList<>();
|
||||
|
||||
{
|
||||
entityList.add(new GenericEntity(1l, "entity_1"));
|
||||
entityList.add(new GenericEntity(2l, "entity_2"));
|
||||
entityList.add(new GenericEntity(3l, "entity_3"));
|
||||
entityList.add(new GenericEntity(4l, "entity_4"));
|
||||
}
|
||||
|
||||
@GetMapping("/entity/all")
|
||||
public List<GenericEntity> findAll() {
|
||||
return entityList;
|
||||
}
|
||||
|
||||
@PostMapping("/entity")
|
||||
public GenericEntity addEntity(GenericEntity entity) {
|
||||
entityList.add(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findby/{id}")
|
||||
public GenericEntity findById(@PathVariable Long id) {
|
||||
return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbydate/{date}")
|
||||
public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) {
|
||||
return entityList.stream().findFirst().get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbymode/{mode}")
|
||||
public GenericEntity findByEnum(@PathVariable("mode") Modes mode) {
|
||||
return entityList.stream().findFirst().get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbyversion")
|
||||
public ResponseEntity findByVersion(@Version String version) {
|
||||
return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.core.convert.converter.GenericConverter;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Set;
|
||||
|
||||
public class GenericBigDecimalConverter implements GenericConverter {
|
||||
@Override
|
||||
public Set<ConvertiblePair> getConvertibleTypes() {
|
||||
|
||||
ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, BigDecimal.class), new ConvertiblePair(String.class, BigDecimal.class) };
|
||||
|
||||
return ImmutableSet.copyOf(pairs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
|
||||
if (sourceType.getType() == BigDecimal.class) {
|
||||
return source;
|
||||
}
|
||||
|
||||
if (sourceType.getType() == String.class) {
|
||||
String number = (String) source;
|
||||
return new BigDecimal(number);
|
||||
} else {
|
||||
Number number = (Number) source;
|
||||
BigDecimal converted = new BigDecimal(number.doubleValue());
|
||||
return converted.setScale(2, BigDecimal.ROUND_HALF_EVEN);
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import com.baeldung.boot.domain.AbstractEntity;
|
||||
import com.baeldung.boot.domain.Bar;
|
||||
import com.baeldung.boot.domain.Foo;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.core.convert.converter.ConverterFactory;
|
||||
|
||||
public class StringToAbstractEntityConverterFactory implements ConverterFactory<String, AbstractEntity>{
|
||||
|
||||
@Override
|
||||
public <T extends AbstractEntity> Converter<String, T> getConverter(Class<T> targetClass) {
|
||||
|
||||
return new StringToAbstractEntityConverter<>(targetClass);
|
||||
}
|
||||
|
||||
|
||||
private static class StringToAbstractEntityConverter<T extends AbstractEntity> implements Converter<String, T> {
|
||||
|
||||
private Class<T> targetClass;
|
||||
|
||||
public StringToAbstractEntityConverter(Class<T> targetClass) {
|
||||
this.targetClass = targetClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T convert(String source) {
|
||||
long id = Long.parseLong(source);
|
||||
if(this.targetClass == Foo.class) {
|
||||
return (T) new Foo(id);
|
||||
}
|
||||
else if(this.targetClass == Bar.class) {
|
||||
return (T) new Bar(id);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import com.baeldung.boot.domain.Employee;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
|
||||
public class StringToEmployeeConverter implements Converter<String, Employee> {
|
||||
|
||||
@Override
|
||||
public Employee convert(String from) {
|
||||
String[] data = from.split(",");
|
||||
return new Employee(Long.parseLong(data[0]), Double.parseDouble(data[1]));
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import com.baeldung.boot.domain.Modes;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
|
||||
public class StringToEnumConverter implements Converter<String, Modes> {
|
||||
|
||||
@Override
|
||||
public Modes convert(String from) {
|
||||
return Modes.valueOf(from);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
@Component
|
||||
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
|
||||
|
||||
@Override
|
||||
public LocalDateTime convert(final String source) {
|
||||
return LocalDateTime.parse(source, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.boot.converter.controller;
|
||||
|
||||
import com.baeldung.boot.domain.Bar;
|
||||
import com.baeldung.boot.domain.Foo;
|
||||
import com.baeldung.boot.domain.Modes;
|
||||
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;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/string-to-abstract")
|
||||
public class AbstractEntityController {
|
||||
|
||||
@GetMapping("/foo/{foo}")
|
||||
public ResponseEntity<Object> getStringToFoo(@PathVariable Foo foo) {
|
||||
return ResponseEntity.ok(foo);
|
||||
}
|
||||
|
||||
@GetMapping("/bar/{bar}")
|
||||
public ResponseEntity<Object> getStringToBar(@PathVariable Bar bar) {
|
||||
return ResponseEntity.ok(bar);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<Object> getStringToMode(@RequestParam("mode") Modes mode) {
|
||||
return ResponseEntity.ok(mode);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.boot.converter.controller;
|
||||
|
||||
import com.baeldung.boot.domain.Employee;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/string-to-employee")
|
||||
public class StringToEmployeeConverterController {
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<Object> getStringToEmployee(@RequestParam("employee") Employee employee) {
|
||||
return ResponseEntity.ok(employee);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
public abstract class AbstractEntity {
|
||||
|
||||
long id;
|
||||
public AbstractEntity(long id){
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
public class Bar extends AbstractEntity {
|
||||
|
||||
private int value;
|
||||
|
||||
public Bar(long id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
public Bar(long id, int value) {
|
||||
super(id);
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Bar [value=" + value + ", id=" + id + "]";
|
||||
}
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Employee {
|
||||
|
||||
@Id
|
||||
private long id;
|
||||
private double salary;
|
||||
|
||||
public Employee() {
|
||||
}
|
||||
|
||||
public Employee(long id, double salary) {
|
||||
this.id = id;
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public double getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(double salary) {
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
|
||||
public class Foo extends AbstractEntity {
|
||||
|
||||
private String name;
|
||||
|
||||
public Foo(long id) {
|
||||
super(id);
|
||||
name = randomAlphanumeric(4);
|
||||
}
|
||||
|
||||
public Foo(long id, String name) {
|
||||
super(id);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo [name=" + name + ", id=" + id + "]";
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class GenericEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
private String value;
|
||||
|
||||
public GenericEntity() {
|
||||
}
|
||||
|
||||
public GenericEntity(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public GenericEntity(Long id, String value) {
|
||||
this.id = id;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
public enum Modes {
|
||||
|
||||
ALPHA, BETA;
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.boot.repository;
|
||||
|
||||
import com.baeldung.boot.domain.GenericEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.boot.web.resolver;
|
||||
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.support.WebDataBinderFactory;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@Component
|
||||
public class HeaderVersionArgumentResolver implements HandlerMethodArgumentResolver {
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(final MethodParameter methodParameter) {
|
||||
return methodParameter.getParameterAnnotation(Version.class) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolveArgument(final MethodParameter methodParameter, final ModelAndViewContainer modelAndViewContainer, final NativeWebRequest nativeWebRequest, final WebDataBinderFactory webDataBinderFactory) throws Exception {
|
||||
HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
|
||||
|
||||
return request.getHeader("Version");
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.boot.web.resolver;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.PARAMETER)
|
||||
public @interface Version {
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletRequestWrapper;
|
||||
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
|
||||
|
||||
private byte[] cachedBody;
|
||||
|
||||
public CachedBodyHttpServletRequest(HttpServletRequest request) throws IOException {
|
||||
super(request);
|
||||
InputStream requestInputStream = request.getInputStream();
|
||||
this.cachedBody = StreamUtils.copyToByteArray(requestInputStream);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServletInputStream getInputStream() throws IOException {
|
||||
return new CachedBodyServletInputStream(this.cachedBody);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BufferedReader getReader() throws IOException {
|
||||
// Create a reader from cachedContent
|
||||
// and return it
|
||||
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.cachedBody);
|
||||
return new BufferedReader(new InputStreamReader(byteArrayInputStream));
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.servlet.ReadListener;
|
||||
import javax.servlet.ServletInputStream;
|
||||
|
||||
public class CachedBodyServletInputStream extends ServletInputStream {
|
||||
|
||||
private InputStream cachedBodyInputStream;
|
||||
|
||||
public CachedBodyServletInputStream(byte[] cachedBody) {
|
||||
this.cachedBodyInputStream = new ByteArrayInputStream(cachedBody);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFinished() {
|
||||
try {
|
||||
return cachedBodyInputStream.available() == 0;
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setReadListener(ReadListener readListener) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
return cachedBodyInputStream.read();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user