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-rest-query-language/src/main/java/com/baeldung/web/controller/HomeController.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/controller/HomeController.java
package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping(value = "/") public class HomeController { public String index() { return "homepage"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/controller/UserController.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/controller/UserController.java
package com.baeldung.web.controller; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.querydsl.binding.QuerydslPredicate; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.baeldung.persistence.dao.GenericSpecificationsBuilder; import com.baeldung.persistence.dao.IUserDAO; import com.baeldung.persistence.dao.MyUserPredicatesBuilder; import com.baeldung.persistence.dao.MyUserRepository; import com.baeldung.persistence.dao.UserRepository; import com.baeldung.persistence.dao.UserSpecification; import com.baeldung.persistence.dao.UserSpecificationsBuilder; import com.baeldung.persistence.dao.rsql.CustomRsqlVisitor; import com.baeldung.persistence.model.MyUser; import com.baeldung.persistence.model.User; import com.baeldung.web.util.CriteriaParser; import com.baeldung.web.util.SearchCriteria; import com.baeldung.web.util.SearchOperation; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.BooleanExpression; import cz.jirutka.rsql.parser.RSQLParser; import cz.jirutka.rsql.parser.ast.Node; //@EnableSpringDataWebSupport @Controller @RequestMapping(value = "/auth/") public class UserController { @Autowired private IUserDAO service; @Autowired private UserRepository dao; @Autowired private MyUserRepository myUserRepository; public UserController() { super(); } // API - READ @RequestMapping(method = RequestMethod.GET, value = "/users") @ResponseBody public List<User> search(@RequestParam(value = "search", required = false) String search) { List<SearchCriteria> params = new ArrayList<SearchCriteria>(); if (search != null) { Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); Matcher matcher = pattern.matcher(search + ","); while (matcher.find()) { params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3))); } } return service.searchUser(params); } @RequestMapping(method = RequestMethod.GET, value = "/users/spec") @ResponseBody public List<User> findAllBySpecification(@RequestParam(value = "search") String search) { UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); String operationSetExper = Joiner.on("|") .join(SearchOperation.SIMPLE_OPERATION_SET); Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),"); Matcher matcher = pattern.matcher(search + ","); while (matcher.find()) { builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5)); } Specification<User> spec = builder.build(); return dao.findAll(spec); } @GetMapping(value = "/users/espec") @ResponseBody public List<User> findAllByOrPredicate(@RequestParam(value = "search") String search) { Specification<User> spec = resolveSpecification(search); return dao.findAll(spec); } @GetMapping(value = "/users/spec/adv") @ResponseBody public List<User> findAllByAdvPredicate(@RequestParam(value = "search") String search) { Specification<User> spec = resolveSpecificationFromInfixExpr(search); return dao.findAll(spec); } protected Specification<User> resolveSpecificationFromInfixExpr(String searchParameters) { CriteriaParser parser = new CriteriaParser(); GenericSpecificationsBuilder<User> specBuilder = new GenericSpecificationsBuilder<>(); return specBuilder.build(parser.parse(searchParameters), UserSpecification::new); } protected Specification<User> resolveSpecification(String searchParameters) { UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); String operationSetExper = Joiner.on("|") .join(SearchOperation.SIMPLE_OPERATION_SET); Pattern pattern = Pattern.compile("(\\p{Punct}?)(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),"); Matcher matcher = pattern.matcher(searchParameters + ","); while (matcher.find()) { builder.with(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(5), matcher.group(4), matcher.group(6)); } return builder.build(); } @RequestMapping(method = RequestMethod.GET, value = "/myusers") @ResponseBody public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") String search) { MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder(); if (search != null) { Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); Matcher matcher = pattern.matcher(search + ","); while (matcher.find()) { builder.with(matcher.group(1), matcher.group(2), matcher.group(3)); } } BooleanExpression exp = builder.build(); return myUserRepository.findAll(exp); } @RequestMapping(method = RequestMethod.GET, value = "/users/rsql") @ResponseBody public List<User> findAllByRsql(@RequestParam(value = "search") String search) { Node rootNode = new RSQLParser().parse(search); Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>()); return dao.findAll(spec); } @RequestMapping(method = RequestMethod.GET, value = "/api/myusers") @ResponseBody public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) Predicate predicate) { return myUserRepository.findAll(predicate); } // API - WRITE @RequestMapping(method = RequestMethod.POST, value = "/users") @ResponseStatus(HttpStatus.CREATED) public void create(@RequestBody User resource) { Preconditions.checkNotNull(resource); dao.save(resource); } @RequestMapping(method = RequestMethod.POST, value = "/myusers") @ResponseStatus(HttpStatus.CREATED) public void addMyUser(@RequestBody MyUser resource) { Preconditions.checkNotNull(resource); myUserRepository.save(resource); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/util/CriteriaParser.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/util/CriteriaParser.java
package com.baeldung.web.util; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Joiner; public class CriteriaParser { private static Map<String, Operator> ops; private static Pattern SpecCriteraRegex = Pattern.compile("^(\\w+?)(" + Joiner.on("|") .join(SearchOperation.SIMPLE_OPERATION_SET) + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?)$"); private enum Operator { OR(1), AND(2); final int precedence; Operator(int p) { precedence = p; } } static { Map<String, Operator> tempMap = new HashMap<>(); tempMap.put("AND", Operator.AND); tempMap.put("OR", Operator.OR); tempMap.put("or", Operator.OR); tempMap.put("and", Operator.AND); ops = Collections.unmodifiableMap(tempMap); } private static boolean isHigerPrecedenceOperator(String currOp, String prevOp) { return (ops.containsKey(prevOp) && ops.get(prevOp).precedence >= ops.get(currOp).precedence); } public Deque<?> parse(String searchParam) { Deque<Object> output = new LinkedList<>(); Deque<String> stack = new LinkedList<>(); Arrays.stream(searchParam.split("\\s+")).forEach(token -> { if (ops.containsKey(token)) { while (!stack.isEmpty() && isHigerPrecedenceOperator(token, stack.peek())) output.push(stack.pop() .equalsIgnoreCase(SearchOperation.OR_OPERATOR) ? SearchOperation.OR_OPERATOR : SearchOperation.AND_OPERATOR); stack.push(token.equalsIgnoreCase(SearchOperation.OR_OPERATOR) ? SearchOperation.OR_OPERATOR : SearchOperation.AND_OPERATOR); } else if (token.equals(SearchOperation.LEFT_PARANTHESIS)) { stack.push(SearchOperation.LEFT_PARANTHESIS); } else if (token.equals(SearchOperation.RIGHT_PARANTHESIS)) { while (!stack.peek() .equals(SearchOperation.LEFT_PARANTHESIS)) output.push(stack.pop()); stack.pop(); } else { Matcher matcher = SpecCriteraRegex.matcher(token); while (matcher.find()) { output.push(new SpecSearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), matcher.group(5))); } } }); while (!stack.isEmpty()) output.push(stack.pop()); return output; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/util/SearchOperation.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/util/SearchOperation.java
package com.baeldung.web.util; public enum SearchOperation { EQUALITY, NEGATION, GREATER_THAN, LESS_THAN, LIKE, STARTS_WITH, ENDS_WITH, CONTAINS; public static final String[] SIMPLE_OPERATION_SET = { ":", "!", ">", "<", "~" }; public static final String OR_PREDICATE_FLAG = "'"; public static final String ZERO_OR_MORE_REGEX = "*"; public static final String OR_OPERATOR = "OR"; public static final String AND_OPERATOR = "AND"; public static final String LEFT_PARANTHESIS = "("; public static final String RIGHT_PARANTHESIS = ")"; public static SearchOperation getSimpleOperation(final char input) { switch (input) { case ':': return EQUALITY; case '!': return NEGATION; case '>': return GREATER_THAN; case '<': return LESS_THAN; case '~': return LIKE; default: 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-rest-query-language/src/main/java/com/baeldung/web/util/SpecSearchCriteria.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/util/SpecSearchCriteria.java
package com.baeldung.web.util; public class SpecSearchCriteria { private String key; private SearchOperation operation; private Object value; private boolean orPredicate; public SpecSearchCriteria() { } public SpecSearchCriteria(final String key, final SearchOperation operation, final Object value) { super(); this.key = key; this.operation = operation; this.value = value; } public SpecSearchCriteria(final String orPredicate, final String key, final SearchOperation operation, final Object value) { super(); this.orPredicate = orPredicate != null && orPredicate.equals(SearchOperation.OR_PREDICATE_FLAG); this.key = key; this.operation = operation; this.value = value; } public SpecSearchCriteria(String key, String operation, String prefix, String value, String suffix) { SearchOperation op = SearchOperation.getSimpleOperation(operation.charAt(0)); if (op != null) { if (op == SearchOperation.EQUALITY) { // the operation may be complex operation final boolean startWithAsterisk = prefix != null && prefix.contains(SearchOperation.ZERO_OR_MORE_REGEX); final boolean endWithAsterisk = suffix != null && suffix.contains(SearchOperation.ZERO_OR_MORE_REGEX); if (startWithAsterisk && endWithAsterisk) { op = SearchOperation.CONTAINS; } else if (startWithAsterisk) { op = SearchOperation.ENDS_WITH; } else if (endWithAsterisk) { op = SearchOperation.STARTS_WITH; } } } this.key = key; this.operation = op; this.value = value; } public String getKey() { return key; } public void setKey(final String key) { this.key = key; } public SearchOperation getOperation() { return operation; } public void setOperation(final SearchOperation operation) { this.operation = operation; } public Object getValue() { return value; } public void setValue(final Object value) { this.value = value; } public boolean isOrPredicate() { return orPredicate; } public void setOrPredicate(boolean orPredicate) { this.orPredicate = orPredicate; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/util/SearchCriteria.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/util/SearchCriteria.java
package com.baeldung.web.util; public class SearchCriteria { private String key; private String operation; private Object value; public SearchCriteria() { } public SearchCriteria(final String key, final String operation, final Object value) { super(); this.key = key; this.operation = operation; this.value = value; } public String getKey() { return key; } public void setKey(final String key) { this.key = key; } public String getOperation() { return operation; } public void setOperation(final String operation) { this.operation = operation; } public Object getValue() { return value; } public void setValue(final Object 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-rest-query-language/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java
package com.baeldung.web.error; import jakarta.persistence.EntityNotFoundException; import org.hibernate.exception.ConstraintViolationException; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.baeldung.web.exception.MyResourceNotFoundException; @ControllerAdvice public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { public RestResponseEntityExceptionHandler() { super(); } // API // 400 @ExceptionHandler({ ConstraintViolationException.class }) public ResponseEntity<Object> handleBadRequest(final ConstraintViolationException ex, final WebRequest request) { final String bodyOfResponse = "This should be application specific"; return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request); } @ExceptionHandler({ DataIntegrityViolationException.class }) public ResponseEntity<Object> handleBadRequest(final DataIntegrityViolationException ex, final WebRequest request) { final String bodyOfResponse = "This should be application specific"; return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request); } @Override protected ResponseEntity<Object> handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { final String bodyOfResponse = "This should be application specific"; // ex.getCause() instanceof JsonMappingException, JsonParseException // for additional information later on return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request); } @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { final String bodyOfResponse = "This should be application specific"; return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request); } // 404 @ExceptionHandler(value = { EntityNotFoundException.class, MyResourceNotFoundException.class }) protected ResponseEntity<Object> handleNotFound(final RuntimeException ex, final WebRequest request) { final String bodyOfResponse = "This should be application specific"; return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request); } // 409 @ExceptionHandler({ InvalidDataAccessApiUsageException.class, DataAccessException.class }) protected ResponseEntity<Object> handleConflict(final RuntimeException ex, final WebRequest request) { final String bodyOfResponse = "This should be application specific"; return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request); } // 412 // 500 @ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class }) /*500*/public ResponseEntity<Object> handleInternal(final RuntimeException ex, final WebRequest request) { logger.error("500 Status Code", ex); final String bodyOfResponse = "This should be application specific"; return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java
spring-web-modules/spring-rest-query-language/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java
package com.baeldung.web.exception; public final class MyResourceNotFoundException extends RuntimeException { public MyResourceNotFoundException() { super(); } public MyResourceNotFoundException(final String message, final Throwable cause) { super(message, cause); } public MyResourceNotFoundException(final String message) { super(message); } public MyResourceNotFoundException(final Throwable cause) { super(cause); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/test/java/com/baeldung/SpringContextTest.java
spring-web-modules/spring-mvc-basics-5/src/test/java/com/baeldung/SpringContextTest.java
package com.baeldung; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest 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-basics-5/src/test/java/com/baeldung/jsonargs/UserControllerIntegrationTest.java
spring-web-modules/spring-mvc-basics-5/src/test/java/com/baeldung/jsonargs/UserControllerIntegrationTest.java
package com.baeldung.jsonargs; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 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.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import com.fasterxml.jackson.databind.ObjectMapper; @WebMvcTest(controllers = UserController.class) class UserControllerIntegrationTest { @Autowired private MockMvc mockMvc; @Test void whenSendingAPostJSON_thenReturnFirstNameAndCity() throws Exception { String jsonString = "{\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":10,\"address\":{\"streetName\":\"Example Street\",\"streetNumber\":\"10A\",\"postalCode\":\"1QW34\",\"city\":\"Timisoara\",\"country\":\"Romania\"}}"; mockMvc.perform(post("/user/process/custom").content(jsonString) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.firstName") .value("John")) .andExpect(MockMvcResultMatchers.jsonPath("$.city") .value("Timisoara")); } @Test void whenSendingAPostJSON_thenReturnUserAndAddress() throws Exception { String jsonString = "{\"firstName\":\"John\",\"lastName\":\"Smith\",\"address\":{\"streetName\":\"Example Street\",\"streetNumber\":\"10A\",\"postalCode\":\"1QW34\",\"city\":\"Timisoara\",\"country\":\"Romania\"}}"; ObjectMapper mapper = new ObjectMapper(); UserDto user = mapper.readValue(jsonString, UserDto.class); AddressDto address = user.getAddress(); String mvcResult = mockMvc.perform(post("/user/process/custompojo").content(jsonString) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); assertEquals(String.format("{\"firstName\": %s, \"lastName\": %s, \"address\" : %s}", user.getFirstName(), user.getLastName(), address), mvcResult); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/test/java/com/baeldung/responsestatus/ResponseStatusRestControllerIntegrationTest.java
spring-web-modules/spring-mvc-basics-5/src/test/java/com/baeldung/responsestatus/ResponseStatusRestControllerIntegrationTest.java
package com.baeldung.responsestatus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class ResponseStatusRestControllerIntegrationTest { private MockMvc mockMvc; @BeforeEach public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(new ResponseStatusRestController()) .build(); } @Test public void whenTeapotEndpointCalled_thenTeapotResponseObtained() throws Exception { this.mockMvc.perform(get("/teapot")) .andExpect(status().isIAmATeapot()); } @Test public void whenEmptyNoContentEndpointCalled_thenNoContentResponseObtained() throws Exception { this.mockMvc.perform(get("/empty")) .andExpect(status().isNoContent()); } @Test public void whenEmptyWithoutResponseStatusEndpointCalled_then200ResponseObtained() throws Exception { this.mockMvc.perform(get("/empty-no-responsestatus")) .andExpect(status().isOk()); } @Test public void whenCreateWithCreatedEndpointCalled_thenCreatedResponseObtained() throws Exception { this.mockMvc.perform(post("/create")) .andExpect(status().isCreated()); } @Test public void whenCreateWithoutResponseStatusEndpointCalled_thenCreatedResponseObtained() throws Exception { this.mockMvc.perform(post("/create-no-responsestatus")) .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-basics-5/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java
spring-web-modules/spring-mvc-basics-5/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java
package com.baeldung.exception; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 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.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import com.baeldung.Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @AutoConfigureMockMvc public class HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest { @Autowired MockMvc mockMvc; @Test public void whenHttpMediaTypeNotAcceptableExceptionTriggered_thenExceptionHandled() throws Exception { mockMvc.perform(post("/test").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_PDF)) .andExpect(content().string("acceptable MIME type:application/json")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/test/java/com/baeldung/deletewrequestbody/DeleteWithRequestBodyLiveTest.java
spring-web-modules/spring-mvc-basics-5/src/test/java/com/baeldung/deletewrequestbody/DeleteWithRequestBodyLiveTest.java
package com.baeldung.deletewrequestbody; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import com.baeldung.deletewrequestbody.client.Apache5DeleteClient; import com.baeldung.deletewrequestbody.client.ApacheDeleteClient; import com.baeldung.deletewrequestbody.client.PlainDeleteClient; import com.baeldung.deletewrequestbody.client.SpringTemplateDeleteClient; import com.baeldung.deletewrequestbody.model.Body; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @SpringBootTest class DeleteWithRequestBodyLiveTest { static String json; static String url; @BeforeAll static void setup(@Value("${server.port:8080}") int port, @Value("${server.servlet.context-path:/}") String context) throws JsonProcessingException { url = String.format("http://localhost:%d%s/delete", port, context); Body body = new Body(); body.setName("foo"); body.setValue(1); json = new ObjectMapper().writeValueAsString(body); } @Test void whenRestTemplate_thenDeleteWithBody() { SpringTemplateDeleteClient client = new SpringTemplateDeleteClient(url); assertEquals(json, client.delete(json)); } @Test void whenPlainHttpClient_thenDeleteWithBody() throws IOException, InterruptedException { PlainDeleteClient client = new PlainDeleteClient(url); assertEquals(json, client.delete(json)); } @Test void whenApacheHttpClient_thenDeleteWithBody() throws IOException { ApacheDeleteClient client = new ApacheDeleteClient(url); assertEquals(json, client.delete(json)); } @Test void whenApacheHttpClient5_thenDeleteWithBody() throws IOException { Apache5DeleteClient client = new Apache5DeleteClient(url); assertEquals(json, client.delete(json)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/Application.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/Application.java
package com.baeldung; 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-mvc-basics-5/src/main/java/com/baeldung/jsonargs/AddressDto.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/AddressDto.java
package com.baeldung.jsonargs; public class AddressDto { private String streetName; private String streetNumber; private String postalCode; private String city; private String country; public String getStreetName() { return streetName; } public void setStreetName(String streetName) { this.streetName = streetName; } public String getStreetNumber() { return streetNumber; } public void setStreetNumber(String streetNumber) { this.streetNumber = streetNumber; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Override public String toString() { return "Address{" + "streetName='" + streetName + '\'' + ", streetNumber='" + streetNumber + '\'' + ", postalCode='" + postalCode + '\'' + ", city='" + city + '\'' + ", country='" + country + '\'' + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/UserDto.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/UserDto.java
package com.baeldung.jsonargs; public class UserDto { private String firstName; private String lastName; private String age; private AddressDto address; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public AddressDto getAddress() { return address; } public void setAddress(AddressDto address) { this.address = address; } @Override public String toString() { return "User{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age='" + age + '\'' + ", address=" + address + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/JsonArgumentResolver.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/JsonArgumentResolver.java
package com.baeldung.jsonargs; import java.io.IOException; import java.util.Objects; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; import com.jayway.jsonpath.JsonPath; public class JsonArgumentResolver implements HandlerMethodArgumentResolver { private static final String JSON_BODY_ATTRIBUTE = "JSON_REQUEST_BODY"; @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(JsonArg.class); } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { String body = getRequestBody(webRequest); String jsonPath = Objects.requireNonNull(Objects.requireNonNull(parameter.getParameterAnnotation(JsonArg.class)) .value()); Class<?> parameterType = parameter.getParameterType(); return JsonPath.parse(body) .read(jsonPath, parameterType); } private String getRequestBody(NativeWebRequest webRequest) { HttpServletRequest servletRequest = Objects.requireNonNull(webRequest.getNativeRequest(HttpServletRequest.class)); String jsonBody = (String) servletRequest.getAttribute(JSON_BODY_ATTRIBUTE); if (jsonBody == null) { try { jsonBody = IOUtils.toString(servletRequest.getInputStream()); servletRequest.setAttribute(JSON_BODY_ATTRIBUTE, jsonBody); } catch (IOException e) { throw new RuntimeException(e); } } return jsonBody; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/UserController.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/UserController.java
package com.baeldung.jsonargs; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @PostMapping("/process/custom") public ResponseEntity process(@JsonArg("firstName") String firstName, @JsonArg("address.city") String city) { /* business processing */ return ResponseEntity.ok() .body(String.format("{\"firstName\": %s, \"city\" : %s}", firstName, city)); } @PostMapping("/process") public ResponseEntity process(@RequestBody UserDto user) { /* business processing */ return ResponseEntity.ok() .body(user.toString()); } @PostMapping("/process/custompojo") public ResponseEntity process(@JsonArg("firstName") String firstName, @JsonArg("lastName") String lastName, @JsonArg("address") AddressDto address) { /* business processing */ return ResponseEntity.ok() .body(String.format("{\"firstName\": %s, \"lastName\": %s, \"address\" : %s}", firstName, lastName, address)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/JsonArg.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/jsonargs/JsonArg.java
package com.baeldung.jsonargs; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface JsonArg { String value() default ""; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/responsestatus/Book.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/responsestatus/Book.java
package com.baeldung.responsestatus; public class Book { private int id; private String author; private String title; public Book() { } public Book(int id, String author, String title) { this.id = id; this.author = author; this.title = title; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/responsestatus/ResponseStatusRestController.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/responsestatus/ResponseStatusRestController.java
package com.baeldung.responsestatus; import java.util.concurrent.ThreadLocalRandom; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @RestController public class ResponseStatusRestController { @GetMapping("/teapot") @ResponseStatus(HttpStatus.I_AM_A_TEAPOT) public void teaPot() { } @GetMapping("empty") @ResponseStatus(HttpStatus.NO_CONTENT) public void emptyResponse() { } @GetMapping("empty-no-responsestatus") public void emptyResponseWithoutResponseStatus() { } @PostMapping("create") @ResponseStatus(HttpStatus.CREATED) public Book createEntity() { // here we would create and persist an entity int randomInt = ThreadLocalRandom.current() .nextInt(1, 100); Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); return entity; } @PostMapping("create-no-responsestatus") public Book createEntityWithoutResponseStatus() { // here we would create and persist an entity int randomInt = ThreadLocalRandom.current() .nextInt(1, 100); Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); return entity; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java
package com.baeldung.exception; import java.util.Collections; import java.util.Map; import org.springframework.http.MediaType; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @ControllerAdvice public class HttpMediaTypeNotAcceptableExceptionExampleController { @PostMapping(value = "/test", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public Map<String, String> test() { return Collections.singletonMap("key", "value"); } @ResponseBody @ExceptionHandler(HttpMediaTypeNotAcceptableException.class) public String handleHttpMediaTypeNotAcceptableException() { return "acceptable MIME type:" + MediaType.APPLICATION_JSON_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-basics-5/src/main/java/com/baeldung/deletewrequestbody/DeleteController.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/DeleteController.java
package com.baeldung.deletewrequestbody; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.baeldung.deletewrequestbody.model.Body; @RestController @RequestMapping("/delete") public class DeleteController { @DeleteMapping public Body delete(@RequestBody Body body) { return body; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/model/Body.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/model/Body.java
package com.baeldung.deletewrequestbody.model; public class Body { private String name; private Integer value; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getValue() { return value; } public void setValue(Integer 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-basics-5/src/main/java/com/baeldung/deletewrequestbody/client/SpringTemplateDeleteClient.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/client/SpringTemplateDeleteClient.java
package com.baeldung.deletewrequestbody.client; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class SpringTemplateDeleteClient { private final String url; private RestTemplate client = new RestTemplate(); public SpringTemplateDeleteClient(String url) { this.url = url; } public String delete(String json) { HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "application/json"); HttpEntity<String> body = new HttpEntity<>(json, headers); ResponseEntity<String> response = client.exchange(url, HttpMethod.DELETE, body, String.class); return response.getBody(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/client/Apache5DeleteClient.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/client/Apache5DeleteClient.java
package com.baeldung.deletewrequestbody.client; import java.io.IOException; import org.apache.hc.client5.http.classic.methods.HttpDelete; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.io.HttpClientResponseHandler; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.StringEntity; public class Apache5DeleteClient { private final String url; public Apache5DeleteClient(String url) { this.url = url; } public String delete(String json) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { StringEntity body = new StringEntity(json, ContentType.APPLICATION_JSON); HttpDelete delete = new HttpDelete(url); delete.setEntity(body); HttpClientResponseHandler<String> handler = response -> { try (HttpEntity entity = response.getEntity()) { return EntityUtils.toString(entity); } }; return client.execute(delete, handler); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/client/ApacheDeleteClient.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/client/ApacheDeleteClient.java
package com.baeldung.deletewrequestbody.client; import java.io.IOException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.baeldung.deletewrequestbody.client.helper.HttpDeleteBody; public class ApacheDeleteClient { private final String url; public ApacheDeleteClient(String url) { this.url = url; } public String delete(String json) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { StringEntity body = new StringEntity(json, ContentType.APPLICATION_JSON); HttpDeleteBody delete = new HttpDeleteBody(url); delete.setEntity(body); CloseableHttpResponse response = client.execute(delete); return EntityUtils.toString(response.getEntity()); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/client/PlainDeleteClient.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/client/PlainDeleteClient.java
package com.baeldung.deletewrequestbody.client; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpRequest.BodyPublisher; import java.net.http.HttpResponse; public class PlainDeleteClient { private final String url; private HttpClient client = HttpClient.newHttpClient(); public PlainDeleteClient(String url) { this.url = url; } public String delete(String json) throws InterruptedException, IOException { BodyPublisher body = HttpRequest.BodyPublishers.ofString(json); HttpRequest request = HttpRequest.newBuilder(URI.create(url)) .header("Content-Type", "application/json") .method("DELETE", body) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); return response.body(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/client/helper/HttpDeleteBody.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/deletewrequestbody/client/helper/HttpDeleteBody.java
package com.baeldung.deletewrequestbody.client.helper; import java.net.URI; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; public class HttpDeleteBody extends HttpEntityEnclosingRequestBase { public HttpDeleteBody(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return "DELETE"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/spring/web/config/WebConfig.java
spring-web-modules/spring-mvc-basics-5/src/main/java/com/baeldung/spring/web/config/WebConfig.java
package com.baeldung.spring.web.config; import java.util.List; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.ViewResolver; 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.resource.PathResourceResolver; import org.springframework.web.servlet.view.BeanNameViewResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import com.baeldung.jsonargs.JsonArgumentResolver; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/") .setViewName("index"); } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { JsonArgumentResolver jsonArgumentResolver = new JsonArgumentResolver(); argumentResolvers.add(jsonArgumentResolver); } @Bean public ViewResolver viewResolver() { InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); bean.setOrder(2); return bean; } /** Static resource locations */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/", "/resources/") .setCachePeriod(3600) .resourceChain(true) .addResolver(new PathResourceResolver()); } @Bean public BeanNameViewResolver beanNameViewResolver() { BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver(); beanNameViewResolver.setOrder(1); return beanNameViewResolver; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java
spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java
package com.baeldung.thymeleaf.mvcdata; import static org.hamcrest.CoreMatchers.containsString; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import com.baeldung.thymeleaf.mvcdata.repository.EmailData; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc(printOnlyOnFailure = false) public class EmailControllerUnitTest { EmailData emailData = new EmailData(); @Autowired private MockMvc mockMvc; @Test public void whenCallModelAttributes_thenReturnEmailData() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/email/modelattributes")) .andExpect(status().isOk()) .andExpect(content().string(containsString("You have received a new message"))); } @Test public void whenCallRequestParameters_thenReturnEmailData() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("emailsubject", emailData.getEmailSubject()); params.add("emailcontent", emailData.getEmailBody()); params.add("emailaddress", emailData.getEmailAddress1()); params.add("emailaddress", emailData.getEmailAddress2()); params.add("emaillocale", emailData.getEmailLocale()); mockMvc.perform(MockMvcRequestBuilders.get("/email/requestparameters") .params(params)) .andExpect(status().isOk()) .andExpect(content().string(containsString("en-US"))); } @Test public void whenCallBeanData_thenReturnEmailData() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/email/beandata")) .andExpect(status().isOk()) .andExpect(content().string(containsString("jhon.doe@example.com"))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java
package com.baeldung.thymeleaf; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; @Configuration public class ThymeleafConfig { @Bean public ClassLoaderTemplateResolver secondaryTemplateResolver() { ClassLoaderTemplateResolver secondaryTemplateResolver = new ClassLoaderTemplateResolver(); secondaryTemplateResolver.setPrefix("templates-2/"); secondaryTemplateResolver.setSuffix(".html"); secondaryTemplateResolver.setTemplateMode(TemplateMode.HTML); secondaryTemplateResolver.setCharacterEncoding("UTF-8"); secondaryTemplateResolver.setOrder(1); secondaryTemplateResolver.setCheckExistence(true); return secondaryTemplateResolver; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/Application.java
spring-web-modules/spring-thymeleaf-4/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-4/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java
package com.baeldung.thymeleaf.mvcdata; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestParam; import com.baeldung.thymeleaf.mvcdata.repository.EmailData; @Controller public class EmailController { private EmailData emailData = new EmailData(); private ServletContext servletContext; public EmailController(ServletContext servletContext) { this.servletContext = servletContext; } @GetMapping(value = "/email/modelattributes") public String emailModel(Model model) { model.addAttribute("emaildata", emailData); return "mvcdata/email-model-attributes"; } @ModelAttribute("emailModelAttribute") EmailData emailModelAttribute() { return emailData; } @GetMapping(value = "/email/requestparameters") public String emailRequestParameters( @RequestParam(value = "emailsubject") String emailSubject, @RequestParam(value = "emailcontent") String emailContent, @RequestParam(value = "emailaddress") String emailAddress1, @RequestParam(value = "emailaddress") String emailAddress2, @RequestParam(value = "emaillocale") String emailLocale) { return "mvcdata/email-request-parameters"; } @GetMapping("/email/beandata") public String emailBeanData() { return "mvcdata/email-bean-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-4/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java
package com.baeldung.thymeleaf.mvcdata; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.baeldung.thymeleaf.mvcdata.repository.EmailData; @Configuration public class BeanConfig { @Bean public EmailData emailData() { return new EmailData(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java
package com.baeldung.thymeleaf.mvcdata.repository; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class EmailData implements Serializable { private String emailSubject; private String emailBody; private String emailLocale; private String emailAddress1; private String emailAddress2; public EmailData() { this.emailSubject = "You have received a new message"; this.emailBody = "Good morning !"; this.emailLocale = "en-US"; this.emailAddress1 = "jhon.doe@example.com"; this.emailAddress2 = "mark.jakob@example.com"; } public String getEmailSubject() { return this.emailSubject; } public String getEmailBody() { return this.emailBody; } public String getEmailLocale() { return this.emailLocale; } public String getEmailAddress1() { return this.emailAddress1; } public String getEmailAddress2() { return this.emailAddress2; } public List<String> getEmailAddresses() { List<String> emailAddresses = new ArrayList<>(); emailAddresses.add(getEmailAddress1()); emailAddresses.add(getEmailAddress2()); return emailAddresses; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java
package com.baeldung.thymeleaf.templatedir; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HelloController { @GetMapping("/hello") public String sayHello() { return "hello"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/url/UrlController.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/url/UrlController.java
package com.baeldung.thymeleaf.url; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class UrlController { @GetMapping("/search") public String test(Model model, @RequestParam("query") String query){ return "url/index"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/imageupload/UploadController.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/imageupload/UploadController.java
package com.baeldung.thymeleaf.imageupload; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @Controller public class UploadController { public static String UPLOAD_DIRECTORY = System.getProperty("user.dir") + "/uploads"; @GetMapping("/uploadimage") public String displayUploadForm() { return "imageupload/index"; } @PostMapping("/upload") public String uploadImage(Model model, @RequestParam("image") MultipartFile file) throws IOException { StringBuilder fileNames = new StringBuilder(); Path fileNameAndPath = Paths.get(UPLOAD_DIRECTORY, file.getOriginalFilename()); fileNames.append(file.getOriginalFilename()); Files.write(fileNameAndPath, file.getBytes()); model.addAttribute("msg", "Uploaded images: " + fileNames.toString()); return "imageupload/index"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/attributes/AttributeController.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/attributes/AttributeController.java
package com.baeldung.thymeleaf.attributes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/attributes") public class AttributeController { private static final Logger logger = LoggerFactory.getLogger(AttributeController.class); @GetMapping public String show(Model model) { model.addAttribute("title", "Baeldung"); model.addAttribute("email", "default@example.com"); return "attributes/index"; } @PostMapping public String submit(String email) { logger.info("Email: {}", email); return "redirect:attributes"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/expression/DinoController.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/expression/DinoController.java
package com.baeldung.thymeleaf.expression; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList; import java.util.List; @Controller public class DinoController { ArrayList<Dino> dinos = new ArrayList<Dino>(); @RequestMapping("/") public String dinoList(Model model) { Dino dinos = new Dino(1, "alpha", "red", "50kg"); model.addAttribute("dinos", new Dino()); model.addAttribute("dinos", dinos); System.out.println(dinos); return "index"; } @RequestMapping("/create") public String dinoCreate(Model model) { model.addAttribute("dinos", new Dino()); return "form"; } @PostMapping("/dino") public String dinoSubmit(@ModelAttribute Dino dino, Model model) { model.addAttribute("dino", dino); return "result"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/expression/Dino.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/expression/Dino.java
package com.baeldung.thymeleaf.expression; public class Dino { private int id; private String name; private String color; private String weight; public Dino(int id, String name, String color, String weight) { this.id = id; this.name = name; this.color = color; this.weight = weight; } public Dino() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/attribute/CheckedAttributeController.java
spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/attribute/CheckedAttributeController.java
package com.baeldung.thymeleaf.attribute; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class CheckedAttributeController { @GetMapping("/checked") public String displayCheckboxForm(Model model) { Engine engine = new Engine(true); model.addAttribute("engine", engine); model.addAttribute("flag", true); return "attribute/index"; } private static class Engine { private Boolean active; public Engine(Boolean active) { this.active = active; } public Boolean getActive() { return active; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/SpringContextTest.java
spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/SpringContextTest.java
package com.baeldung; import com.baeldung.spring.Application; 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(classes = Application.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-rest-testing/src/test/java/com/baeldung/Consts.java
spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/Consts.java
package com.baeldung; public interface Consts { int APPLICATION_PORT = 8082; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/SpringContextIntegrationTest.java
spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/SpringContextIntegrationTest.java
package com.baeldung; import com.baeldung.spring.Application; 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(classes = Application.class) public class SpringContextIntegrationTest { @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-rest-testing/src/test/java/com/baeldung/util/IDUtil.java
spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/util/IDUtil.java
package com.baeldung.util; import java.util.Random; public final class IDUtil { private IDUtil() { throw new AssertionError(); } // API public static String randomPositiveLongAsString() { return Long.toString(randomPositiveLong()); } public static String randomNegativeLongAsString() { return Long.toString(randomNegativeLong()); } public static long randomPositiveLong() { long id = new Random().nextLong() * 10000; id = (id < 0) ? (-1 * id) : id; return id; } private static long randomNegativeLong() { long id = new Random().nextLong() * 10000; id = (id > 0) ? (-1 * id) : id; return id; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/persistence/PersistenceTestSuite.java
spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/persistence/PersistenceTestSuite.java
package com.baeldung.persistence; import com.baeldung.persistence.service.FooServicePersistenceIntegrationTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off FooServicePersistenceIntegrationTest.class }) // public class PersistenceTestSuite { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java
spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java
package com.baeldung.persistence.service; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.hamcrest.MatcherAssert.assertThat; import java.io.Serializable; import java.util.List; import com.baeldung.util.IDUtil; import com.baeldung.persistence.IOperations; import com.baeldung.persistence.model.Foo; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Test; import org.springframework.dao.DataAccessException; public abstract class AbstractServicePersistenceIntegrationTest<T extends Serializable> { // tests // find - one @Test /**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() { // When final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong()); // Then assertNull(createdResource); } @Test public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() { final Foo existingResource = persistNewEntity(); getApi().findOne(existingResource.getId()); } @Test public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() { getApi().findOne(IDUtil.randomPositiveLong()); } @Test public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() { final Foo existingResource = persistNewEntity(); final Foo retrievedResource = getApi().findOne(existingResource.getId()); assertNotNull(retrievedResource); } @Test public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() { final Foo existingResource = persistNewEntity(); final Foo retrievedResource = getApi().findOne(existingResource.getId()); assertEquals(existingResource, retrievedResource); } // find - one - by name // find - all @Test /**/public void whenAllResourcesAreRetrieved_thenNoExceptions() { getApi().findAll(); } @Test /**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() { final List<Foo> resources = getApi().findAll(); assertNotNull(resources); } @Test /**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() { persistNewEntity(); // When final List<Foo> allResources = getApi().findAll(); // Then assertThat(allResources, not(Matchers.<Foo> empty())); } @Test /**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() { final Foo existingResource = persistNewEntity(); final List<Foo> resources = getApi().findAll(); assertThat(resources, hasItem(existingResource)); } @Test /**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() { persistNewEntity(); // When final List<Foo> allResources = getApi().findAll(); // Then for (final Foo resource : allResources) { assertNotNull(resource.getId()); } } // create @Test(expected = RuntimeException.class) /**/public void whenNullResourceIsCreated_thenException() { getApi().create(null); } @Test /**/public void whenResourceIsCreated_thenNoExceptions() { persistNewEntity(); } @Test /**/public void whenResourceIsCreated_thenResourceIsRetrievable() { final Foo existingResource = persistNewEntity(); assertNotNull(getApi().findOne(existingResource.getId())); } @Test /**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() { final Foo originalResource = createNewEntity(); final Foo savedResource = getApi().create(originalResource); assertEquals(originalResource, savedResource); } @Test(expected = RuntimeException.class) public void whenResourceWithFailedConstraintsIsCreated_thenException() { final Foo invalidResource = createNewEntity(); invalidate(invalidResource); getApi().create(invalidResource); } /** * -- specific to the persistence engine */ @Test(expected = DataAccessException.class) @Ignore("Hibernate simply ignores the id silently and still saved (tracking this)") public void whenResourceWithIdIsCreated_thenDataAccessException() { final Foo resourceWithId = createNewEntity(); resourceWithId.setId(IDUtil.randomPositiveLong()); getApi().create(resourceWithId); } // update @Test(expected = RuntimeException.class) /**/public void whenNullResourceIsUpdated_thenException() { getApi().update(null); } @Test /**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() { // Given final Foo existingResource = persistNewEntity(); // When getApi().update(existingResource); } /** * - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException */ @Test(expected = RuntimeException.class) public void whenResourceIsUpdatedWithFailedConstraints_thenException() { final Foo existingResource = persistNewEntity(); invalidate(existingResource); getApi().update(existingResource); } @Test /**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() { // Given final Foo existingResource = persistNewEntity(); // When change(existingResource); getApi().update(existingResource); final Foo updatedResource = getApi().findOne(existingResource.getId()); // Then assertEquals(existingResource, updatedResource); } // delete // @Test(expected = RuntimeException.class) // public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() { // // When // getApi().delete(IDUtil.randomPositiveLong()); // } // // @Test(expected = RuntimeException.class) // public void whenResourceIsDeletedByNegativeId_thenException() { // // When // getApi().delete(IDUtil.randomNegativeLong()); // } // // @Test // public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() { // // Given // final Foo existingResource = persistNewEntity(); // // // When // getApi().delete(existingResource.getId()); // } // // @Test // /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() { // // Given // final Foo existingResource = persistNewEntity(); // // // When // getApi().delete(existingResource.getId()); // // // Then // assertNull(getApi().findOne(existingResource.getId())); // } // template method protected Foo createNewEntity() { return new Foo(randomAlphabetic(6)); } protected abstract IOperations<Foo> getApi(); private final void invalidate(final Foo entity) { entity.setName(null); } private final void change(final Foo entity) { entity.setName(randomAlphabetic(6)); } protected Foo persistNewEntity() { return getApi().create(createNewEntity()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
package com.baeldung.persistence.service; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.junit.Assert.assertNotNull; import com.baeldung.persistence.IOperations; import com.baeldung.persistence.model.Foo; import com.baeldung.spring.PersistenceConfig; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest<Foo> { @Autowired private IFooService service; // tests @Test public final void whenContextIsBootstrapped_thenNoExceptions() { // } @Test public final void whenEntityIsCreated_thenNoExceptions() { service.create(new Foo(randomAlphabetic(6))); } @Test(expected = DataIntegrityViolationException.class) public final void whenInvalidEntityIsCreated_thenDataException() { service.create(new Foo()); } @Test(expected = DataIntegrityViolationException.class) public final void whenEntityWithLongNameIsCreated_thenDataException() { service.create(new Foo(randomAlphabetic(2048))); } // custom Query method @Test public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() { final String name = randomAlphabetic(6); service.create(new Foo(name)); final Foo retrievedByName = service.retrieveByName(name); assertNotNull(retrievedByName); } // work in progress @Test(expected = InvalidDataAccessApiUsageException.class) @Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail") public final void whenSameEntityIsCreatedTwice_thenDataException() { final Foo entity = new Foo(randomAlphabetic(8)); service.create(entity); service.create(entity); } // API @Override protected final IOperations<Foo> getApi() { return service; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/exceptiontesting/controller/ExceptionControllerUnitTest.java
spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/exceptiontesting/controller/ExceptionControllerUnitTest.java
package com.baeldung.exceptiontesting.controller; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import com.baeldung.exceptiontesting.controller.ExceptionController; import com.baeldung.exceptiontesting.exception.BadArgumentsException; import com.baeldung.exceptiontesting.exception.InternalException; import com.baeldung.exceptiontesting.exception.ResourceNotFoundException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @WebMvcTest(ExceptionController.class) public class ExceptionControllerUnitTest{ @Autowired private MockMvc mvc; @Test public void givenNotFound_whenGetSpecificException_thenNotFoundCode() throws Exception { String exceptionParam = "not_found"; mvc.perform(get("/exception/{exception_id}", exceptionParam) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()) .andExpect(result -> assertTrue(result.getResolvedException() instanceof ResourceNotFoundException)) .andExpect(result -> assertEquals("resource not found", result.getResolvedException().getMessage())); } @Test public void givenBadArguments_whenGetSpecificException_thenBadRequest() throws Exception { String exceptionParam = "bad_arguments"; mvc.perform(get("/exception/{exception_id}", exceptionParam) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(result -> assertTrue(result.getResolvedException() instanceof BadArgumentsException)) .andExpect(result -> assertEquals("bad arguments", result.getResolvedException().getMessage())); } @Test public void givenOther_whenGetSpecificException_thenInternalServerError() throws Exception { String exceptionParam = "dummy"; mvc.perform(get("/exception/{exception_id}", exceptionParam) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isInternalServerError()) .andExpect(result -> assertTrue(result.getResolvedException() instanceof InternalException)) .andExpect(result -> assertEquals("internal error", result.getResolvedException().getMessage())); } @Test(expected = Exception.class) public void whenGetException_thenInternalServerError() throws Exception { mvc.perform(get("/exception/throw") .contentType(MediaType.APPLICATION_JSON)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/cargo/CargoPluginLiveTest.java
spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/cargo/CargoPluginLiveTest.java
package com.baeldung.cargo; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; class CargoPluginLiveTest { @Test void givenCargoProfile_expectTestRuns() { assertTrue(true); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/IOperations.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/IOperations.java
package com.baeldung.persistence; import java.io.Serializable; import java.util.List; public interface IOperations<T extends Serializable> { // read - one T findOne(final long id); // read - all List<T> findAll(); // write T create(final T entity); T update(final T entity); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/dao/IFooDao.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/dao/IFooDao.java
package com.baeldung.persistence.dao; import com.baeldung.persistence.model.Foo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface IFooDao extends JpaRepository<Foo, Long> { @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") Foo retrieveByName(@Param("name") String name); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/service/IFooService.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/service/IFooService.java
package com.baeldung.persistence.service; import com.baeldung.persistence.model.Foo; import com.baeldung.persistence.IOperations; public interface IFooService extends IOperations<Foo> { Foo retrieveByName(String name); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/service/impl/FooService.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/service/impl/FooService.java
package com.baeldung.persistence.service.impl; import com.baeldung.persistence.dao.IFooDao; import com.baeldung.persistence.model.Foo; import com.baeldung.persistence.service.IFooService; import com.baeldung.persistence.service.common.AbstractService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class FooService extends AbstractService<Foo> implements IFooService { @Autowired private IFooDao dao; public FooService() { super(); } // API @Override protected JpaRepository<Foo, Long> getDao() { return dao; } // custom methods @Override public Foo retrieveByName(final String name) { return dao.retrieveByName(name); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/service/common/AbstractService.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/service/common/AbstractService.java
package com.baeldung.persistence.service.common; import java.io.Serializable; import java.util.List; import com.baeldung.persistence.IOperations; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.Lists; @Transactional public abstract class AbstractService<T extends Serializable> implements IOperations<T> { // read - one @Override @Transactional(readOnly = true) public T findOne(final long id) { return getDao().findById(id).orElse(null); } // read - all @Override @Transactional(readOnly = true) public List<T> findAll() { return Lists.newArrayList(getDao().findAll()); } // write @Override public T create(final T entity) { return getDao().save(entity); } @Override public T update(final T entity) { return getDao().save(entity); } protected abstract JpaRepository<T, Long> getDao(); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/model/Foo.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/model/Foo.java
package com.baeldung.persistence.model; import java.io.Serializable; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class Foo implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(nullable = false) private String name; public Foo() { super(); } public Foo(final String name) { super(); this.name = name; } // API public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } // @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Foo other = (Foo) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Foo [name=").append(name).append("]"); return builder.toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/model/User.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/persistence/model/User.java
package com.baeldung.persistence.model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; private String email; private int age; public User() { super(); } public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(final String username) { email = username; } public int getAge() { return age; } public void setAge(final int age) { this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final User user = (User) obj; return email.equals(user.email); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); return builder.toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/PersistenceConfig.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/PersistenceConfig.java
package com.baeldung.spring; import java.util.Properties; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) @ComponentScan({ "com.baeldung.persistence" }) // @ImportResource("classpath*:springDataPersistenceConfig.xml") @EnableJpaRepositories(basePackages = "com.baeldung.persistence.dao") public class PersistenceConfig { @Autowired private Environment env; public PersistenceConfig() { super(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); // vendorAdapter.set em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); return em; } @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); return dataSource; } @Bean public PlatformTransactionManager transactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); return hibernateProperties; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/Application.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/Application.java
package com.baeldung.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * Main Application Class - uses Spring Boot. Just run this as a normal Java * class to run up a Jetty Server (on http://localhost:8082/spring-rest-full) * */ @EnableAutoConfiguration @ComponentScan("com.baeldung") @SpringBootApplication public class Application { public static void main(final 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-rest-testing/src/main/java/com/baeldung/exceptiontesting/ExceptionTestingApplication.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/exceptiontesting/ExceptionTestingApplication.java
package com.baeldung.exceptiontesting; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; /** * Main Application Class - uses Spring Boot. Just run this as a normal Java * class to run up a Jetty Server (on http://localhost:8082/spring-rest-full) * */ @EnableScheduling @EnableAutoConfiguration @ComponentScan("com.baeldung.exceptiontesting") @SpringBootApplication public class ExceptionTestingApplication extends SpringBootServletInitializer { public static void main(final String[] args) { SpringApplication.run(ExceptionTestingApplication.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-rest-testing/src/main/java/com/baeldung/exceptiontesting/controller/ExceptionController.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/exceptiontesting/controller/ExceptionController.java
package com.baeldung.exceptiontesting.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.baeldung.exceptiontesting.exception.BadArgumentsException; import com.baeldung.exceptiontesting.exception.InternalException; import com.baeldung.exceptiontesting.exception.ResourceNotFoundException; @RestController public class ExceptionController { @GetMapping("/exception/{exception_id}") public void getSpecificException(@PathVariable("exception_id") String pException) { if("not_found".equals(pException)) { throw new ResourceNotFoundException("resource not found"); } else if("bad_arguments".equals(pException)) { throw new BadArgumentsException("bad arguments"); } else { throw new InternalException("internal error"); } } @GetMapping("/exception/throw") public void getException() throws Exception { throw new Exception("error"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/exceptiontesting/exception/InternalException.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/exceptiontesting/exception/InternalException.java
package com.baeldung.exceptiontesting.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @SuppressWarnings("serial") @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public class InternalException extends RuntimeException { public InternalException(String message) { super(message); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/exceptiontesting/exception/BadArgumentsException.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/exceptiontesting/exception/BadArgumentsException.java
package com.baeldung.exceptiontesting.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @SuppressWarnings("serial") @ResponseStatus(HttpStatus.BAD_REQUEST) public class BadArgumentsException extends RuntimeException { public BadArgumentsException(String message) { super(message); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/exceptiontesting/exception/ResourceNotFoundException.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/exceptiontesting/exception/ResourceNotFoundException.java
package com.baeldung.exceptiontesting.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @SuppressWarnings("serial") @ResponseStatus(HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/controller/FooController.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/controller/FooController.java
package com.baeldung.web.controller; import java.util.List; import jakarta.servlet.http.HttpServletResponse; import com.baeldung.persistence.model.Foo; import com.baeldung.persistence.service.IFooService; import com.baeldung.web.util.RestPreconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; 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.bind.annotation.ResponseStatus; import com.google.common.base.Preconditions; @Controller @RequestMapping(value = "/auth/foos") public class FooController { @Autowired private IFooService service; public FooController() { super(); } // API @RequestMapping(method = RequestMethod.GET, value = "/count") @ResponseBody @ResponseStatus(value = HttpStatus.OK) public long count() { return 2l; } // read - one @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); return resourceById; } // read - all @RequestMapping(method = RequestMethod.GET) @ResponseBody public List<Foo> findAll() { return service.findAll(); } // write @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { Preconditions.checkNotNull(resource); final Foo foo = service.create(resource); return foo; } @RequestMapping(method = RequestMethod.HEAD) @ResponseStatus(HttpStatus.OK) public void head(final HttpServletResponse resp) { resp.setContentType(MediaType.APPLICATION_JSON_VALUE); resp.setHeader("bar", "baz"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/controller/HomeController.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/controller/HomeController.java
package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping(value = "/") public class HomeController { public String index() { return "homepage"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/util/RestPreconditions.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/util/RestPreconditions.java
package com.baeldung.web.util; import com.baeldung.web.exception.MyResourceNotFoundException; import org.springframework.http.HttpStatus; /** * Simple static methods to be called at the start of your own methods to verify correct arguments and state. If the Precondition fails, an {@link HttpStatus} code is thrown */ public final class RestPreconditions { private RestPreconditions() { throw new AssertionError(); } // API /** * Check if some value was found, otherwise throw exception. * * @param expression * has value true if found, otherwise false * @throws MyResourceNotFoundException * if expression is false, means value not found. */ public static void checkFound(final boolean expression) { if (!expression) { throw new MyResourceNotFoundException(); } } /** * Check if some value was found, otherwise throw exception. * * @param resource * has value not null to be returned, otherwise throw exception * @throws MyResourceNotFoundException * if resource is null, means value not found. */ public static <T> T checkFound(final T resource) { if (resource == null) { throw new MyResourceNotFoundException(); } return resource; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java
spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java
package com.baeldung.web.exception; public final class MyResourceNotFoundException extends RuntimeException { public MyResourceNotFoundException() { super(); } public MyResourceNotFoundException(final String message, final Throwable cause) { super(message, cause); } public MyResourceNotFoundException(final String message) { super(message); } public MyResourceNotFoundException(final Throwable cause) { super(cause); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java
spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java
package com.baeldung.thymeleaf; import org.junit.Ignore; 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.thymeleaf.config.InitSecurity; import com.baeldung.thymeleaf.config.WebApp; import com.baeldung.thymeleaf.config.WebMVCConfig; import com.baeldung.thymeleaf.config.WebMVCSecurity; @Ignore @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.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-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsIntegrationTest.java
spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsIntegrationTest.java
package com.baeldung.thymeleaf.controller; import static org.hamcrest.Matchers.containsString; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpSession; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.baeldung.thymeleaf.config.InitSecurity; import com.baeldung.thymeleaf.config.WebApp; import com.baeldung.thymeleaf.config.WebMVCConfig; import com.baeldung.thymeleaf.config.WebMVCSecurity; import jakarta.servlet.Filter; @Ignore @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) public class FragmentsIntegrationTest { @Autowired WebApplicationContext wac; @Autowired MockHttpSession session; private MockMvc mockMvc; @Autowired private Filter springSecurityFilterChain; private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); } @Test public void whenAccessingFragmentsRoute_thenViewHasExpectedContent() throws Exception { this.mockMvc .perform(get("/fragments").with(testUser())) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("<title>Thymeleaf Fragments: home</title>"))); } @Test public void whenAccessingParamsRoute_thenViewHasExpectedContent() throws Exception { this.mockMvc .perform(get("/params").with(testUser())) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("<span>Name</span>"))); } @Test public void whenAccessingMarkupRoute_thenViewHasExpectedContent() throws Exception { this.mockMvc .perform(get("/markup").with(testUser())) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("<div class=\"another\">This is another sidebar</div>"))); } @Test public void whenAccessingOtherRoute_thenViewHasExpectedContent() throws Exception { this.mockMvc .perform(get("/other").with(testUser())) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("<td>John Smith</td>"))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java
spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java
package com.baeldung.thymeleaf.controller; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpSession; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.baeldung.thymeleaf.config.InitSecurity; import com.baeldung.thymeleaf.config.WebApp; import com.baeldung.thymeleaf.config.WebMVCConfig; import com.baeldung.thymeleaf.config.WebMVCSecurity; import jakarta.servlet.Filter; @Ignore @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) public class ExpressionUtilityObjectsControllerIntegrationTest { @Autowired WebApplicationContext wac; @Autowired MockHttpSession session; private MockMvc mockMvc; @Autowired private Filter springSecurityFilterChain; private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); } @Test public void testDates() throws Exception { mockMvc.perform(get("/dates").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("dates.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/src/test/java/com/baeldung/thymeleaf/controller/ControllerIntegrationTest.java
spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ControllerIntegrationTest.java
package com.baeldung.thymeleaf.controller; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.junit.Before; import org.junit.Ignore; 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.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.baeldung.thymeleaf.config.WebApp; import com.baeldung.thymeleaf.config.WebMVCConfig; import jakarta.servlet.Filter; @Ignore @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class}) public class ControllerIntegrationTest { @Autowired WebApplicationContext wac; private MockMvc mockMvc; @Autowired private Filter springSecurityFilterChain; private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); } @Test public void testTeachers() throws Exception { mockMvc.perform(get("/listTeachers").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("listTeachers.html")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java
spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java
package com.baeldung.thymeleaf.security.csrf; import com.baeldung.thymeleaf.config.InitSecurity; import com.baeldung.thymeleaf.config.WebApp; import com.baeldung.thymeleaf.config.WebMVCConfig; import com.baeldung.thymeleaf.config.WebMVCSecurity; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpSession; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import jakarta.servlet.Filter; @Ignore @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) public class CsrfEnabledIntegrationTest { @Autowired WebApplicationContext wac; @Autowired MockHttpSession session; private MockMvc mockMvc; @Autowired private Filter springSecurityFilterChain; private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); } @Test public void htmlInliningTest() throws Exception { mockMvc.perform(get("/html").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("inliningExample.html")); } @Test public void jsInliningTest() throws Exception { mockMvc.perform(get("/js").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("studentCheck.js")); } @Test public void plainInliningTest() throws Exception { mockMvc.perform(get("/plain").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("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/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java
spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java
package com.baeldung.thymeleaf.cssandjs; 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 static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.junit.Before; import org.junit.Ignore; 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.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @Ignore @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = CssAndJsApplication.class) public class CssAndJsControllerIntegrationTest { @Autowired private WebApplicationContext context; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); } @Test public void whenCalledGetStyledPage_thenReturnContent() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/styled-page")) .andExpect(status().isOk()) .andExpect(view().name("cssandjs/styledPage")) .andExpect(content().string(containsString("Carefully Styled Heading"))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/DatesController.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/DatesController.java
package com.baeldung.thymeleaf.controller; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; import com.baeldung.thymeleaf.model.Student; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class DatesController { @RequestMapping(value = "/dates", method = RequestMethod.GET) public String getInfo(Model model) { model.addAttribute("standardDate", new Date()); model.addAttribute("localDateTime", LocalDateTime.now()); model.addAttribute("localDate", LocalDate.now()); model.addAttribute("timestamp", Instant.now()); return "dates.html"; } @RequestMapping(value = "/saveStudent", method = RequestMethod.GET) public String displaySaveStudent(Model model) { model.addAttribute("student", new Student()); return "datePicker/saveStudent.html"; } @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) public String saveStudent(Model model, @ModelAttribute("student") Student student) { model.addAttribute("student", student); return "datePicker/displayDate.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/src/main/java/com/baeldung/thymeleaf/controller/FragmentsController.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/FragmentsController.java
package com.baeldung.thymeleaf.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import com.baeldung.thymeleaf.utils.StudentUtils; @Controller public class FragmentsController { @GetMapping("/fragments") public String getHome() { return "fragments.html"; } @GetMapping("/markup") public String markupPage() { return "markup.html"; } @GetMapping("/params") public String paramsPage() { return "params.html"; } @GetMapping("/other") public String otherPage(Model model) { model.addAttribute("data", StudentUtils.buildStudents()); return "other.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/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.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; import com.baeldung.thymeleaf.utils.StudentUtils; /** * Handles requests for the student model. * */ @Controller public class StudentController { @RequestMapping(value = "/listStudents", method = RequestMethod.GET) public String listStudent(Model model) { model.addAttribute("students", StudentUtils.buildStudents()); return "listStudents.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/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java
package com.baeldung.thymeleaf.controller; import com.baeldung.thymeleaf.utils.TeacherUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class TeacherController { @RequestMapping(value = "/listTeachers", method = RequestMethod.GET) public String getInfo(Model model) { model.addAttribute("teachers", TeacherUtils.buildTeachers()); return "listTeachers.html"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java
spring-web-modules/spring-thymeleaf/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/src/main/java/com/baeldung/thymeleaf/model/Teacher.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Teacher.java
package com.baeldung.thymeleaf.model; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotNull; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Teacher implements Serializable { private static final long serialVersionUID = 946941572942270450L; @NotNull(message = "Teacher ID is required.") @Min(value = 1000, message = "Teacher ID must be at least 4 digits.") private Integer id; @NotNull(message = "Teacher name is required.") private String name; @NotNull(message = "Teacher gender is required.") private String gender; private boolean isActive; private List<String> courses = new ArrayList<String>(); private String additionalSkills; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public boolean isActive() { return isActive; } public void setActive(boolean isActive) { this.isActive = isActive; } public List<String> getCourses() { return courses; } public void setCourses(List<String> courses) { this.courses = courses; } public String getAdditionalSkills() { return additionalSkills; } public void setAdditionalSkills(String additionalSkills) { this.additionalSkills = additionalSkills; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/errors/UserRepository.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/errors/UserRepository.java
package com.baeldung.thymeleaf.errors; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/errors/UserValidationService.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/errors/UserValidationService.java
package com.baeldung.thymeleaf.errors; import org.springframework.stereotype.Service; @Service public class UserValidationService { public String validateUser(User user) { String message = ""; if (user.getCountry() != null && user.getPhoneNumber() != null) { if (user.getCountry() .equalsIgnoreCase("India") && !user.getPhoneNumber() .startsWith("91")) { message = "Phone number is invalid for " + user.getCountry(); } } 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-thymeleaf/src/main/java/com/baeldung/thymeleaf/errors/User.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/errors/User.java
package com.baeldung.thymeleaf.errors; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotEmpty(message = "User's name cannot be empty.") @Size(min = 5, max = 250) private String fullName; @NotEmpty(message = "User's email cannot be empty.") @Size(min = 7, max = 320) private String email; @NotNull(message = "User's age cannot be null.") @Min(value = 18) private Integer age; private String country; private String phoneNumber; public Long getId() { return id; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public void setId(Long id) { this.id = id; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/errors/UserController.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/errors/UserController.java
package com.baeldung.thymeleaf.errors; import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @Controller public class UserController { @Autowired private UserRepository repository; @Autowired private UserValidationService validationService; @GetMapping("/add") public String showAddUserForm(User user) { return "errors/addUser"; } @PostMapping("/add") public String addUser(@Valid User user, BindingResult result, Model model) { String err = validationService.validateUser(user); if (!err.isEmpty()) { ObjectError error = new ObjectError("globalError", err); result.addError(error); } if (result.hasErrors()) { return "errors/addUser"; } repository.save(user); model.addAttribute("users", repository.findAll()); return "errors/home"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java
package com.baeldung.thymeleaf.formatter; import java.text.ParseException; import java.util.Locale; import org.springframework.format.Formatter; import org.thymeleaf.util.StringUtils; /** * * Name formatter class that implements the Spring Formatter interface. * Formats a name(String) and return the value with spaces replaced by commas. * */ public class NameFormatter implements Formatter<String> { @Override public String print(String input, Locale locale) { return formatName(input, locale); } @Override public String parse(String input, Locale locale) throws ParseException { return formatName(input, locale); } private String formatName(String input, Locale locale) { return StringUtils.replace(input, " ", ","); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/option/Student.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/option/Student.java
package com.baeldung.thymeleaf.option; import java.io.Serializable; 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; private Float percentage; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Character getGender() { return gender; } public void setGender(Character gender) { this.gender = gender; } public Float getPercentage() { return percentage; } public void setPercentage(Float percentage) { this.percentage = percentage; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/option/StudentFormController.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/option/StudentFormController.java
package com.baeldung.thymeleaf.option; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Handles requests for the student model. * */ @Controller public class StudentFormController { @RequestMapping(value = "/student", method = RequestMethod.GET) public String addStudent(Model model) { model.addAttribute("student", new Student()); return "option/studentForm.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/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java
spring-web-modules/spring-thymeleaf/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/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java
package com.baeldung.thymeleaf.utils; public class ArrayUtil { public static String[] array(String... args) { return 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/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java
package com.baeldung.thymeleaf.utils; import com.baeldung.thymeleaf.model.Teacher; import java.util.ArrayList; import java.util.List; public class TeacherUtils { private static List<Teacher> teachers = new ArrayList<Teacher>(); public static List<Teacher> buildTeachers() { if (teachers.isEmpty()) { Teacher teacher1 = new Teacher(); teacher1.setId(2001); teacher1.setName("Jane Doe"); teacher1.setGender("F"); teacher1.setActive(true); teacher1.getCourses().add("Mathematics"); teacher1.getCourses().add("Physics"); teachers.add(teacher1); Teacher teacher2 = new Teacher(); teacher2.setId(2002); teacher2.setName("Lazy Dude"); teacher2.setGender("M"); teacher2.setActive(false); teacher2.setAdditionalSkills("emergency responder"); teachers.add(teacher2); Teacher teacher3 = new Teacher(); teacher3.setId(2002); teacher3.setName("Micheal Jordan"); teacher3.setGender("M"); teacher3.setActive(true); teacher3.getCourses().add("Sports"); teachers.add(teacher3); } return teachers; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/dropDownList/DropDownListController.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/dropDownList/DropDownListController.java
package com.baeldung.thymeleaf.dropDownList; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.ArrayList; import java.util.List; @Controller public class DropDownListController { @RequestMapping(value = "/populateDropDownList", method = RequestMethod.GET) public String populateList(Model model) { List<String> options = new ArrayList<String>(); options.add("option 1"); options.add("option 2"); options.add("option 3"); options.add("option 4"); model.addAttribute("options", options); return "dropDownList/dropDownList.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/src/main/java/com/baeldung/thymeleaf/config/WebApp.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java
package com.baeldung.thymeleaf.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * Java configuration file that is used for web application initialization */ public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { public WebApp() { super(); } @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java
package com.baeldung.thymeleaf.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) public class WebMVCSecurity { @Bean public InMemoryUserDetailsManager userDetailsService() { UserDetails user = User.withUsername("user1") .password("{noop}user1Pass") .authorities("USER") .build(); return new InMemoryUserDetailsManager(user); } @Bean public WebSecurityCustomizer webSecurityCustomizer() { return web -> web.ignoring().requestMatchers("/resources/**"); } @Bean public SecurityFilterChain filterChain(final HttpSecurity http) throws Exception { return http.authorizeRequests().anyRequest().authenticated().and().build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java
package com.baeldung.thymeleaf.config; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class InitSecurity extends AbstractSecurityWebApplicationInitializer { public InitSecurity() { super(WebMVCSecurity.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java
package com.baeldung.thymeleaf.config; import java.util.Locale; import nz.net.ultraq.thymeleaf.LayoutDialect; import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect; import org.thymeleaf.spring6.ISpringTemplateEngine; import org.thymeleaf.spring6.SpringTemplateEngine; import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring6.view.ThymeleafViewResolver; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ITemplateResolver; import com.baeldung.thymeleaf.formatter.NameFormatter; import com.baeldung.thymeleaf.utils.ArrayUtil; @Configuration @EnableWebMvc @ComponentScan({ "com.baeldung.thymeleaf" }) /** * Java configuration file that is used for Spring MVC and Thymeleaf * configurations */ public class WebMVCConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Bean public ViewResolver htmlViewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine(htmlTemplateResolver())); resolver.setContentType("text/html"); resolver.setCharacterEncoding("UTF-8"); resolver.setViewNames(ArrayUtil.array("*.html")); return resolver; } @Bean public ViewResolver javascriptViewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver())); resolver.setContentType("application/javascript"); resolver.setCharacterEncoding("UTF-8"); resolver.setViewNames(ArrayUtil.array("*.js")); return resolver; } @Bean public ViewResolver plainViewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine(plainTemplateResolver())); resolver.setContentType("text/plain"); resolver.setCharacterEncoding("UTF-8"); resolver.setViewNames(ArrayUtil.array("*.txt")); return resolver; } private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.addDialect(new LayoutDialect(new GroupingStrategy())); engine.addDialect(new Java8TimeDialect()); engine.setTemplateResolver(templateResolver); engine.setTemplateEngineMessageSource(messageSource()); return engine; } private ITemplateResolver htmlTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/views/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.HTML); return resolver; } private ITemplateResolver javascriptTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/js/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.JAVASCRIPT); return resolver; } private ITemplateResolver plainTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/txt/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.TEXT); return resolver; } @Bean @Description("Spring Message Resolver") public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(new Locale("en")); return localeResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**", "/css/**") .addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/"); } @Override @Description("Custom Conversion Service") public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new NameFormatter()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java
package com.baeldung.thymeleaf.cssandjs; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CssAndJsApplication { public static void main(String[] args) { SpringApplication.run(CssAndJsApplication.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/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java
spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java
package com.baeldung.thymeleaf.cssandjs; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class CssAndJsController { @GetMapping("/styled-page") public String getStyledPage(Model model) { model.addAttribute("name", "Baeldung Reader"); return "cssandjs/styledPage"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/cache/CacheControlControllerIntegrationTest.java
spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/cache/CacheControlControllerIntegrationTest.java
package com.baeldung.cache; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.http.HttpHeaders.IF_UNMODIFIED_SINCE; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration(classes = {CacheWebConfig.class, CacheWebConfig.class}) public class CacheControlControllerIntegrationTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @BeforeEach void setup() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test void whenResponseBody_thenReturnCacheHeader() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/hello/baeldung")) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.header() .string("Cache-Control","max-age=60, must-revalidate, no-transform")); } @Test void whenViewName_thenReturnCacheHeader() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/home/baeldung")) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.header().string("Cache-Control","max-age=60, must-revalidate, no-transform")) .andExpect(MockMvcResultMatchers.view().name("home")); } @Test void whenStaticResources_thenReturnCacheHeader() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/resources/hello.css")) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.header().string("Cache-Control","max-age=60, must-revalidate, no-transform")); } @Test void whenInterceptor_thenReturnCacheHeader() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/login/baeldung")) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.header().string("Cache-Control","max-age=60, must-revalidate, no-transform")); } @Test void whenValidate_thenReturnCacheHeader() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.add(IF_UNMODIFIED_SINCE, "Tue, 04 Feb 2020 19:57:25 GMT"); this.mockMvc.perform(MockMvcRequestBuilders.get("/productInfo/baeldung").headers(headers)) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.status().is(304)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false