JAVA-3519: Moved spring-mvc-basics-2 inside spring-web-modules

This commit is contained in:
sampadawagde
2020-12-22 16:24:43 +05:30
parent ee417ff070
commit 8de5b196e8
76 changed files with 1 additions and 1 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,42 @@
package com.baeldung.spring.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.baeldung.spring.domain.Customer;
import com.baeldung.spring.validator.CustomerValidator;
@Controller
public class CustomerController {
@Autowired
CustomerValidator validator;
@RequestMapping(value = "/customer", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("customerHome", "customer", new Customer());
}
@PostMapping("/addCustomer")
public String submit(@Valid @ModelAttribute("customer") final Customer customer, final BindingResult result, final ModelMap model) {
validator.validate(customer, result);
if (result.hasErrors()) {
return "customerHome";
}
model.addAttribute("customerId", customer.getCustomerId());
model.addAttribute("customerName", customer.getCustomerName());
model.addAttribute("customerContact", customer.getCustomerContact());
model.addAttribute("customerEmail", customer.getCustomerEmail());
return "customerView";
}
}

View File

@@ -0,0 +1,47 @@
package com.baeldung.spring.controller;
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.baeldung.spring.domain.Employee;
@Controller
public class EmployeeController {
Map<Long, Employee> employeeMap = new HashMap<>();
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
return employeeMap.get(Id);
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("contactNumber", employee.getContactNumber());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
}

View File

@@ -0,0 +1,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;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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 + '\'' +
'}';
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,45 @@
package com.baeldung.spring.domain;
public class Customer {
private String customerId;
private String customerName;
private String customerContact;
private String customerEmail;
public Customer() {
super();
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerContact() {
return customerContact;
}
public void setCustomerContact(String customerContact) {
this.customerContact = customerContact;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.spring.domain;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Employee {
private long id;
@NotNull
@Size(min = 5)
private String name;
@NotNull
@Size(min = 7)
private String contactNumber;
public Employee() {
super();
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(final String contactNumber) {
this.contactNumber = contactNumber;
}
}

View File

@@ -0,0 +1,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;
}
}

View File

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

View File

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

View File

@@ -0,0 +1,19 @@
package com.baeldung.spring.interceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class FileUploadExceptionAdvice {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView handleMaxSizeException(MaxUploadSizeExceededException exc, HttpServletRequest request, HttpServletResponse response){
ModelAndView modelAndView = new ModelAndView("file");
modelAndView.getModel().put("message", "File too large!");
return modelAndView;
}
}

View File

@@ -0,0 +1,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;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,28 @@
package com.baeldung.spring.validator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.baeldung.spring.domain.Customer;
@Component
public class CustomerValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Customer.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerId", "error.customerId", "Customer Id is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerName", "error.customerName", "Customer Name is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerContact", "error.customerNumber", "Customer Contact is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerEmail", "error.customerEmail", "Customer Email is required.");
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,6 @@
<html>
<body>
<h1>Hello ${message}</h1>
</body>
</html>

View File

@@ -0,0 +1,5 @@
<html>
<body>
<h1>Hello ${message}</h1>
</body>
</html>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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')
}
}
}
}

View File

@@ -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")

View File

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

View File

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

View File

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

View File

@@ -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() {
}
}

View File

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

View File

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

View File

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

View File

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