Java 23053 02 (#14432)
* JAVA-23053: renaming the module * JAVA-23053: correction made for More articles links in spring-thymeleaf
This commit is contained in:
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.thymeleaf;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.thymeleaf;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
|
||||
|
||||
@Configuration
|
||||
public class ThymeleafConfig {
|
||||
|
||||
@Bean
|
||||
public ClassLoaderTemplateResolver secondaryTemplateResolver() {
|
||||
ClassLoaderTemplateResolver secondaryTemplateResolver = new ClassLoaderTemplateResolver();
|
||||
secondaryTemplateResolver.setPrefix("templates-2/");
|
||||
secondaryTemplateResolver.setSuffix(".html");
|
||||
secondaryTemplateResolver.setTemplateMode(TemplateMode.HTML);
|
||||
secondaryTemplateResolver.setCharacterEncoding("UTF-8");
|
||||
secondaryTemplateResolver.setOrder(1);
|
||||
secondaryTemplateResolver.setCheckExistence(true);
|
||||
|
||||
return secondaryTemplateResolver;
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.thymeleaf.attribute;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class CheckedAttributeController {
|
||||
|
||||
@GetMapping("/checked")
|
||||
public String displayCheckboxForm(Model model) {
|
||||
Engine engine = new Engine(true);
|
||||
model.addAttribute("engine", engine);
|
||||
model.addAttribute("flag", true);
|
||||
return "attribute/index";
|
||||
}
|
||||
|
||||
private static class Engine {
|
||||
private Boolean active;
|
||||
|
||||
public Engine(Boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
public Boolean getActive() {
|
||||
return active;
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.thymeleaf.attributes;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
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.RequestMapping;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/attributes")
|
||||
public class AttributeController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AttributeController.class);
|
||||
|
||||
@GetMapping
|
||||
public String show(Model model) {
|
||||
model.addAttribute("title", "Baeldung");
|
||||
model.addAttribute("email", "default@example.com");
|
||||
return "attributes/index";
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String submit(String email) {
|
||||
logger.info("Email: {}", email);
|
||||
return "redirect:attributes";
|
||||
}
|
||||
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.thymeleaf.config;
|
||||
|
||||
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
|
||||
|
||||
public class InitSecurity extends AbstractSecurityWebApplicationInitializer {
|
||||
|
||||
public InitSecurity() {
|
||||
super(WebMVCSecurity.class);
|
||||
|
||||
}
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.thymeleaf.config;
|
||||
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
import javax.servlet.ServletRegistration.Dynamic;
|
||||
|
||||
/**
|
||||
* Java configuration file that is used for web application initialization
|
||||
*/
|
||||
public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
|
||||
public WebApp() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return new Class<?>[] { WebMVCConfig.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[] { "/" };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void customizeRegistration(final Dynamic registration) {
|
||||
super.customizeRegistration(registration);
|
||||
}
|
||||
|
||||
}
|
||||
-115
@@ -1,115 +0,0 @@
|
||||
package com.baeldung.thymeleaf.config;
|
||||
|
||||
import com.baeldung.thymeleaf.formatter.NameFormatter;
|
||||
import com.baeldung.thymeleaf.utils.ArrayUtil;
|
||||
import nz.net.ultraq.thymeleaf.LayoutDialect;
|
||||
import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Description;
|
||||
import org.springframework.context.support.ResourceBundleMessageSource;
|
||||
import org.springframework.format.FormatterRegistry;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
|
||||
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
|
||||
import org.thymeleaf.spring5.ISpringTemplateEngine;
|
||||
import org.thymeleaf.spring5.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
|
||||
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ITemplateResolver;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan({ "com.baeldung.thymeleaf" })
|
||||
/*
|
||||
Java configuration file that is used for Spring MVC and Thymeleaf
|
||||
configurations
|
||||
*/
|
||||
public class WebMVCConfig implements WebMvcConfigurer, ApplicationContextAware {
|
||||
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver htmlViewResolver() {
|
||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||
resolver.setTemplateEngine(templateEngine(htmlTemplateResolver()));
|
||||
resolver.setContentType("text/html");
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
resolver.setViewNames(ArrayUtil.array("*.html"));
|
||||
return resolver;
|
||||
}
|
||||
|
||||
private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
|
||||
SpringTemplateEngine engine = new SpringTemplateEngine();
|
||||
engine.addDialect(new LayoutDialect(new GroupingStrategy()));
|
||||
engine.addDialect(new Java8TimeDialect());
|
||||
engine.setTemplateResolver(templateResolver);
|
||||
engine.setTemplateEngineMessageSource(messageSource());
|
||||
return engine;
|
||||
}
|
||||
|
||||
private ITemplateResolver htmlTemplateResolver() {
|
||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||
resolver.setApplicationContext(applicationContext);
|
||||
resolver.setPrefix("/WEB-INF/views/");
|
||||
resolver.setCacheable(false);
|
||||
resolver.setTemplateMode(TemplateMode.HTML);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Description("Spring Message Resolver")
|
||||
public ResourceBundleMessageSource messageSource() {
|
||||
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
|
||||
messageSource.setBasename("messages");
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleResolver localeResolver() {
|
||||
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
|
||||
localeResolver.setDefaultLocale(new Locale("en"));
|
||||
return localeResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleChangeInterceptor localeChangeInterceptor() {
|
||||
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
|
||||
localeChangeInterceptor.setParamName("lang");
|
||||
return localeChangeInterceptor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(localeChangeInterceptor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**", "/css/**")
|
||||
.addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Description("Custom Conversion Service")
|
||||
public void addFormatters(FormatterRegistry registry) {
|
||||
registry.addFormatter(new NameFormatter());
|
||||
}
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.thymeleaf.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
|
||||
public class WebMVCSecurity {
|
||||
|
||||
@Bean
|
||||
public InMemoryUserDetailsManager userDetailsService() {
|
||||
UserDetails user = User.withUsername("user1")
|
||||
.password("{noop}user1Pass")
|
||||
.authorities("ROLE_USER")
|
||||
.build();
|
||||
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public WebSecurityCustomizer webSecurityCustomizer() {
|
||||
return (web) -> web.ignoring()
|
||||
.antMatchers("/resources/**");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.httpBasic();
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.thymeleaf.controller;
|
||||
|
||||
import com.baeldung.thymeleaf.model.Book;
|
||||
import com.baeldung.thymeleaf.service.BookService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
@Controller
|
||||
public class BookController {
|
||||
|
||||
@Autowired
|
||||
private BookService bookService;
|
||||
|
||||
@RequestMapping(value = "/listBooks", method = RequestMethod.GET)
|
||||
public String listBooks(Model model, @RequestParam("page") Optional<Integer> page, @RequestParam("size") Optional<Integer> size) {
|
||||
final int currentPage = page.orElse(1);
|
||||
final int pageSize = size.orElse(5);
|
||||
|
||||
Page<Book> bookPage = bookService.findPaginated(PageRequest.of(currentPage - 1, pageSize));
|
||||
|
||||
model.addAttribute("bookPage", bookPage);
|
||||
|
||||
int totalPages = bookPage.getTotalPages();
|
||||
if (totalPages > 0) {
|
||||
List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
model.addAttribute("pageNumbers", pageNumbers);
|
||||
}
|
||||
|
||||
return "listBooks.html";
|
||||
}
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.thymeleaf.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Handles requests for the application home page.
|
||||
*
|
||||
*/
|
||||
@Controller
|
||||
public class HomeController {
|
||||
|
||||
@RequestMapping(value = "/", method = RequestMethod.GET)
|
||||
public String getHome(Model model) {
|
||||
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.getDefault());
|
||||
model.addAttribute("serverTime", dateFormat.format(new Date()));
|
||||
return "home.html";
|
||||
}
|
||||
|
||||
}
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
package com.baeldung.thymeleaf.controller;
|
||||
|
||||
import com.baeldung.thymeleaf.model.Student;
|
||||
import com.baeldung.thymeleaf.utils.StudentUtils;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Handles requests for the student model.
|
||||
*
|
||||
*/
|
||||
@Controller
|
||||
public class StudentController {
|
||||
|
||||
@RequestMapping(value = "/saveStudent", method = RequestMethod.POST)
|
||||
public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) {
|
||||
if (!errors.hasErrors()) {
|
||||
// get mock objects
|
||||
List<Student> students = StudentUtils.buildStudents();
|
||||
// add current student
|
||||
students.add(student);
|
||||
model.addAttribute("students", students);
|
||||
}
|
||||
return ((errors.hasErrors()) ? "addStudent.html" : "listStudents.html");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/addStudent", method = RequestMethod.GET)
|
||||
public String addStudent(Model model) {
|
||||
model.addAttribute("student", new Student());
|
||||
return "addStudent.html";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/listStudents", method = RequestMethod.GET)
|
||||
public String listStudent(Model model) {
|
||||
|
||||
model.addAttribute("students", StudentUtils.buildStudents());
|
||||
|
||||
return "listStudents.html";
|
||||
}
|
||||
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.thymeleaf.controller;
|
||||
|
||||
import com.baeldung.thymeleaf.utils.TeacherUtils;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
@Controller
|
||||
public class TeacherController {
|
||||
|
||||
@RequestMapping(value = "/listTeachers", method = RequestMethod.GET)
|
||||
public String getInfo(Model model) {
|
||||
model.addAttribute("teachers", TeacherUtils.buildTeachers());
|
||||
|
||||
return "listTeachers.html";
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.thymeleaf.expression;
|
||||
|
||||
public class Dino {
|
||||
private int id;
|
||||
private String name;
|
||||
private String color;
|
||||
private String weight;
|
||||
|
||||
public Dino(int id, String name, String color, String weight) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.color = color;
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public Dino() {
|
||||
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public void setColor(String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public String getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public void setWeight(String weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.thymeleaf.expression;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Controller
|
||||
public class DinoController {
|
||||
|
||||
ArrayList<Dino> dinos = new ArrayList<Dino>();
|
||||
|
||||
@RequestMapping("/")
|
||||
public String dinoList(Model model) {
|
||||
Dino dinos = new Dino(1, "alpha", "red", "50kg");
|
||||
|
||||
model.addAttribute("dinos", new Dino());
|
||||
model.addAttribute("dinos", dinos);
|
||||
System.out.println(dinos);
|
||||
|
||||
return "templates-3/index";
|
||||
|
||||
}
|
||||
|
||||
@RequestMapping("/create")
|
||||
public String dinoCreate(Model model) {
|
||||
|
||||
model.addAttribute("dinos", new Dino());
|
||||
|
||||
return "templates-3/form";
|
||||
|
||||
}
|
||||
|
||||
@PostMapping("/dino")
|
||||
public String dinoSubmit(@ModelAttribute Dino dino, Model model) {
|
||||
|
||||
model.addAttribute("dino", dino);
|
||||
return "templates-3/result";
|
||||
}
|
||||
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.thymeleaf.formatter;
|
||||
|
||||
import org.springframework.format.Formatter;
|
||||
import org.thymeleaf.util.StringUtils;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
*
|
||||
* Name formatter class that implements the Spring Formatter interface.
|
||||
* Formats a name(String) and return the value with spaces replaced by commas.
|
||||
*
|
||||
*/
|
||||
public class NameFormatter implements Formatter<String> {
|
||||
|
||||
@Override
|
||||
public String print(String input, Locale locale) {
|
||||
return formatName(input, locale);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String parse(String input, Locale locale) throws ParseException {
|
||||
return formatName(input, locale);
|
||||
}
|
||||
|
||||
private String formatName(String input, Locale locale) {
|
||||
return StringUtils.replace(input, " ", ",");
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.thymeleaf.imageupload;
|
||||
|
||||
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.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
@Controller public class UploadController {
|
||||
|
||||
public static String UPLOAD_DIRECTORY = System.getProperty("user.dir") + "/uploads";
|
||||
|
||||
@GetMapping("/uploadimage") public String displayUploadForm() {
|
||||
return "imageupload/index";
|
||||
}
|
||||
|
||||
@PostMapping("/upload") public String uploadImage(Model model, @RequestParam("image") MultipartFile file) throws IOException {
|
||||
StringBuilder fileNames = new StringBuilder();
|
||||
Path fileNameAndPath = Paths.get(UPLOAD_DIRECTORY, file.getOriginalFilename());
|
||||
fileNames.append(file.getOriginalFilename());
|
||||
Files.write(fileNameAndPath, file.getBytes());
|
||||
model.addAttribute("msg", "Uploaded images: " + fileNames.toString());
|
||||
return "imageupload/index";
|
||||
}
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.thymeleaf.model;
|
||||
|
||||
public class Book {
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public Book(int id, String name) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
package com.baeldung.thymeleaf.model;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
*
|
||||
* Simple student POJO with few fields
|
||||
*
|
||||
*/
|
||||
public class Student implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = -8582553475226281591L;
|
||||
|
||||
@NotNull(message = "Student ID is required.")
|
||||
@Min(value = 1000, message = "Student ID must be at least 4 digits.")
|
||||
private Integer id;
|
||||
|
||||
@NotNull(message = "Student name is required.")
|
||||
private String name;
|
||||
|
||||
@NotNull(message = "Student gender is required.")
|
||||
private Character gender;
|
||||
|
||||
private Float percentage;
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Character getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
public void setGender(Character gender) {
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
public Float getPercentage() {
|
||||
return percentage;
|
||||
}
|
||||
|
||||
public void setPercentage(Float percentage) {
|
||||
this.percentage = percentage;
|
||||
}
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
package com.baeldung.thymeleaf.model;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Teacher implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 946941572942270450L;
|
||||
|
||||
@NotNull(message = "Teacher ID is required.")
|
||||
@Min(value = 1000, message = "Teacher ID must be at least 4 digits.")
|
||||
private Integer id;
|
||||
|
||||
@NotNull(message = "Teacher name is required.")
|
||||
private String name;
|
||||
|
||||
@NotNull(message = "Teacher gender is required.")
|
||||
private String gender;
|
||||
|
||||
private boolean isActive;
|
||||
|
||||
private List<String> courses = new ArrayList<String>();
|
||||
|
||||
private String additionalSkills;
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
public void setGender(String gender) {
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setActive(boolean isActive) {
|
||||
this.isActive = isActive;
|
||||
}
|
||||
|
||||
public List<String> getCourses() {
|
||||
return courses;
|
||||
}
|
||||
|
||||
public void setCourses(List<String> courses) {
|
||||
this.courses = courses;
|
||||
}
|
||||
|
||||
public String getAdditionalSkills() {
|
||||
return additionalSkills;
|
||||
}
|
||||
|
||||
public void setAdditionalSkills(String additionalSkills) {
|
||||
this.additionalSkills = additionalSkills;
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.thymeleaf.mvcdata;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.baeldung.thymeleaf.mvcdata.repository.EmailData;
|
||||
|
||||
@Configuration
|
||||
public class BeanConfig {
|
||||
@Bean
|
||||
public EmailData emailData() {
|
||||
return new EmailData();
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.thymeleaf.mvcdata;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import com.baeldung.thymeleaf.mvcdata.repository.EmailData;
|
||||
|
||||
@Controller
|
||||
public class EmailController {
|
||||
private EmailData emailData = new EmailData();
|
||||
private ServletContext servletContext;
|
||||
|
||||
public EmailController(ServletContext servletContext) {
|
||||
this.servletContext = servletContext;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/email/modelattributes")
|
||||
public String emailModel(Model model) {
|
||||
model.addAttribute("emaildata", emailData);
|
||||
return "mvcdata/email-model-attributes";
|
||||
}
|
||||
|
||||
@ModelAttribute("emailModelAttribute")
|
||||
EmailData emailModelAttribute() {
|
||||
return emailData;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/email/requestparameters")
|
||||
public String emailRequestParameters(
|
||||
@RequestParam(value = "emailsubject") String emailSubject,
|
||||
@RequestParam(value = "emailcontent") String emailContent,
|
||||
@RequestParam(value = "emailaddress") String emailAddress1,
|
||||
@RequestParam(value = "emailaddress") String emailAddress2,
|
||||
@RequestParam(value = "emaillocale") String emailLocale) {
|
||||
return "mvcdata/email-request-parameters";
|
||||
}
|
||||
|
||||
@GetMapping("/email/sessionattributes")
|
||||
public String emailSessionAttributes(HttpSession httpSession) {
|
||||
httpSession.setAttribute("emaildata", emailData);
|
||||
return "mvcdata/email-session-attributes";
|
||||
}
|
||||
|
||||
@GetMapping("/email/servletcontext")
|
||||
public String emailServletContext() {
|
||||
servletContext.setAttribute("emailsubject", emailData.getEmailSubject());
|
||||
servletContext.setAttribute("emailcontent", emailData.getEmailBody());
|
||||
servletContext.setAttribute("emailaddress", emailData.getEmailAddress1());
|
||||
servletContext.setAttribute("emaillocale", emailData.getEmailLocale());
|
||||
return "mvcdata/email-servlet-context";
|
||||
}
|
||||
|
||||
@GetMapping("/email/beandata")
|
||||
public String emailBeanData() {
|
||||
return "mvcdata/email-bean-data";
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.thymeleaf.mvcdata.repository;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class EmailData implements Serializable {
|
||||
private String emailSubject;
|
||||
private String emailBody;
|
||||
private String emailLocale;
|
||||
private String emailAddress1;
|
||||
private String emailAddress2;
|
||||
|
||||
public EmailData() {
|
||||
this.emailSubject = "You have received a new message";
|
||||
this.emailBody = "Good morning !";
|
||||
this.emailLocale = "en-US";
|
||||
this.emailAddress1 = "jhon.doe@example.com";
|
||||
this.emailAddress2 = "mark.jakob@example.com";
|
||||
}
|
||||
|
||||
public String getEmailSubject() {
|
||||
return this.emailSubject;
|
||||
}
|
||||
|
||||
public String getEmailBody() {
|
||||
return this.emailBody;
|
||||
}
|
||||
|
||||
public String getEmailLocale() {
|
||||
return this.emailLocale;
|
||||
}
|
||||
|
||||
public String getEmailAddress1() {
|
||||
return this.emailAddress1;
|
||||
}
|
||||
|
||||
public String getEmailAddress2() {
|
||||
return this.emailAddress2;
|
||||
}
|
||||
|
||||
public List<String> getEmailAddresses() {
|
||||
List<String> emailAddresses = new ArrayList<>();
|
||||
emailAddresses.add(getEmailAddress1());
|
||||
emailAddresses.add(getEmailAddress2());
|
||||
return emailAddresses;
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package com.baeldung.thymeleaf.service;
|
||||
|
||||
import com.baeldung.thymeleaf.model.Book;
|
||||
import com.baeldung.thymeleaf.utils.BookUtils;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class BookService {
|
||||
|
||||
final private List<Book> books = BookUtils.buildBooks();
|
||||
|
||||
public Page<Book> findPaginated(Pageable pageable) {
|
||||
int pageSize = pageable.getPageSize();
|
||||
int currentPage = pageable.getPageNumber();
|
||||
int startItem = currentPage * pageSize;
|
||||
List<Book> list;
|
||||
|
||||
if (books.size() < startItem) {
|
||||
list = Collections.emptyList();
|
||||
} else {
|
||||
int toIndex = Math.min(startItem + pageSize, books.size());
|
||||
list = books.subList(startItem, toIndex);
|
||||
}
|
||||
|
||||
Page<Book> bookPage = new PageImpl<Book>(list, PageRequest.of(currentPage, pageSize), books.size());
|
||||
|
||||
return bookPage;
|
||||
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.thymeleaf.templatedir;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class HelloController {
|
||||
|
||||
@GetMapping("/hello")
|
||||
public String sayHello() {
|
||||
return "hello";
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.thymeleaf.url;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
@Controller
|
||||
public class UrlController {
|
||||
@GetMapping("/search") public String test(Model model, @RequestParam("query") String query){
|
||||
return "url/index";
|
||||
}
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.thymeleaf.utils;
|
||||
|
||||
public class ArrayUtil {
|
||||
|
||||
public static String[] array(String... args) {
|
||||
return args;
|
||||
}
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
package com.baeldung.thymeleaf.utils;
|
||||
|
||||
import com.baeldung.thymeleaf.model.Book;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class BookUtils {
|
||||
|
||||
private static List<Book> books = new ArrayList<Book>();
|
||||
|
||||
private static final int NUM_BOOKS = 30;
|
||||
|
||||
private static final int MIN_BOOK_NUM = 1000;
|
||||
|
||||
public static List<Book> buildBooks() {
|
||||
if (books.isEmpty()) {
|
||||
IntStream.range(0, NUM_BOOKS).forEach(n -> {
|
||||
books.add(new Book(MIN_BOOK_NUM + n + 1, "Spring in Action"));
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
return books;
|
||||
}
|
||||
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.baeldung.thymeleaf.utils;
|
||||
|
||||
import com.baeldung.thymeleaf.model.Student;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class StudentUtils {
|
||||
|
||||
private static List<Student> students = new ArrayList<Student>();
|
||||
|
||||
public static List<Student> buildStudents() {
|
||||
if (students.isEmpty()) {
|
||||
Student student1 = new Student();
|
||||
student1.setId(1001);
|
||||
student1.setName("John Smith");
|
||||
student1.setGender('M');
|
||||
student1.setPercentage(Float.valueOf("80.45"));
|
||||
|
||||
students.add(student1);
|
||||
|
||||
Student student2 = new Student();
|
||||
student2.setId(1002);
|
||||
student2.setName("Jane Williams");
|
||||
student2.setGender('F');
|
||||
student2.setPercentage(Float.valueOf("60.25"));
|
||||
|
||||
students.add(student2);
|
||||
}
|
||||
|
||||
return students;
|
||||
}
|
||||
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
package com.baeldung.thymeleaf.utils;
|
||||
|
||||
import com.baeldung.thymeleaf.model.Teacher;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class TeacherUtils {
|
||||
|
||||
private static List<Teacher> teachers = new ArrayList<Teacher>();
|
||||
|
||||
public static List<Teacher> buildTeachers() {
|
||||
if (teachers.isEmpty()) {
|
||||
Teacher teacher1 = new Teacher();
|
||||
teacher1.setId(2001);
|
||||
teacher1.setName("Jane Doe");
|
||||
teacher1.setGender("F");
|
||||
teacher1.setActive(true);
|
||||
teacher1.getCourses().add("Mathematics");
|
||||
teacher1.getCourses().add("Physics");
|
||||
|
||||
teachers.add(teacher1);
|
||||
|
||||
Teacher teacher2 = new Teacher();
|
||||
teacher2.setId(2002);
|
||||
teacher2.setName("Lazy Dude");
|
||||
teacher2.setGender("M");
|
||||
teacher2.setActive(false);
|
||||
teacher2.setAdditionalSkills("emergency responder");
|
||||
|
||||
teachers.add(teacher2);
|
||||
|
||||
Teacher teacher3 = new Teacher();
|
||||
teacher3.setId(2002);
|
||||
teacher3.setName("Micheal Jordan");
|
||||
teacher3.setGender("M");
|
||||
teacher3.setActive(true);
|
||||
teacher3.getCourses().add("Sports");
|
||||
|
||||
teachers.add(teacher3);
|
||||
|
||||
}
|
||||
|
||||
return teachers;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
#spring.thymeleaf.prefix=classpath:/templates-2/
|
||||
spring.servlet.multipart.max-file-size = 5MB
|
||||
spring.servlet.multipart.max-request-size = 5MB
|
||||
@@ -1,19 +0,0 @@
|
||||
<?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>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,2 @@
|
||||
welcome.message=welcome to Dino world.
|
||||
dino.color=red is my favourite, mine is {0}
|
||||
@@ -1,13 +0,0 @@
|
||||
msg.id=ID
|
||||
msg.name=Name
|
||||
msg.gender=Gender
|
||||
msg.percent=Percentage
|
||||
welcome.message=Welcome Student !!!
|
||||
msg.AddStudent=Add Student
|
||||
msg.ListStudents=List Students
|
||||
msg.Home=Home
|
||||
msg.ListTeachers=List Teachers
|
||||
msg.ListBooks=List Books with paging
|
||||
msg.courses=Courses
|
||||
msg.skills=Skills
|
||||
msg.active=Active
|
||||
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Enums in Thymeleaf</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>Hello from 'templates/templates-2'</h2>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,20 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html xmlns:th="https://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Dino World</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<h2 th:text="#{welcome.message}"></h2>
|
||||
<h1>Form</h1>
|
||||
<form action="#" th:action="@{/dino}" th:object="${dinos}" method="post">
|
||||
<p>Id: <input type="text" th:field="*{id}" /></p>
|
||||
<p>Name: <input type="text" th:field="*{name}" /></p>
|
||||
<p>Color: <input type="text" th:field="*{color}" /></p>
|
||||
<p>Weight: <input type="text" th:field="*{weight}" /></p>
|
||||
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
|
||||
</form>
|
||||
|
||||
</body>
|
||||
<div th:replace="~{index :: footer}"></div>
|
||||
</html>
|
||||
@@ -0,0 +1,29 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html xmlns:th="https://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Dino World</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<h2 th:text="#{welcome.message}"></h2>
|
||||
<h2 th:text="#{dino.color('blue')}"></h2>
|
||||
|
||||
<div>
|
||||
<span>[[${dinos.id}]]/<span>
|
||||
<span>[[${dinos.name}]]/<span>
|
||||
<span>[[${dinos.weight}]]/<span>
|
||||
<span>[[${dinos.color}]]/<span>
|
||||
</div>
|
||||
<div th:object="${dinos}">
|
||||
<p th:text="*{id}">
|
||||
<p th:text="*{name}">
|
||||
<p th:text="*{weight}">
|
||||
<p th:text="*{color}">
|
||||
</div>
|
||||
<a href="/create">Submit Another Dino</a>
|
||||
</body>
|
||||
<div th:fragment="footer">
|
||||
<p> Copyright 2022</p>
|
||||
<hr />
|
||||
</div>
|
||||
</html>
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html xmlns:th="https://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Dino World</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<h2 th:text="#{welcome.message}"></h2>
|
||||
<h2 th:text="#{dino.color(${dino.color})}"></h2>
|
||||
<h1>Result</h1>
|
||||
<p th:text="'id: ' + ${dino.id}" />
|
||||
<p th:text="'content: ' + ${dino.name}" />
|
||||
<a th:href="@{/create}">Submit Another Dino</a>
|
||||
<a th:href="@{http://www.baeldung.com}"> Baeldung Home</a>
|
||||
</body>
|
||||
|
||||
|
||||
<div th:replace="~{index :: footer}"></div>
|
||||
</html>
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<title>Spring Boot Thymeleaf Application - Checkbox Checked Conditionally</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<form method="post">
|
||||
<label>
|
||||
<input type="checkbox" th:checked="${flag}"/> Flag activated
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" th:checked="${engine.getActive()}"/> Customer activated
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" th:checked="${flag ? false: true}"/> Flag deactivated
|
||||
</label>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Difference Between th:text and th:value in Thymeleaf</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h1 th:text="${title} ?: 'Default title'"/>
|
||||
|
||||
<form th:action="@{/attributes}" method="post">
|
||||
<label>Email:
|
||||
<input name="email" type="email" th:value="${email}">
|
||||
</label>
|
||||
<input type="submit" value="Submit"/>
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
|
||||
</head>
|
||||
<body>
|
||||
<section class="my-5">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-8 mx-auto">
|
||||
<h2>Upload Image Example</h2>
|
||||
<p th:text="${message}" th:if="${message ne null}" class="alert alert-primary"></p>
|
||||
<form method="post" th:action="@{/upload}" enctype="multipart/form-data">
|
||||
<div class="form-group">
|
||||
<input type="file" name="image" accept="image/*" class="form-control-file">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Upload image</button>
|
||||
</form>
|
||||
<span th:if="${msg != null}" th:text="${msg}"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</body>
|
||||
</html>
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<body>
|
||||
<h1>Subject</h1>
|
||||
<p th:text="${@emailData.emailSubject}">Subject</p>
|
||||
<h1>Content</h1>
|
||||
<p th:text="${@emailData.emailBody}">Body</p>
|
||||
<h1>Email address</h1>
|
||||
<p th:text="${@emailData.emailAddress1}">Email address</p>
|
||||
<h1>Language</h1>
|
||||
<p th:text="${@emailData.emailLocale}">Language</p>
|
||||
</body>
|
||||
</html>
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<body>
|
||||
<h1>Subject</h1>
|
||||
<p th:text="${emaildata.emailSubject}">Subject</p>
|
||||
<h1>Content</h1>
|
||||
<p th:text="${emaildata.emailBody}"></p>
|
||||
<h1>Email addresses</h1>
|
||||
<p th:each="emailAddress : ${emailModelAttribute.getEmailAddresses()}">
|
||||
<span th:text="${emailAddress}"></span>
|
||||
</p>
|
||||
<h1>Language</h1>
|
||||
<p th:text="${emaildata.emailLocale}"></p>
|
||||
</body>
|
||||
</html>
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<body>
|
||||
<h1>Subject</h1>
|
||||
<p th:text="${param.emailsubject}">Subject</p>
|
||||
<h1>Content</h1>
|
||||
<p th:text="${param.emailcontent}"></p>
|
||||
<h1>Email addresses</h1>
|
||||
<p th:each="emailaddress : ${param.emailaddress}">
|
||||
<span th:text="${emailaddress}"></span>
|
||||
</p>
|
||||
<h1>Email address 1</h1>
|
||||
<p th:text="${param.emailaddress[0]}"></p>
|
||||
<h1>Email address 2</h1>
|
||||
<p th:text="${param.emailaddress[1]}"></p>
|
||||
<h1>Language</h1>
|
||||
<p th:text="${param.emaillocale}"></p>
|
||||
</body>
|
||||
</html>
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<body>
|
||||
<h1>Subject</h1>
|
||||
<p th:text="${#servletContext.getAttribute('emailsubject')}"></p>
|
||||
<h1>Content</h1>
|
||||
<p th:text="${#servletContext.getAttribute('emailcontent')}"></p>
|
||||
<h1>Email address</h1>
|
||||
<p th:text="${#servletContext.getAttribute('emailaddress')}"></p>
|
||||
<h1>Language</h1>
|
||||
<p th:text="${#servletContext.getAttribute('emaillocale')}"></p>
|
||||
</body>
|
||||
</html>
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<body>
|
||||
<h1>Subject</h1>
|
||||
<p th:text="${session.emaildata.emailSubject}"></p>
|
||||
<h1>Content</h1>
|
||||
<p th:text="${session.emaildata.emailBody}"></p>
|
||||
<h1>Email address</h1>
|
||||
<p th:text="${session.emaildata.emailAddress1}"></p>
|
||||
<h1>Language</h1>
|
||||
<p th:text="${#session.getAttribute('emaillocale')}"></p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div th:if="${param.query != null}">
|
||||
<p th:text="${param.query }"></p>
|
||||
</div>
|
||||
<div th:if="${param.query != null}">
|
||||
<p th:text="${param.query[0]}" th:unless="${param.query == null}"></p>
|
||||
</div>
|
||||
<div th:if="${#request.getParameter('query') != null}">
|
||||
<p th:text="${#request.getParameter('query')}" th:unless="${#request.getParameter('query') == null}"></p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,45 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Add Student</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Add Student</h1>
|
||||
<form action="#" th:action="@{/saveStudent}" th:object="${student}"
|
||||
method="post">
|
||||
<ul>
|
||||
<li th:errors="*{id}" />
|
||||
<li th:errors="*{name}" />
|
||||
<li th:errors="*{gender}" />
|
||||
<li th:errors="*{percentage}" />
|
||||
</ul>
|
||||
<table border="1">
|
||||
<tr>
|
||||
<td><label th:text="#{msg.id}" /></td>
|
||||
<td><input type="number" th:field="*{id}" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><label th:text="#{msg.name}" /></td>
|
||||
<td><input type="text" th:field="*{name}" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><label th:text="#{msg.gender}" /></td>
|
||||
<td><select th:field="*{gender}">
|
||||
<option th:value="'M'" th:text="Male"></option>
|
||||
<option th:value="'F'" th:text="Female"></option>
|
||||
</select></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><label th:text="#{msg.percent}" /></td>
|
||||
<td><select id="percentage" name="percentage">
|
||||
<option th:each="i : ${#numbers.sequence(0, 100)}" th:value="${i}" th:text="${i}" th:selected="${i==75}"></option>
|
||||
</select></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input type="submit" value="Submit" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,12 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
|
||||
</head>
|
||||
<body>
|
||||
<form action="http://localhost:8080/spring-thymeleaf/saveStudent" method="post">
|
||||
<input type="hidden" name="payload" value="CSRF attack!"/>
|
||||
<input type="submit" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,29 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org"
|
||||
th:with="lang=${#locale.language}" th:lang="${lang}">
|
||||
<head>
|
||||
<title>Home</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>
|
||||
<span th:text="#{welcome.message}" />
|
||||
</h1>
|
||||
<p>
|
||||
Current time is <span th:text="${serverTime}" />
|
||||
</p>
|
||||
<table>
|
||||
<tr>
|
||||
<td><a th:href="@{/addStudent}" th:text="#{msg.AddStudent}" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a th:href="@{/listStudents}" th:text="#{msg.ListStudents}" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a th:href="@{/listTeachers}" th:text="#{msg.ListTeachers}" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a th:href="@{/listBooks}" th:text="#{msg.ListBooks}" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,58 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<style>
|
||||
.pagination {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.pagination a {
|
||||
color: black;
|
||||
float: left;
|
||||
padding: 5px 5px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.pagination a.active {
|
||||
background-color: gray;
|
||||
color: white;
|
||||
border-radius: 2px;
|
||||
}
|
||||
</style>
|
||||
<head>
|
||||
<title>Book List</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Book List</h1>
|
||||
<table border="1">
|
||||
<thead>
|
||||
<tr>
|
||||
<th th:text="#{msg.id}" />
|
||||
<th th:text="#{msg.name}" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="book, iStat : ${bookPage.content}"
|
||||
th:style="${iStat.odd}? 'font-weight: bold;'"
|
||||
th:alt-title="${iStat.even}? 'even' : 'odd'">
|
||||
<td th:text="${book.id}" />
|
||||
<td th:text="${book.name}" />
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div th:if="${bookPage.totalPages > 0}" class="pagination"
|
||||
th:each="pageNumber : ${pageNumbers}">
|
||||
<a th:href="@{/listBooks(size=${bookPage.size}, page=${pageNumber})}"
|
||||
th:text=${pageNumber}
|
||||
th:class="${pageNumber==bookPage.number + 1} ? active"></a>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p>
|
||||
<a th:href="@{/}" th:text="#{msg.Home}"></a>
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Student List</title>
|
||||
</head>
|
||||
<script type="text/javascript"
|
||||
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
$.ajax({
|
||||
url : "/spring-thymeleaf/js",
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<body>
|
||||
<h1>Student List</h1>
|
||||
<table border="1">
|
||||
<thead>
|
||||
<tr>
|
||||
<th th:text="#{msg.id}" />
|
||||
<th th:text="#{msg.name}" />
|
||||
<th th:text="#{msg.gender}" />
|
||||
<th th:text="#{msg.percent}" />
|
||||
<th th:text="index" />
|
||||
<th th:text="count" />
|
||||
<th th:text="first" />
|
||||
<th th:text="last" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="student, iStat : ${students}" th:style="${iStat.odd}? 'font-weight: bold;'" th:alt-title="${iStat.even}? 'even' : 'odd'">
|
||||
<td th:text="${student.id}" />
|
||||
<td th:text="${student.name}" />
|
||||
<td th:switch="${student.gender}"><span th:case="'M'"
|
||||
th:text="Male" /> <span th:case="'F'" th:text="Female" /></td>
|
||||
<td th:text="${#conversions.convert(student.percentage, 'Integer')}" />
|
||||
<td th:text="${iStat.index}" />
|
||||
<td th:text="${iStat.count}" />
|
||||
<td th:text="${iStat.first}" />
|
||||
<td th:text="${iStat.last}" />
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div>
|
||||
<p>
|
||||
<a th:href="@{/}" th:text="#{msg.Home}" />
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Teacher List</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Teacher List</h1>
|
||||
<table border="1">
|
||||
<thead>
|
||||
<tr>
|
||||
<th th:text="#{msg.id}" />
|
||||
<th th:text="#{msg.name}" />
|
||||
<th th:text="#{msg.gender}" />
|
||||
<th th:text="#{msg.active}" />
|
||||
<th th:text="#{msg.courses}" />
|
||||
<th th:text="#{msg.skills}" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="teacher: ${teachers}">
|
||||
<td th:text="${teacher.id}" />
|
||||
<td th:text="${{teacher.name}}" />
|
||||
|
||||
<td><span th:if="${teacher.gender == 'F'}">Female</span> <span
|
||||
th:unless="${teacher.gender == 'F'}">Male</span></td>
|
||||
|
||||
<td th:text="${teacher.active} ? 'ACTIVE' : 'RETIRED'" />
|
||||
|
||||
<td th:switch="${#lists.size(teacher.courses)}"><span
|
||||
th:case="'0'">NO COURSES YET!</span> <span th:case="'1'"
|
||||
th:text="${teacher.courses[0]}"></span>
|
||||
<div th:case="*">
|
||||
<div th:each="course: ${teacher.courses}" th:text="${course}"></div>
|
||||
</div></td>
|
||||
|
||||
<td th:text="*{teacher.additionalSkills}?: 'UNKNOWN'" />
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div>
|
||||
<p>
|
||||
<a th:href="@{/}" th:text="#{msg.Home}" />
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.thymeleaf;
|
||||
|
||||
import com.baeldung.thymeleaf.config.WebApp;
|
||||
import com.baeldung.thymeleaf.config.WebMVCConfig;
|
||||
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;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class })
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package com.baeldung.thymeleaf.controller;
|
||||
|
||||
import com.baeldung.thymeleaf.config.WebApp;
|
||||
import com.baeldung.thymeleaf.config.WebMVCConfig;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.RequestPostProcessor;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class})
|
||||
public class ControllerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
WebApplicationContext wac;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private Filter springSecurityFilterChain;
|
||||
|
||||
private RequestPostProcessor testUser() {
|
||||
return user("user1").password("user1Pass").roles("USER");
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTeachers() throws Exception {
|
||||
mockMvc.perform(get("/listTeachers").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("listTeachers.html"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addStudentWithoutCSRF() throws Exception {
|
||||
mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser())).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addStudentWithCSRF() throws Exception {
|
||||
mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk());
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.thymeleaf.mvcdata;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
|
||||
import com.baeldung.thymeleaf.mvcdata.repository.EmailData;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc(printOnlyOnFailure = false)
|
||||
public class EmailControllerUnitTest {
|
||||
|
||||
EmailData emailData = new EmailData();
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void whenCallModelAttributes_thenReturnEmailData() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/email/modelattributes"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("You have received a new message")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallRequestParameters_thenReturnEmailData() throws Exception {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("emailsubject", emailData.getEmailSubject());
|
||||
params.add("emailcontent", emailData.getEmailBody());
|
||||
params.add("emailaddress", emailData.getEmailAddress1());
|
||||
params.add("emailaddress", emailData.getEmailAddress2());
|
||||
params.add("emaillocale", emailData.getEmailLocale());
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/email/requestparameters")
|
||||
.params(params))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("en-US")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallSessionAttributes_thenReturnEmailData() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/email/sessionattributes"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Good morning !")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallServletContext_thenReturnEmailData() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/email/servletcontext"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("jhon.doe@example.com")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallBeanData_thenReturnEmailData() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/email/beandata"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("jhon.doe@example.com")));
|
||||
}
|
||||
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
package com.baeldung.thymeleaf.security.csrf;
|
||||
|
||||
import com.baeldung.thymeleaf.config.InitSecurity;
|
||||
import com.baeldung.thymeleaf.config.WebApp;
|
||||
import com.baeldung.thymeleaf.config.WebMVCConfig;
|
||||
import com.baeldung.thymeleaf.config.WebMVCSecurity;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockHttpSession;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.RequestPostProcessor;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class })
|
||||
public class CsrfEnabledIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
WebApplicationContext wac;
|
||||
@Autowired
|
||||
MockHttpSession session;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private Filter springSecurityFilterChain;
|
||||
|
||||
private RequestPostProcessor testUser() {
|
||||
return user("user1").password("user1Pass").roles("USER");
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addStudentWithoutCSRF() throws Exception {
|
||||
mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser())).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addStudentWithCSRF() throws Exception {
|
||||
mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration scan="true" scanPeriod="15 seconds" debug="false">
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user