repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java | spring-web-modules/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java | package com.baeldung.thymeleaf;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class ApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java | spring-web-modules/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java | package com.baeldung.thymeleaf.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc(printOnlyOnFailure = false)
public class LayoutDialectControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetDates() throws Exception {
mockMvc.perform(get("/layout")).andExpect(status().isOk()).andExpect(view().name("content.html"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java | spring-web-modules/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java | package com.baeldung.thymeleaf.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc(printOnlyOnFailure = false)
public class ExpressionUtilityObjectsControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetObjects() throws Exception {
mockMvc.perform(get("/objects")).andExpect(status().isOk()).andExpect(view().name("objects.html"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/currencies/CurrenciesControllerIntegrationTest.java | spring-web-modules/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/currencies/CurrenciesControllerIntegrationTest.java | package com.baeldung.thymeleaf.currencies;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc(printOnlyOnFailure = false)
public class CurrenciesControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void whenCallCurrencyWithSpanishLocale_ThenReturnProperCurrency() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/currency")
.header("Accept-Language", "es-ES")
.param("amount", "10032.5"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("10.032,50")));
}
@Test
public void whenCallCurrencyWithUSALocale_ThenReturnProperCurrency() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/currency")
.header("Accept-Language", "en-US")
.param("amount", "10032.5"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("$10,032.50")));
}
@Test
public void whenCallCurrencyWithRomanianLocaleWithArrays_ThenReturnLocaleCurrencies() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/currency")
.header("Accept-Language", "en-GB")
.param("amountList", "10", "20", "30"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("£10.00, £20.00, £30.00")));
}
@Test
public void whenCallCurrencyWithUSALocaleWithoutDecimal_ThenReturnCurrencyWithoutTrailingZeros() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/currency")
.header("Accept-Language", "en-US")
.param("amount", "10032"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("$10,032")));
}
@Test
public void whenCallCurrencyWithUSALocale_ThenReturnReplacedDecimalPoint() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/currency")
.header("Accept-Language", "en-US")
.param("amount", "1.5"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("1,5")));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java | 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);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java | 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;
@Controller
public class LayoutDialectController {
@RequestMapping(value = "/layout", method = RequestMethod.GET)
public String getNewPage(Model model) {
return "content.html";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java | package com.baeldung.thymeleaf.controller;
import org.springframework.security.core.context.SecurityContextHolder;
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 com.baeldung.thymeleaf.utils.StudentUtils;
@Controller
public class InliningController {
@RequestMapping(value = "/html", method = RequestMethod.GET)
public String getExampleHTML(Model model) {
model.addAttribute("title", "Baeldung");
model.addAttribute("description", "<strong>Thymeleaf</strong> tutorial");
return "inliningExample.html";
}
@RequestMapping(value = "/js", method = RequestMethod.GET)
public String getExampleJS(Model model) {
model.addAttribute("students", StudentUtils.buildStudents());
return "studentCheck.js";
}
@RequestMapping(value = "/plain", method = RequestMethod.GET)
public String getExamplePlain(Model model) {
model.addAttribute("username", SecurityContextHolder.getContext().getAuthentication().getName());
model.addAttribute("students", StudentUtils.buildStudents());
return "studentsList.txt";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java | package com.baeldung.thymeleaf.controller;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
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 to test expression utility objects: dates,
*
*/
@Controller
public class ExpressionUtilityObjectsController {
@RequestMapping(value = "/objects", method = RequestMethod.GET)
public String getDates(Model model) {
model.addAttribute("date", new Date());
model.addAttribute("calendar", Calendar.getInstance());
model.addAttribute("num", Math.random() * 10);
model.addAttribute("string", "new text");
model.addAttribute("emptyString", "");
model.addAttribute("nullString", null);
model.addAttribute("array", new int[] { 1, 3, 4, 5 });
model.addAttribute("set", new HashSet<Integer>(Arrays.asList(1, 3, 8)));
return "objects.html";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/currencies/CurrenciesController.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/currencies/CurrenciesController.java | package com.baeldung.thymeleaf.currencies;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class CurrenciesController {
@GetMapping(value = "/currency")
public String exchange(
@RequestParam(value = "amount", required = false) String amount,
@RequestParam(value = "amountList", required = false) List amountList,
Locale locale) {
return "currencies/currencies";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/model/Student.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/model/Student.java | package com.baeldung.thymeleaf.model;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
/**
*
* 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;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthDate;
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 Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Float getPercentage() {
return percentage;
}
public void setPercentage(Float percentage) {
this.percentage = percentage;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/articles/ArticlesController.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/articles/ArticlesController.java | package com.baeldung.thymeleaf.articles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Arrays;
import java.util.List;
@Controller
@RequestMapping("/api/articles")
public class ArticlesController {
@GetMapping
public String allArticles(Model model) {
model.addAttribute("articles", fetchArticles());
return "articles/articles-list";
}
private List<Article> fetchArticles() {
return Arrays.asList(
new Article(
"Introduction to Using Thymeleaf in Spring",
"https://www.baeldung.com/thymeleaf-in-spring-mvc"
),
new Article(
"Spring Boot CRUD Application with Thymeleaf",
"https://www.baeldung.com/spring-boot-crud-thymeleaf"
),
new Article(
"Spring MVC Data and Thymeleaf",
"https://www.baeldung.com/spring-mvc-thymeleaf-data"
)
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/articles/Article.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/articles/Article.java | package com.baeldung.thymeleaf.articles;
public class Article {
private String name;
private String url;
public Article(String name, String url) {
this.name = name;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java | package com.baeldung.thymeleaf.utils;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.thymeleaf.model.Student;
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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/conditionalclasses/ConditionalClassesController.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/conditionalclasses/ConditionalClassesController.java | package com.baeldung.thymeleaf.conditionalclasses;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ConditionalClassesController {
@GetMapping("/conditional-classes")
public String getConditionalClassesPage( Model model) {
model.addAttribute("condition", true);
return "conditionalclasses/conditionalclasses";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java | package com.baeldung.thymeleaf.blog;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Random;
@Controller
public class BlogController {
@GetMapping("/blog/new")
public String newBlogPost(Model model) {
// Set a random ID so we can see it in the HTML form
BlogDTO blog = new BlogDTO();
blog.setBlogId(Math.abs(new Random().nextLong() % 1000000));
model.addAttribute("blog", blog);
return "blog/blog-new";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java | spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java | package com.baeldung.thymeleaf.blog;
import java.util.Date;
public class BlogDTO {
private long blogId;
private String title;
private String body;
private String author;
private String category;
private Date publishedDate;
public long getBlogId() {
return blogId;
}
public void setBlogId(long blogId) {
this.blogId = blogId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java | spring-web-modules/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java | package com.baeldung.springsoap;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ClassUtils;
import org.springframework.ws.client.core.WebServiceTemplate;
import com.baeldung.springsoap.client.gen.GetCountryRequest;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationIntegrationTest {
private Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
@LocalServerPort
private int port = 0;
@Before
public void init() throws Exception {
marshaller.setPackagesToScan(ClassUtils.getPackageName(GetCountryRequest.class));
marshaller.afterPropertiesSet();
}
@Test
public void whenSendRequest_thenResponseIsNotNull() {
WebServiceTemplate ws = new WebServiceTemplate(marshaller);
GetCountryRequest request = new GetCountryRequest();
request.setName("Spain");
Object response = ws.marshalSendAndReceive("http://localhost:" + port + "/ws", request);
assertThat(response).isNotNull();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java | spring-web-modules/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java | package com.baeldung.springsoap.client;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.springsoap.client.gen.Currency;
import com.baeldung.springsoap.client.gen.GetCountryResponse;
//Ensure that the server - com.baeldung.springsoap.Application - is running before executing this test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CountryClientConfig.class, loader = AnnotationConfigContextLoader.class)
public class CountryClientLiveTest {
@Autowired
CountryClient client;
@Test
public void givenCountryService_whenCountryPoland_thenCapitalIsWarsaw() {
GetCountryResponse response = client.getCountry("Poland");
assertEquals("Warsaw", response.getCountry()
.getCapital());
}
@Test
public void givenCountryService_whenCountrySpain_thenCurrencyEUR() {
GetCountryResponse response = client.getCountry("Spain");
assertEquals(Currency.EUR, response.getCountry()
.getCurrency());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java | spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java | package com.baeldung.springsoap;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
@Bean
public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean<>(servlet, "/ws/*");
}
@Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CountriesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://www.baeldung.com/springsoap/gen");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
@Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java | spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java | package com.baeldung.springsoap;
import java.util.HashMap;
import java.util.Map;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import com.baeldung.springsoap.client.gen.Country;
import com.baeldung.springsoap.client.gen.Currency;
@Component
public class CountryRepository {
private static final Map<String, Country> countries = new HashMap<>();
@PostConstruct
public void initData() {
Country spain = new Country();
spain.setName("Spain");
spain.setCapital("Madrid");
spain.setCurrency(Currency.EUR);
spain.setPopulation(46704314);
countries.put(spain.getName(), spain);
Country poland = new Country();
poland.setName("Poland");
poland.setCapital("Warsaw");
poland.setCurrency(Currency.PLN);
poland.setPopulation(38186860);
countries.put(poland.getName(), poland);
Country uk = new Country();
uk.setName("United Kingdom");
uk.setCapital("London");
uk.setCurrency(Currency.GBP);
uk.setPopulation(63705000);
countries.put(uk.getName(), uk);
}
public Country findCountry(String name) {
Assert.notNull(name, "The country's name must not be null");
return countries.get(name);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java | spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java | package com.baeldung.springsoap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import com.baeldung.springsoap.client.gen.GetCountryRequest;
import com.baeldung.springsoap.client.gen.GetCountryResponse;
@Endpoint
public class CountryEndpoint {
private static final String NAMESPACE_URI = "http://www.baeldung.com/springsoap/gen";
private CountryRepository countryRepository;
@Autowired
public CountryEndpoint(CountryRepository countryRepository) {
this.countryRepository = countryRepository;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest")
@ResponsePayload
public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) {
GetCountryResponse response = new GetCountryResponse();
response.setCountry(countryRepository.findCountry(request.getName()));
return response;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/Application.java | spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/Application.java | package com.baeldung.springsoap;
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);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java | spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java | package com.baeldung.springsoap.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import com.baeldung.springsoap.client.gen.GetCountryRequest;
import com.baeldung.springsoap.client.gen.GetCountryResponse;
public class CountryClient extends WebServiceGatewaySupport {
private static final Logger logger = LoggerFactory.getLogger(CountryClient.class);
public GetCountryResponse getCountry(String country) {
GetCountryRequest request = new GetCountryRequest();
request.setName(country);
logger.info("Requesting information for " + country);
GetCountryResponse response = (GetCountryResponse) getWebServiceTemplate().marshalSendAndReceive(request);
return response;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java | spring-web-modules/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java | package com.baeldung.springsoap.client;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
@Configuration
public class CountryClientConfig {
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.baeldung.springsoap.client.gen");
return marshaller;
}
@Bean
public CountryClient countryClient(Jaxb2Marshaller marshaller) {
CountryClient client = new CountryClient();
client.setDefaultUri("http://localhost:8080/ws");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java | spring-web-modules/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java | package com.baeldung;
import com.baeldung.spring.SecSecurityConfig;
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)
@ContextConfiguration(classes = { SecSecurityConfig.class})
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-static-resources/src/test/java/com/baeldung/loadresourceasstring/LoadResourceAsStringIntegrationTest.java | spring-web-modules/spring-static-resources/src/test/java/com/baeldung/loadresourceasstring/LoadResourceAsStringIntegrationTest.java | package com.baeldung.loadresourceasstring;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = LoadResourceConfig.class)
public class LoadResourceAsStringIntegrationTest {
private static final String EXPECTED_RESOURCE_VALUE = "This is a resource text file. This file will be loaded as a " + "resource and use its contents as a string.";
@Value("#{T(com.baeldung.loadresourceasstring.ResourceReader).readFileToString('classpath:resource.txt')}")
private String resourceStringUsingSpel;
@Autowired
@Qualifier("resourceString")
private String resourceString;
@Autowired
private ResourceLoader resourceLoader;
@Test
public void givenUsingResourceLoadAndFileCopyUtils_whenConvertingAResourceToAString_thenCorrect() {
Resource resource = resourceLoader.getResource("classpath:resource.txt");
assertEquals(EXPECTED_RESOURCE_VALUE, ResourceReader.asString(resource));
}
@Test
public void givenUsingResourceStringBean_whenConvertingAResourceToAString_thenCorrect() {
assertEquals(EXPECTED_RESOURCE_VALUE, resourceString);
}
@Test
public void givenUsingSpel_whenConvertingAResourceToAString_thenCorrect() {
assertEquals(EXPECTED_RESOURCE_VALUE, resourceStringUsingSpel);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/LoadResourceConfig.java | spring-web-modules/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/LoadResourceConfig.java | package com.baeldung.loadresourceasstring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LoadResourceConfig {
@Bean
public String resourceString() {
return ResourceReader.readFileToString("resource.txt");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/ResourceReader.java | spring-web-modules/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/ResourceReader.java | package com.baeldung.loadresourceasstring;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.FileCopyUtils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UncheckedIOException;
import static java.nio.charset.StandardCharsets.UTF_8;
public class ResourceReader {
public static String readFileToString(String path) {
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource(path);
return asString(resource);
}
public static String asString(Resource resource) {
try (Reader reader = new InputStreamReader(resource.getInputStream(), UTF_8)) {
return FileCopyUtils.copyToString(reader);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java | spring-web-modules/spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java | package com.baeldung.security;
import java.io.IOException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response, authentication);
HttpSession session = request.getSession(false);
if (session != null) {
session.setMaxInactiveInterval(30);
}
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
return "/home.html";
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java | spring-web-modules/spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java | package com.baeldung.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
public class SecSecurityConfig {
public SecSecurityConfig() {
super();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java | spring-web-modules/spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java | package com.baeldung.spring;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.env.Environment;
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.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.resource.EncodedResourceResolver;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@ComponentScan(basePackages = { "com.baeldung.web.controller", "com.baeldung.persistence.service", "com.baeldung.persistence.dao" })
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Autowired
Environment env;
public MvcConfig() {
super();
}
// API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/login.html");
registry.addViewController("/home.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// For examples using Spring 4.1.0
if ((env.getProperty("resource.handler.conf")).equals("4.1.0")) {
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(3600).resourceChain(true).addResolver(new EncodedResourceResolver()).addResolver(new PathResourceResolver());
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/", "classpath:/other-resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver());
registry.addResourceHandler("/files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver());
registry.addResourceHandler("/other-files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new EncodedResourceResolver());
}
// For examples using Spring 4.0.7
else if ((env.getProperty("resource.handler.conf")).equals("4.0.7")) {
registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/", "classpath:/other-resources/");
registry.addResourceHandler("/files/**").addResourceLocations("file:/Users/Elena/");
}
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
registry.addInterceptor(localeChangeInterceptor);
}
@Bean
public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
ResourceUrlEncodingFilter filter = new ResourceUrlEncodingFilter();
return filter;
}
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH);
return cookieLocaleResolver;
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(0);
return messageSource;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java | spring-web-modules/spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java | package com.baeldung.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@ComponentScan(basePackages = { "com.baeldung.persistence.service", "com.baeldung.persistence.dao" })
@Import({ MvcConfig.class, SecSecurityConfig.class })
@PropertySource("classpath:application.properties")
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java | spring-web-modules/spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java | package com.baeldung.web.controller;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
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.context.request.WebRequest;
@Controller
public class HomeController {
@Autowired
Environment env;
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String showHome(WebRequest request, Model model, Locale locale) throws IOException {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/largefile/LargeFileDownloadIntegrationTest.java | spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/largefile/LargeFileDownloadIntegrationTest.java | package com.baeldung.largefile;
import java.io.File;
import java.io.FileOutputStream;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
public class LargeFileDownloadIntegrationTest {
static String FILE_URL = "https://s3.amazonaws.com/baeldung.com/Do+JSON+with+Jackson.pdf?__s=vatuzcrazsqopnn7finb";
RestTemplate restTemplate;
@Before
public void setUp() {
restTemplate = new RestTemplate();
}
@Test
public void givenResumableUrl_whenUrlCalledByHeadOption_thenExpectHeadersAvailable() {
HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
Assertions
.assertThat(headers.get("Accept-Ranges"))
.contains("bytes");
Assertions
.assertThat(headers.getContentLength())
.isGreaterThan(0);
}
@Test
public void givenResumableUrl_whenDownloadCompletely_thenExpectCorrectFileSize() {
HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
long contentLength = headers.getContentLength();
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, null, clientHttpResponse -> {
File ret = File.createTempFile("download", "tmp");
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
return ret;
});
Assert.assertNotNull(file);
Assertions
.assertThat(file.length())
.isEqualTo(contentLength);
}
@Test
public void givenResumableUrl_whenDownloadRange_thenExpectFileSizeEqualOrLessThanRange() {
int range = 10;
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest
.getHeaders()
.set("Range", String.format("bytes=0-%d", range - 1)), clientHttpResponse -> {
File ret = File.createTempFile("download", "tmp");
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
return ret;
});
Assert.assertNotNull(file);
Assertions
.assertThat(file.length())
.isLessThanOrEqualTo(range);
}
@Test
public void givenResumableUrl_whenPauseDownloadAndResume_thenExpectCorrectFileSize() {
int range = 10;
HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
long contentLength = headers.getContentLength();
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest
.getHeaders()
.set("Range", String.format("bytes=0-%d", range - 1)), clientHttpResponse -> {
File ret = File.createTempFile("download", "tmp");
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
return ret;
});
Assert.assertNotNull(file);
Assertions
.assertThat(file.length())
.isLessThanOrEqualTo(range);
restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest
.getHeaders()
.set("Range", String.format("bytes=%d-%d", file.length(), contentLength)), clientHttpResponse -> {
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(file, true));
return file;
});
Assertions
.assertThat(file.length())
.isEqualTo(contentLength);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/encoding/service/HttpBinServiceLiveTest.java | spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/encoding/service/HttpBinServiceLiveTest.java | package com.baeldung.encoding.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.fasterxml.jackson.core.JsonProcessingException;
@SpringBootTest
class HttpBinServiceLiveTest {
@Autowired
private HttpBinService httpBinService;
@Test
void givenWithoutPlusSign_whenGet_thenSameValueReturned() throws JsonProcessingException {
String parameterWithoutPlusSign = "springboot";
String responseWithoutPlusSign = httpBinService.get(parameterWithoutPlusSign);
assertEquals(parameterWithoutPlusSign, responseWithoutPlusSign);
}
@Test
void givenWithPlusSign_whenGet_thenSameValueReturned() throws JsonProcessingException {
String parameterWithPlusSign = "spring+boot";
String responseWithPlusSign = httpBinService.get(parameterWithPlusSign);
assertEquals(parameterWithPlusSign, responseWithPlusSign);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/proxy/RequestFactoryLiveTest.java | spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/proxy/RequestFactoryLiveTest.java | package com.baeldung.resttemplate.proxy;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* This class is used to test a request using {@link RestTemplate} with {@link Proxy}
* using a {@link SimpleClientHttpRequestFactory} as configuration.
* <br />
* <br />
*
* Before running the test we should change the <code>PROXY_SERVER_HOST</code>
* and <code>PROXY_SERVER_PORT</code> constants in our class to match our preferred proxy configuration.
*/
public class RequestFactoryLiveTest {
private static final String PROXY_SERVER_HOST = "127.0.0.1";
private static final int PROXY_SERVER_PORT = 8080;
RestTemplate restTemplate;
@Before
public void setUp() {
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(PROXY_SERVER_HOST, PROXY_SERVER_PORT));
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setProxy(proxy);
restTemplate = new RestTemplate(requestFactory);
}
@Test
public void givenRestTemplate_whenRequestedWithProxy_thenResponseBodyIsOk() {
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://httpbin.org/get", String.class);
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/proxy/RestTemplateCustomizerLiveTest.java | spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/proxy/RestTemplateCustomizerLiveTest.java | package com.baeldung.resttemplate.proxy;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.net.Proxy;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.apache.hc.core5.http.HttpHost;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* This class is used to test a request using {@link RestTemplate} with {@link Proxy}
* using a {@link RestTemplateCustomizer} as configuration.
* <br />
* <br />
*
* Before running the test we should change the <code>PROXY_SERVER_HOST</code>
* and <code>PROXY_SERVER_PORT</code> constants in our class to match our preferred proxy configuration.
*/
public class RestTemplateCustomizerLiveTest {
private static final String PROXY_SERVER_HOST = "127.0.0.1";
private static final int PROXY_SERVER_PORT = 8080;
RestTemplate restTemplate;
@Before
public void setUp() {
restTemplate = new RestTemplateBuilder(new ProxyCustomizer()).build();
}
@Test
public void givenRestTemplate_whenRequestedWithProxy_thenResponseBodyIsOk() {
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://httpbin.org/get", String.class);
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
}
private static class ProxyCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
HttpHost proxy = new HttpHost(PROXY_SERVER_HOST, PROXY_SERVER_PORT);
HttpClient httpClient = HttpClientBuilder.create()
.setRoutePlanner(new DefaultProxyRoutePlanner(proxy))
.build();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/methods/RestTemplateMethodsUnitTest.java | spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/methods/RestTemplateMethodsUnitTest.java | package com.baeldung.resttemplate.methods;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.response.MockRestResponseCreators;
import org.springframework.web.client.RestTemplate;
/**
* Unit tests for different ways to send POST with RestTemplate.
*/
public class RestTemplateMethodsUnitTest
{
private final RestTemplate restTemplate = new RestTemplate();
private final String URL = "https://localhost:8080";
private MockRestServiceServer mockServer;
@BeforeEach
public void setup() {
mockServer = MockRestServiceServer.createServer(restTemplate);
}
/**
* Test that postForEntity sends a POST to the desired URL.
*/
@Test
public void testPostForEntity() {
mockServer.expect(requestTo(URL))
.andExpect(method(HttpMethod.POST))
.andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK)
.contentType(MediaType.TEXT_PLAIN)
.body("Ok"));
restTemplate.postForEntity(
URL,
"Test Body",
String.class);
mockServer.verify();
}
/**
* Test that exchange with POST method sends a POST to the desired URL.
*/
@Test
public void testPostExchange() {
mockServer.expect(requestTo(URL))
.andExpect(method(HttpMethod.POST))
.andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK)
.contentType(MediaType.TEXT_PLAIN)
.body("Ok"));
restTemplate.exchange(
URL,
HttpMethod.POST,
new HttpEntity<>("Test Body"),
String.class);
mockServer.verify();
}
@Test
public void testPostExecute() {
mockServer.expect(requestTo(URL))
.andExpect(method(HttpMethod.POST))
.andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK)
.contentType(MediaType.TEXT_PLAIN)
.body("Ok"));
restTemplate.execute(
URL,
HttpMethod.POST,
restTemplate.httpEntityCallback("Test body"),
restTemplate.responseEntityExtractor(String.class));
mockServer.verify();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/json/consumer/service/UserConsumerServiceImplUnitTest.java | spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/json/consumer/service/UserConsumerServiceImplUnitTest.java | package com.baeldung.resttemplate.json.consumer.service;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
@SpringBootTest
public class UserConsumerServiceImplUnitTest {
private static String USER_JSON = "[{\"id\":1,\"name\":\"user1\",\"addressList\":[{\"addressLine1\":\"address1_addressLine1\",\"addressLine2\":\"address1_addressLine2\",\"town\":\"address1_town\",\"postCode\":\"user1_address1_postCode\"}," +
"{\"addressLine1\":\"address2_addressLine1\",\"addressLine2\":\"address2_addressLine2\",\"town\":\"address2_town\",\"postCode\":\"user1_address2_postCode\"}]}," +
"{\"id\":2,\"name\":\"user2\",\"addressList\":[{\"addressLine1\":\"address1_addressLine1\",\"addressLine2\":\"address1_addressLine2\",\"town\":\"address1_town\",\"postCode\":\"user2_address1_postCode\"}]}]";
private MockRestServiceServer mockServer;
private final RestTemplate restTemplate = new RestTemplate();
private final UserConsumerService tested = new UserConsumerServiceImpl(restTemplate);
@Before
public void init() {
mockServer = MockRestServiceServer.createServer(restTemplate);
}
@Test
public void whenProcessUserDataAsObjects_thenOK() {
String url = "http://localhost:8080/users";
List<String> expected = Arrays.asList("user1", "user2");
mockServer.expect(ExpectedCount.once(),
requestTo(url))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(USER_JSON));
List<String> actual = tested.processUserDataFromObjectArray();
mockServer.verify();
assertThat(actual).containsExactly(expected.get(0), expected.get(1));
}
@Test
public void whenProcessUserDataAsArray_thenOK() {
String url = "http://localhost:8080/users";
List<String> expected = Arrays.asList("user1", "user2");
mockServer.expect(ExpectedCount.once(),
requestTo(url))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(USER_JSON));
List<String> actual = tested.processUserDataFromUserArray();
mockServer.verify();
assertThat(actual).containsExactly(expected.get(0), expected.get(1));
}
@Test
public void whenProcessUserDataAsList_thenOK() {
String url = "http://localhost:8080/users";
List<String> expected = Arrays.asList("user1", "user2");
mockServer.expect(ExpectedCount.once(),
requestTo(url))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(USER_JSON));
List<String> actual = tested.processUserDataFromUserList();
mockServer.verify();
assertThat(actual).containsExactly(expected.get(0), expected.get(1));
}
@Test
public void whenProcessNestedUserDataFromArray_thenOK() {
String url = "http://localhost:8080/users";
List<String> expected = Arrays.asList("user1_address1_postCode", "user1_address2_postCode", "user2_address1_postCode");
mockServer.expect(ExpectedCount.once(),
requestTo(url))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(USER_JSON));
List<String> actual = tested.processNestedUserDataFromUserArray();
mockServer.verify();
assertThat(actual).containsExactly(expected.get(0), expected.get(1), expected.get(2));
}
@Test
public void whenProcessNestedUserDataFromList_thenOK() {
String url = "http://localhost:8080/users";
List<String> expected = Arrays.asList("user1_address1_postCode", "user1_address2_postCode", "user2_address1_postCode");
mockServer.expect(ExpectedCount.once(),
requestTo(url))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(USER_JSON));
List<String> actual = tested.processNestedUserDataFromUserList();
mockServer.verify();
assertThat(actual).containsExactly(expected.get(0), expected.get(1), expected.get(2));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplateexception/RestTemplateExceptionLiveTest.java | spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplateexception/RestTemplateExceptionLiveTest.java | package com.baeldung.resttemplateexception;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.baeldung.resttemplateexception.model.Product;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { RestTemplate.class, RestTemplateExceptionApplication.class })
public class RestTemplateExceptionLiveTest {
@Autowired
RestTemplate restTemplate;
@Test(expected = IllegalArgumentException.class)
public void givenGetUrl_whenJsonIsPassed_thenThrowException() {
String url = "http://localhost:8080/spring-rest/api/get?criterion={\"prop\":\"name\",\"value\":\"ASUS VivoBook\"}";
Product product = restTemplate.getForObject(url, Product.class);
}
@Test
public void givenGetUrl_whenJsonIsPassed_thenGetProduct() {
String criterion = "{\"prop\":\"name\",\"value\":\"ASUS VivoBook\"}";
String url = "http://localhost:8080/spring-rest/api/get?criterion={criterion}";
Product product = restTemplate.getForObject(url, Product.class, criterion);
assertEquals(product.getPrice(), 650, 0);
}
@Test
public void givenGetUrl_whenJsonIsPassed_thenReturnProduct() {
String criterion = "{\"prop\":\"name\",\"value\":\"Acer Aspire 5\"}";
String url = "http://localhost:8080/spring-rest/api/get";
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url).queryParam("criterion", criterion);
Product product = restTemplate.getForObject(builder.build().toUri(), Product.class);
assertEquals(product.getId(), 1, 0);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/encoding/UriEncodingInterceptor.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/encoding/UriEncodingInterceptor.java | package com.baeldung.encoding;
import java.io.IOException;
import java.net.URI;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.web.util.UriComponentsBuilder;
public class UriEncodingInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpRequest encodedRequest = new HttpRequestWrapper(request) {
@Override
public URI getURI() {
URI uri = super.getURI();
String escapedQuery = uri.getRawQuery().replace("+", "%2B");
return UriComponentsBuilder.fromUri(uri)
.replaceQuery(escapedQuery)
.build(true).toUri();
}
};
return execution.execute(encodedRequest, body);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/encoding/Application.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/encoding/Application.java | package com.baeldung.encoding;
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);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/encoding/service/HttpBinService.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/encoding/service/HttpBinService.java | package com.baeldung.encoding.service;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class HttpBinService {
private final RestTemplate restTemplate;
public HttpBinService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String get(String parameter) throws JsonProcessingException {
String url = "http://httpbin.org/get?parameter={parameter}";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, parameter);
Map<String, Object> mapping = new ObjectMapper().readValue(response.getBody(), HashMap.class);
Map<String, String> args = (Map<String, String>) mapping.get("args");
return args.get("parameter");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/encoding/config/RestTemplateConfig.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/encoding/config/RestTemplateConfig.java | package com.baeldung.encoding.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
DefaultUriBuilderFactory defaultUriBuilderFactory = new DefaultUriBuilderFactory();
defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);
restTemplate.setUriTemplateHandler(defaultUriBuilderFactory);
return restTemplate;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/encoding/config/RestTemplateWithInterceptorsConfig.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/encoding/config/RestTemplateWithInterceptorsConfig.java | package com.baeldung.encoding.config;
import java.util.Collections;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import com.baeldung.encoding.UriEncodingInterceptor;
@Configuration
public class RestTemplateWithInterceptorsConfig {
@Qualifier("restTemplateWithInterceptors")
@Bean
public RestTemplate restTemplateWithInterceptors() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(new UriEncodingInterceptor()));
return restTemplate;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/json/model/Address.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/json/model/Address.java | package com.baeldung.resttemplate.json.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Address {
private final String addressLine1;
private final String addressLine2;
private final String town;
private final String postCode;
@JsonCreator
public Address(
@JsonProperty("addressLine1") String addressLine1,
@JsonProperty("addressLine2") String addressLine2,
@JsonProperty("town") String town,
@JsonProperty("postCode") String postCode) {
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.town = town;
this.postCode = postCode;
}
public String getPostCode() {
return postCode;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/json/model/User.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/json/model/User.java | package com.baeldung.resttemplate.json.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
private final int id;
private final String name;
private final List<Address> addressList;
@JsonCreator
public User(
@JsonProperty("id") int id,
@JsonProperty("name") String name,
@JsonProperty("addressList") List<Address> addressList) {
this.id = id;
this.name = name;
this.addressList = addressList;
}
public String getName() {
return name;
}
public List<Address> getAddressList() { return addressList; }
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/json/methods/RestTemplateMethodsApplication.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/json/methods/RestTemplateMethodsApplication.java | package com.baeldung.resttemplate.json.methods;
import java.io.IOException;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
/**
* Examples of making the same call with RestTemplate
* using postForEntity(), exchange(), and execute().
*/
@SpringBootApplication
public class RestTemplateMethodsApplication {
private final static RestTemplate restTemplate = new RestTemplate();
public static void main(String[] args) {
}
private static void postForEntity() {
Book book = new Book(
"Cruising Along with Java",
"Venkat Subramaniam",
2023);
ResponseEntity<Book> response = restTemplate.postForEntity(
"https://api.bookstore.com",
book,
Book.class);
}
private static void exchange() {
Book book = new Book(
"Effective Java",
"Joshua Bloch",
2001);
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("username", "password");
ResponseEntity<Book> response = restTemplate.exchange(
"https://api.bookstore.com",
HttpMethod.POST,
new HttpEntity<>(book, headers),
Book.class);
}
private static void execute() {
ResponseEntity<Book> response = restTemplate.execute(
"https://api.bookstore.com",
HttpMethod.POST,
new RequestCallback() {
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
// Create or decorate the request object as needed
}
},
new ResponseExtractor<ResponseEntity<Book>>() {
@Override
public ResponseEntity<Book> extractData(ClientHttpResponse response) throws IOException {
// extract required data from response
return null;
}
}
);
// Could also use some factory methods in RestTemplate for
// the request callback and/or response extractor
Book book = new Book(
"Reactive Spring",
"Josh Long",
2020);
response = restTemplate.execute(
"https://api.bookstore.com",
HttpMethod.POST,
restTemplate.httpEntityCallback(book),
restTemplate.responseEntityExtractor(Book.class)
);
}
private static class Book {
String title;
String author;
int yearPublished;
public Book(String title, String author, int yearPublished) {
this.title = title;
this.author = author;
this.yearPublished = yearPublished;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/json/consumer/service/UserConsumerServiceImpl.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/json/consumer/service/UserConsumerServiceImpl.java | package com.baeldung.resttemplate.json.consumer.service;
import com.baeldung.resttemplate.json.model.Address;
import com.baeldung.resttemplate.json.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class UserConsumerServiceImpl implements UserConsumerService {
private static final String BASE_URL = "http://localhost:8080/users";
private final RestTemplate restTemplate;
private static final ObjectMapper mapper = new ObjectMapper();
public UserConsumerServiceImpl(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public List<String> processUserDataFromObjectArray() {
ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity(BASE_URL, Object[].class);
Object[] objects = responseEntity.getBody();
return Arrays.stream(objects)
.map(object -> mapper.convertValue(object, User.class))
.map(User::getName)
.collect(Collectors.toList());
}
@Override
public List<String> processUserDataFromUserArray() {
ResponseEntity<User[]> responseEntity = restTemplate.getForEntity(BASE_URL, User[].class);
User[] userArray = responseEntity.getBody();
return Arrays.stream(userArray)
.map(User::getName)
.collect(Collectors.toList());
}
@Override
public List<String> processUserDataFromUserList() {
ResponseEntity<List<User>> responseEntity =
restTemplate.exchange(
BASE_URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<User>>() {}
);
List<User> users = responseEntity.getBody();
return users.stream()
.map(User::getName)
.collect(Collectors.toList());
}
@Override
public List<String> processNestedUserDataFromUserArray() {
ResponseEntity<User[]> responseEntity = restTemplate.getForEntity(BASE_URL, User[].class);
User[] userArray = responseEntity.getBody();
//we can get more info if we need :
MediaType contentType = responseEntity.getHeaders().getContentType();
HttpStatusCode statusCode = responseEntity.getStatusCode();
return Arrays.stream(userArray)
.flatMap(user -> user.getAddressList().stream())
.map(Address::getPostCode)
.collect(Collectors.toList());
}
@Override
public List<String> processNestedUserDataFromUserList() {
ResponseEntity<List<User>> responseEntity =
restTemplate.exchange(
BASE_URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<User>>() {}
);
List<User> userList = responseEntity.getBody();
return userList.stream()
.flatMap(user -> user.getAddressList().stream())
.map(Address::getPostCode)
.collect(Collectors.toList());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/json/consumer/service/UserConsumerService.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/json/consumer/service/UserConsumerService.java | package com.baeldung.resttemplate.json.consumer.service;
import java.util.List;
public interface UserConsumerService {
List<String> processUserDataFromObjectArray();
List<String> processUserDataFromUserArray();
List<String> processUserDataFromUserList();
List<String> processNestedUserDataFromUserArray();
List<String> processNestedUserDataFromUserList();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/RestTemplateExceptionApplication.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/RestTemplateExceptionApplication.java | package com.baeldung.resttemplateexception;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestTemplateExceptionApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateExceptionApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/controller/ProductApi.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/controller/ProductApi.java | package com.baeldung.resttemplateexception.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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.RestController;
import com.baeldung.resttemplateexception.model.Criterion;
import com.baeldung.resttemplateexception.model.Product;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@RestController
@RequestMapping("/api")
public class ProductApi {
private List<Product> productList = new ArrayList<>(Arrays.asList(new Product(1, "Acer Aspire 5", 437), new Product(2, "ASUS VivoBook", 650), new Product(3, "Lenovo Legion", 990)));
@GetMapping("/get")
public Product get(@RequestParam String criterion) throws JsonMappingException, JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Criterion crt = objectMapper.readValue(criterion, Criterion.class);
if (crt.getProp().equals("name"))
return findByName(crt.getValue());
// Search by other properties (id,price)
return null;
}
private Product findByName(String name) {
for (Product product : this.productList) {
if (product.getName().equals(name)) {
return product;
}
}
return null;
}
// Other methods
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Product.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Product.java | package com.baeldung.resttemplateexception.model;
public class Product {
private int id;
private String name;
private double price;
public Product() {
}
public Product(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Criterion.java | spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Criterion.java | package com.baeldung.resttemplateexception.model;
public class Criterion {
private String prop;
private String value;
public Criterion() {
}
public String getProp() {
return prop;
}
public void setProp(String prop) {
this.prop = prop;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/test/java/com/baeldung/SpringContextTest.java | spring-web-modules/spring-mvc-forms-jsp/src/test/java/com/baeldung/SpringContextTest.java | package com.baeldung;
import com.baeldung.springmvcforms.configuration.ApplicationConfiguration;
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)
@ContextConfiguration(classes = ApplicationConfiguration.class)
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/dbaccess/SQLConnection.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/dbaccess/SQLConnection.java | package com.baeldung.jstl.dbaccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class SQLConnection {
private static String userName = "root";
private static String password = "";
private static final Logger LOGGER = LoggerFactory.getLogger(SQLConnection.class.getName());
public static Connection getConnection() throws Exception {
LOGGER.error("connecting...");
Class.forName("com.mysql.cj.jdbc.Driver");
LOGGER.error("class checked...");
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", userName);
connectionProps.put("password", password);
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=false",
connectionProps);
LOGGER.info("Connected to database");
return conn;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/bundles/CustomMessage_en.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/bundles/CustomMessage_en.java | package com.baeldung.jstl.bundles;
import java.util.ListResourceBundle;
public class CustomMessage_en extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"verb.go", "go"},
{"verb.come", "come"},
{"verb.sit", "sit"},
{"verb.stand", "stand"}
};
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/bundles/CustomMessage_fr_FR.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/bundles/CustomMessage_fr_FR.java | package com.baeldung.jstl.bundles;
import java.util.ListResourceBundle;
public class CustomMessage_fr_FR extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"verb.go", "aller"},
{"verb.come", "venir"},
{"verb.sit", "siéger"},
{"verb.stand", "se lever"}
};
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/controllers/JSTLController.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/controllers/JSTLController.java | package com.baeldung.jstl.controllers;
import com.baeldung.jstl.dbaccess.SQLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.sql.*;
import java.util.Calendar;
@Controller
public class JSTLController {
private static final Logger LOGGER = LoggerFactory.getLogger(JSTLController.class.getName());
@Autowired
ServletContext servletContext;
@PostConstruct
public void init() {
PreparedStatement preparedStatement = null;
Connection connection = null;
try {
connection = SQLConnection.getConnection();
preparedStatement = connection.prepareStatement("create table IF NOT EXISTS USERS " +
"( id int not null primary key AUTO_INCREMENT," +
" email VARCHAR(255) not null, first_name varchar (255), last_name varchar (255), registered DATE)");
int status = preparedStatement.executeUpdate();
preparedStatement = connection.prepareStatement("SELECT COUNT(*) AS total FROM USERS;");
ResultSet result = preparedStatement.executeQuery();
if(result!=null) {
result.next();
if (result.getInt("total") == 0) {
generateDummy(connection);
}
} else {
generateDummy(connection);
}
} catch (Exception e) {
LOGGER.error(e.getMessage());
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
LOGGER.error(e.getMessage());
}
}
}
@RequestMapping(value = "/core_tags", method = RequestMethod.GET)
public ModelAndView coreTags(final Model model) {
ModelAndView mv = new ModelAndView("core_tags");
return mv;
}
@RequestMapping(value = "/core_tags_redirect", method = RequestMethod.GET)
public ModelAndView coreTagsRedirect(final Model model) {
ModelAndView mv = new ModelAndView("core_tags_redirect");
return mv;
}
@RequestMapping(value = "/formatting_tags", method = RequestMethod.GET)
public ModelAndView formattingTags(final Model model) {
ModelAndView mv = new ModelAndView("formatting_tags");
return mv;
}
@RequestMapping(value = "/sql_tags", method = RequestMethod.GET)
public ModelAndView sqlTags(final Model model) {
ModelAndView mv = new ModelAndView("sql_tags");
return mv;
}
@RequestMapping(value = "/xml_tags", method = RequestMethod.GET)
public ModelAndView xmlTags(final Model model) {
System.out.println("dddddddddddddddddffffffffffffff");
ModelAndView mv = new ModelAndView("xml_tags");
return mv;
}
@RequestMapping(value = "/items_xml", method = RequestMethod.GET)
@ResponseBody public FileSystemResource getFile(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/xml");
return new FileSystemResource(new File(servletContext.getRealPath("/WEB-INF/items.xsl")));
}
@RequestMapping(value = "/function_tags", method = RequestMethod.GET)
public ModelAndView functionTags(final Model model) {
ModelAndView mv = new ModelAndView("function_tags");
return mv;
}
private void generateDummy(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO USERS " +
"(email, first_name, last_name, registered) VALUES (?, ?, ?, ?);");
preparedStatement.setString(1, "patrick@baeldung.com");
preparedStatement.setString(2, "Patrick");
preparedStatement.setString(3, "Frank");
preparedStatement.setDate(4, new Date(Calendar.getInstance().getTimeInMillis()));
preparedStatement.addBatch();
preparedStatement.setString(1, "bfrank@baeldung.com");
preparedStatement.setString(2, "Benjamin");
preparedStatement.setString(3, "Franklin");
preparedStatement.setDate(4, new Date(Calendar.getInstance().getTimeInMillis()));
preparedStatement.executeBatch();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/foreachdemo/Movie.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/foreachdemo/Movie.java | package com.baeldung.jstl.foreachdemo;
public class Movie {
private String title;
private int year;
public Movie(String title, int year) {
this.title = title;
this.year = year;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/foreachdemo/JSTLForEachDemoController.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/jstl/foreachdemo/JSTLForEachDemoController.java | package com.baeldung.jstl.foreachdemo;
import java.util.List;
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.servlet.ModelAndView;
@Controller
public class JSTLForEachDemoController {
@RequestMapping(value = "/foreach-demo", method = RequestMethod.GET)
public ModelAndView forEachDemo(final Model model) {
ModelAndView mv = new ModelAndView("jstlForEachDemo");
List<Movie> movies = List.of(
//@formatter:off
new Movie("The Hurt Locker", 2008),
new Movie("A Beautiful Mind", 2001),
new Movie("The Silence of the Lambs", 1991),
new Movie("A Man for All Seasons", 1966),
new Movie("No Country for Old Men", 2007)
//@formatter:on
);
mv.addObject("movieList", movies);
return mv;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java | package com.baeldung.springmvcforms.controller;
import jakarta.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.springmvcforms.domain.Customer;
import com.baeldung.springmvcforms.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";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/FileUploadController.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/FileUploadController.java | package com.baeldung.springmvcforms.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java | package com.baeldung.springmvcforms.controller;
import com.baeldung.springmvcforms.domain.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;
@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, params = "submit")
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";
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST, params = "cancel")
public String cancel(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
model.addAttribute("message", "You clicked cancel, please re-enter employee details:");
return "employeeHome";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/UserController.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/UserController.java | package com.baeldung.springmvcforms.controller;
import com.baeldung.springmvcforms.domain.User;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import jakarta.validation.Valid;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Controller
public class UserController {
private List<User> users = Arrays.asList(
new User("ana@yahoo.com", "pass", "Ana", 20),
new User("bob@yahoo.com", "pass", "Bob", 30),
new User("john@yahoo.com", "pass", "John", 40),
new User("mary@yahoo.com", "pass", "Mary", 30));
@GetMapping("/userPage")
public String getUserProfilePage() {
return "user";
}
@PostMapping("/user")
@ResponseBody
public ResponseEntity<Object> saveUser(@Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) {
final List<String> errors = result.getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return new ResponseEntity<>(errors, HttpStatus.OK);
} else {
if (users.stream().anyMatch(it -> user.getEmail().equals(it.getEmail()))) {
return new ResponseEntity<>(Collections.singletonList("Email already exists!"), HttpStatus.CONFLICT);
} else {
users.add(user);
return new ResponseEntity<>(HttpStatus.CREATED);
}
}
}
@GetMapping("/users")
@ResponseBody
public List<User> getUsers() {
return users;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java | package com.baeldung.springmvcforms.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 jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRegistration;
public class WebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ApplicationConfiguration.class);
ctx.setServletContext(container);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(ctx));
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
// @Override
// public void onStartup(ServletContext container) {
// // Create the 'root' Spring application context
// AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
// rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class);
//
// // Manage the lifecycle of the root application context
// container.addListener(new ContextLoaderListener(rootContext));
//
// // Create the dispatcher servlet's Spring application context
// AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
// dispatcherServlet.register(MvcConfig.class);
//
// // Register and map the dispatcher servlet
// ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
// dispatcher.setLoadOnStartup(1);
// dispatcher.addMapping("/");
//
// }
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java | package com.baeldung.springmvcforms.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
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.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.baeldung.springmvcforms", "com.baeldung.jstl"})
public class ApplicationConfiguration implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ResourceBundleMessageSource resourceBundleMessageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
// switch orders to server views from html over views directory
@Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
bean.setOrder(1);
return bean;
}
@Bean
public InternalResourceViewResolver htmlViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/html/");
bean.setSuffix(".html");
bean.setOrder(2);
return bean;
}
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Employee.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Employee.java | package com.baeldung.springmvcforms.domain;
import jakarta.validation.constraints.NotNull;
import jakarta.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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Customer.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Customer.java | package com.baeldung.springmvcforms.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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java | package com.baeldung.springmvcforms.domain;
import jakarta.validation.constraints.Digits;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class User {
@NotNull
@Email
private String email;
@NotNull
@Size(min = 4, max = 15)
private String password;
@NotBlank
private String name;
@Min(18)
@Digits(integer = 2, fraction = 0)
private int age;
public User() {
}
public User(String email, String password, String name, int age) {
super();
this.email = email;
this.password = password;
this.name = name;
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/interceptor/FileUploadExceptionAdvice.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/interceptor/FileUploadExceptionAdvice.java | package com.baeldung.springmvcforms.interceptor;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.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;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/validator/CustomerValidator.java | spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/validator/CustomerValidator.java | package com.baeldung.springmvcforms.validator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.baeldung.springmvcforms.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.");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-freemarker/src/test/java/com/baeldung/SpringContextTest.java | spring-web-modules/spring-freemarker/src/test/java/com/baeldung/SpringContextTest.java | 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.freemarker.config.SpringWebConfig;
import com.baeldung.freemarker.config.WebConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringWebConfig.class, WebConfiguration.class })
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-freemarker/src/main/java/com/baeldung/freemarker/controller/SpringController.java | spring-web-modules/spring-freemarker/src/main/java/com/baeldung/freemarker/controller/SpringController.java | package com.baeldung.freemarker.controller;
import java.util.*;
import com.baeldung.freemarker.method.LastCharMethod;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.Version;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.baeldung.freemarker.model.Car;
@Controller
public class SpringController {
private static List<Car> carList = new ArrayList<Car>();
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "redirect:/cars";
}
static {
carList.add(new Car("Honda", "Civic"));
carList.add(new Car("Toyota", "Camry"));
carList.add(new Car("Nissan", "Altima"));
}
@RequestMapping(value = "/cars", method = RequestMethod.GET)
public String init(@ModelAttribute("model") ModelMap model) {
model.addAttribute("carList", carList);
return "index";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addCar(@ModelAttribute("car") Car car) {
if (null != car && null != car.getMake() && null != car.getModel() && !car.getMake().isEmpty() && !car.getModel().isEmpty()) {
carList.add(car);
}
return "redirect:/cars";
}
@RequestMapping(value = "/commons", method = RequestMethod.GET)
public String showCommonsPage(Model model) {
model.addAttribute("statuses", Arrays.asList("200 OK", "404 Not Found", "500 Internal Server Error"));
model.addAttribute("lastChar", new LastCharMethod());
model.addAttribute("random", new Random());
model.addAttribute("statics", new DefaultObjectWrapperBuilder(new Version("2.3.28")).build().getStaticModels());
return "commons";
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-freemarker/src/main/java/com/baeldung/freemarker/model/Car.java | spring-web-modules/spring-freemarker/src/main/java/com/baeldung/freemarker/model/Car.java | package com.baeldung.freemarker.model;
public class Car {
private String make;
private String model;
public Car() {
}
public Car(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-freemarker/src/main/java/com/baeldung/freemarker/method/LastCharMethod.java | spring-web-modules/spring-freemarker/src/main/java/com/baeldung/freemarker/method/LastCharMethod.java | package com.baeldung.freemarker.method;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.springframework.util.StringUtils;
import java.util.List;
public class LastCharMethod implements TemplateMethodModelEx {
public Object exec(List arguments) throws TemplateModelException {
if (arguments.size() != 1 || StringUtils.isEmpty(arguments.get(0)))
throw new TemplateModelException("Wrong arguments!");
String argument = arguments.get(0).toString();
return argument.charAt(argument.length() - 1);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-freemarker/src/main/java/com/baeldung/freemarker/config/SpringWebConfig.java | spring-web-modules/spring-freemarker/src/main/java/com/baeldung/freemarker/config/SpringWebConfig.java | package com.baeldung.freemarker.config;
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.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
@EnableWebMvc
@Configuration
@ComponentScan({ "com.baeldung.freemarker" })
public class SpringWebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Bean
public FreeMarkerViewResolver freemarkerViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(true);
resolver.setPrefix("");
resolver.setSuffix(".ftl");
return resolver;
}
@Bean
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
return freeMarkerConfigurer;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-freemarker/src/main/java/com/baeldung/freemarker/config/WebConfiguration.java | spring-web-modules/spring-freemarker/src/main/java/com/baeldung/freemarker/config/WebConfiguration.java | package com.baeldung.freemarker.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-crash/src/test/java/com/baeldung/SpringContextTest.java | spring-web-modules/spring-mvc-crash/src/test/java/com/baeldung/SpringContextTest.java | 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.ClientWebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ClientWebConfig.class)
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java | spring-web-modules/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java | import org.crsh.command.BaseCommand;
import org.crsh.cli.Usage;
import org.crsh.cli.Command;
import org.crsh.cli.Option;
public class message2 extends BaseCommand {
@Usage("show my own message using java")
@Command
public Object main(@Usage("custom message") @Option(names = { "m", "message" }) String message) {
if (message == null)
message = "No message given...";
return message;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java | spring-web-modules/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java | package com.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ImportResource("classpath:webMvcConfig.xml")
@Configuration
@ComponentScan
public class ClientWebConfig implements WebMvcConfigurer {
public ClientWebConfig() {
super();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java | spring-web-modules/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java | package com.baeldung.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@ComponentScan("com.baeldung.spring")
public class ClientWebConfigJava implements WebMvcConfigurer {
public ClientWebConfigJava() {
super();
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java | spring-web-modules/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java | package com.baeldung.spring.controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("welcome");
model.addObject("msg", "Welcome to Introduction to CRaSH article from Baeldung");
return model;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/listbindingexample/SpringContextTest.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/listbindingexample/SpringContextTest.java | package com.baeldung.listbindingexample;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.listbindingexample.ListBindingApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ListBindingApplication.class})
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/multipartboundary/FileControllerIntegrationTest.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/multipartboundary/FileControllerIntegrationTest.java | package com.baeldung.multipartboundary;
import static com.baeldung.multipartboundary.FileController.FILES;
import static okhttp3.MediaType.parse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class FileControllerIntegrationTest {
@LocalServerPort
private int port;
private static final String HOST = "http://localhost:";
private static final String BOUNDARY = "OurCustomBoundaryValue";
// @formatter:off
private static final String BODY =
"--" + BOUNDARY + "\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"import.csv\"\r\n" +
"Content-Type: text/csv\r\n" +
"\r\n" +
"content-of-the-csv-file\r\n" +
"--" + BOUNDARY + "\r\n" +
"Content-Disposition: form-data; name=\"fileDescription\"\r\n" +
"\r\n" +
"Records\r\n" +
"--" + BOUNDARY + "--";
// @formatter:on
private Response executeCall(RequestBody requestBody) throws IOException {
Request request = new Request.Builder().url(HOST + port + FILES)
.post(requestBody)
.build();
return new OkHttpClient().newCall(request)
.execute();
}
@Test
void givenFormData_whenPostWithoutBoundary_thenReturn500() throws IOException {
RequestBody requestBody = RequestBody.create(BODY.getBytes(), parse(MediaType.MULTIPART_FORM_DATA_VALUE));
try (Response response = executeCall(requestBody)) {
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), response.code());
}
}
@Test
void givenFormData_whenPostWithBoundary_thenReturn200() throws IOException {
RequestBody requestBody = RequestBody.create(BODY.getBytes(), parse(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + BOUNDARY));
try (Response response = executeCall(requestBody)) {
assertEquals(HttpStatus.OK.value(), response.code());
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyIntegrationTest.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyIntegrationTest.java | package com.baeldung.sessionattrs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
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.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
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.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
@Import(TestConfig.class)
public class TodoControllerWithScopedProxyIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.build();
}
@Test
public void whenFirstRequest_thenContainsUnintializedTodo() throws Exception {
MvcResult result = mockMvc.perform(get("/scopedproxy/form"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("todo"))
.andReturn();
TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo");
assertFalse(StringUtils.isEmpty(item.getDescription()));
}
@Test
public void whenSubmit_thenSubsequentFormRequestContainsMostRecentTodo() throws Exception {
mockMvc.perform(post("/scopedproxy/form")
.param("description", "newtodo"))
.andExpect(status().is3xxRedirection())
.andReturn();
MvcResult result = mockMvc.perform(get("/scopedproxy/form"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("todo"))
.andReturn();
TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo");
assertEquals("newtodo", item.getDescription());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/SpringContextTest.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/SpringContextTest.java | package com.baeldung.sessionattrs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.sessionattrs.SessionAttrsApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SessionAttrsApplication.class})
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/SessionAttrsApplicationIntegrationTest.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/SessionAttrsApplicationIntegrationTest.java | package com.baeldung.sessionattrs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SessionAttrsApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesIntegrationTest.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesIntegrationTest.java | package com.baeldung.sessionattrs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
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.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
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.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.FlashMap;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class TodoControllerWithSessionAttributesIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.build();
}
@Test
public void whenFirstRequest_thenContainsUnintializedTodo() throws Exception {
MvcResult result = mockMvc.perform(get("/sessionattributes/form"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("todo"))
.andReturn();
TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo");
assertTrue(StringUtils.isEmpty(item.getDescription()));
}
@Test
public void whenSubmit_thenSubsequentFormRequestContainsMostRecentTodo() throws Exception {
FlashMap flashMap = mockMvc.perform(post("/sessionattributes/form")
.param("description", "newtodo"))
.andExpect(status().is3xxRedirection())
.andReturn().getFlashMap();
MvcResult result = mockMvc.perform(get("/sessionattributes/form")
.sessionAttrs(flashMap))
.andExpect(status().isOk())
.andExpect(model().attributeExists("todo"))
.andReturn();
TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo");
assertEquals("newtodo", item.getDescription());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TestConfig.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TestConfig.java | package com.baeldung.sessionattrs;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.SimpleThreadScope;
@Configuration
public class TestConfig {
@Bean
public CustomScopeConfigurer customScopeConfigurer() {
CustomScopeConfigurer configurer = new CustomScopeConfigurer();
configurer.addScope("session", new SimpleThreadScope());
return configurer;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/multipartupload/EmployeeControllerIntegrationTest.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/multipartupload/EmployeeControllerIntegrationTest.java | package com.baeldung.multipartupload;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest
@EnableWebMvc
public class EmployeeControllerIntegrationTest {
private static final MockMultipartFile A_FILE = new MockMultipartFile("document", null, "application/octet-stream", "Employee Record".getBytes());
@Autowired
private MockMvc mockMvc;
@MockBean
private EmployeeService employeeService;
@Test
public void givenFormData_whenPost_thenReturns200OK() throws Exception {
mockMvc.perform(multipart("/employee")
.file(A_FILE)
.param("name", "testname"))
.andExpect(status().isOk());
}
@Test
public void givenEmployeeJsonAndMultipartFile_whenPostWithRequestPart_thenReturnsOK() throws Exception {
MockMultipartFile employeeJson = new MockMultipartFile("employee", null,
"application/json", "{\"name\": \"Emp Name\"}".getBytes());
mockMvc.perform(multipart("/requestpart/employee")
.file(A_FILE)
.file(employeeJson))
.andExpect(status().isOk());
}
@Test
public void givenRequestPartAndRequestParam_whenPost_thenReturns200OK() throws Exception {
mockMvc.perform(multipart("/requestparam/employee")
.file(A_FILE)
.param("name", "testname"))
.andExpect(status().isOk());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java | package com.baeldung.listbindingexample;
public class Book {
private long id;
private String title;
private String author;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (id != other.id)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public String toString() {
return "Book [id=" + id + ", title=" + title + ", author=" + author + "]";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java | package com.baeldung.listbindingexample;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;
@EnableWebMvc
@Configuration
public class Config implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/")
.setViewName("index");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
@Bean
public ITemplateResolver templateResolver() {
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("templates/books/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java | package com.baeldung.listbindingexample;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class InMemoryBookService implements BookService {
static Map<Long, Book> booksDB = new HashMap<>();
@Override
public List<Book> findAll() {
return new ArrayList<>(booksDB.values());
}
@Override
public void saveAll(List<Book> books) {
long nextId = getNextId();
for (Book book : books) {
if (book.getId() == 0) {
book.setId(nextId++);
}
}
Map<Long, Book> bookMap = books.stream()
.collect(Collectors.toMap(Book::getId, Function.identity()));
booksDB.putAll(bookMap);
}
private Long getNextId() {
return booksDB.keySet()
.stream()
.mapToLong(value -> value)
.max()
.orElse(0) + 1;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java | package com.baeldung.listbindingexample;
import java.util.List;
public interface BookService {
List<Book> findAll();
void saveAll(List<Book> books);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java | package com.baeldung.listbindingexample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, DataSourceAutoConfiguration.class })
public class ListBindingApplication {
public static void main(String[] args) {
SpringApplication.run(ListBindingApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java | package com.baeldung.listbindingexample;
import java.util.ArrayList;
import java.util.List;
public class BooksCreationDto {
private List<Book> books;
public BooksCreationDto() {
this.books = new ArrayList<>();
}
public BooksCreationDto(List<Book> books) {
this.books = books;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public void addBook(Book book) {
this.books.add(book);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java | package com.baeldung.listbindingexample;
import org.springframework.beans.factory.annotation.Autowired;
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
@RequestMapping("/books")
public class MultipleBooksController {
@Autowired
private BookService bookService;
@GetMapping(value = "/all")
public String showAll(Model model) {
model.addAttribute("books", bookService.findAll());
return "allBooks";
}
@GetMapping(value = "/create")
public String showCreateForm(Model model) {
BooksCreationDto booksForm = new BooksCreationDto();
for (int i = 1; i <= 3; i++) {
booksForm.addBook(new Book());
}
model.addAttribute("form", booksForm);
return "createBooksForm";
}
@GetMapping(value = "/edit")
public String showEditForm(Model model) {
List<Book> books = new ArrayList<>();
bookService.findAll()
.iterator()
.forEachRemaining(books::add);
model.addAttribute("form", new BooksCreationDto(books));
return "editBooksForm";
}
@PostMapping(value = "/save")
public String saveBooks(@ModelAttribute BooksCreationDto form, Model model) {
bookService.saveAll(form.getBooks());
model.addAttribute("books", bookService.findAll());
return "redirect:/books/all";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/multipartboundary/MultipartBoundaryApplication.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/multipartboundary/MultipartBoundaryApplication.java | package com.baeldung.multipartboundary;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MultipartBoundaryApplication {
public static void main(String[] args) {
SpringApplication.run(MultipartBoundaryApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/multipartboundary/FileController.java | spring-web-modules/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/multipartboundary/FileController.java | package com.baeldung.multipartboundary;
import static com.baeldung.multipartboundary.FileController.FILES;
import org.springframework.http.MediaType;
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;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping(FILES)
public class FileController {
protected static final String FILES = "/files";
@GetMapping()
public String displayUploadForm(Model model) {
return "files/uploadForm";
}
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String upload(@RequestParam("file") MultipartFile file, String fileDescription) {
return "files/success";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.