Adding spring-web-url

This commit is contained in:
anuragkumawat 2021-12-07 16:05:59 +05:30
parent 5c9e48a10f
commit 1862d8cce2
17 changed files with 535 additions and 3 deletions

View File

@ -7,10 +7,7 @@ This module contains articles about Spring MVC
- [A Custom Data Binder in Spring MVC](https://www.baeldung.com/spring-mvc-custom-data-binder)
- [Validating Lists in a Spring Controller](https://www.baeldung.com/spring-validate-list-controller)
- [Spring Validation Message Interpolation](https://www.baeldung.com/spring-validation-message-interpolation)
- [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url)
- [Using Enums as Request Parameters in Spring](https://www.baeldung.com/spring-enum-request-param)
- [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter)
- [Guide to Flash Attributes in a Spring Web Application](https://www.baeldung.com/spring-web-flash-attributes)
- [Handling URL Encoded Form Data in Spring REST](https://www.baeldung.com/spring-url-encoded-form-data)
- [Reading HttpServletRequest Multiple Times in Spring](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times)
- More articles: [[<-- prev]](/spring-mvc-basics-2)[[more -->]](/spring-mvc-basics-4)

View File

@ -0,0 +1,8 @@
## Spring Web URL
This module contains articles about Spring MVC
## Relevant articles:
- [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url)
- [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter)
- [Handling URL Encoded Form Data in Spring REST](https://www.baeldung.com/spring-url-encoded-form-data)

View File

@ -0,0 +1,138 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-web-url</artifactId>
<name>spring-web-url</name>
<packaging>war</packaging>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>${jpa.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.subethamail</groupId>
<artifactId>subethasmtp</artifactId>
<version>${subethasmtp.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/conf.properties</exclude>
</excludes>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>autoconfiguration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
</excludes>
<includes>
<include>**/AutoconfigurationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- The main class to start by executing java -jar -->
<start-class>com.baeldung.exclude_urls_filter.Application</start-class>
<jquery.version>3.1.1</jquery.version>
<bootstrap.version>3.3.7-1</bootstrap.version>
<jpa.version>2.2</jpa.version>
<guava.version>18.0</guava.version>
<subethasmtp.version>3.1.7</subethasmtp.version>
<httpclient.version>4.5.8</httpclient.version>
</properties>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.exclude_urls_filter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@ComponentScan(basePackages = "com.baeldung.exclude_urls_filter")
@Configuration
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.exclude_urls_filter.controller;
import com.baeldung.exclude_urls_filter.service.FAQService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FAQController {
private final FAQService faqService;
@Autowired
public FAQController(FAQService faqService) {
this.faqService = faqService;
}
@RequestMapping(value = "/faq/helpline", method = RequestMethod.GET)
public ResponseEntity<String> getHelpLineNumber() {
String helplineNumber = faqService.getHelpLineNumber();
if (helplineNumber != null) {
return new ResponseEntity<String>(helplineNumber, HttpStatus.OK);
} else {
return new ResponseEntity<String>("Unavailable", HttpStatus.NOT_FOUND);
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.exclude_urls_filter.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Ping {
@RequestMapping(value = "/health", method = RequestMethod.GET)
public ResponseEntity<String> pingGet() {
return new ResponseEntity<String>("pong", HttpStatus.OK);
}
@RequestMapping(value = "/health", method = RequestMethod.POST)
public ResponseEntity<String> pingPost() {
return new ResponseEntity<String>("pong", HttpStatus.OK);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.exclude_urls_filter.filter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterRegistrationConfig {
@Bean
public FilterRegistrationBean<LogFilter> logFilter() {
FilterRegistrationBean<LogFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new LogFilter());
registrationBean.addUrlPatterns("/health", "/faq/*");
return registrationBean;
}
@Bean
public FilterRegistrationBean<HeaderValidatorFilter> headerValidatorFilter() {
FilterRegistrationBean<HeaderValidatorFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new HeaderValidatorFilter());
registrationBean.addUrlPatterns("*");
return registrationBean;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.exclude_urls_filter.filter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Order(1)
public class HeaderValidatorFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException,
IOException {
String countryCode = request.getHeader("X-Country-Code");
if (!"US".equals(countryCode)) {
response.sendError(HttpStatus.BAD_REQUEST.value(), "Invalid Locale");
return;
}
filterChain.doFilter(request, response);
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
String path = request.getRequestURI();
return "/health".equals(path);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.exclude_urls_filter.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Order(1)
public class LogFilter extends OncePerRequestFilter {
private final Logger logger = LoggerFactory.getLogger(LogFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String path = request.getRequestURI();
String contentType = request.getContentType();
logger.info("Request URL path : {}, Request content type: {}", path, contentType);
filterChain.doFilter(request, response);
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.exclude_urls_filter.service;
public interface FAQService {
String getHelpLineNumber();
}

View File

@ -0,0 +1,15 @@
package com.baeldung.exclude_urls_filter.service;
import org.springframework.stereotype.Service;
@Service
public class FAQServiceImpl implements FAQService {
private static final String HELPLINE_NUMBER = "+1 888-777-66";
@Override
public String getHelpLineNumber() {
return HELPLINE_NUMBER;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.form_submission;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.form_submission.controllers;
import com.baeldung.form_submission.model.Feedback;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
@Controller
public class FeedbackForm {
@GetMapping(path = "/feedback")
public String getFeedbackForm(Model model) {
Feedback feedback = new Feedback();
model.addAttribute("feedback", feedback);
return "feedback";
}
@PostMapping(
path = "/web/feedback",
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public String handleBrowserSubmissions(Feedback feedback) throws Exception {
// Save feedback data
return "redirect:/feedback/success";
}
@GetMapping("/feedback/success")
public ResponseEntity<String> getSuccess() {
return new ResponseEntity<String>("Thank you for submitting feedback.", HttpStatus.OK);
}
@PostMapping(
path = "/feedback",
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public ResponseEntity<String> handleNonBrowserSubmissions(@RequestParam MultiValueMap paramMap) throws Exception {
// Save feedback data
return new ResponseEntity<String>("Thank you for submitting feedback", HttpStatus.OK);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.form_submission.model;
public class Feedback {
private String emailId;
private String comment;
public String getEmailId() {
return this.emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}

View File

@ -0,0 +1,7 @@
spring.mail.host=localhost
spring.mail.port=8025
spring.thymeleaf.cache=false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

View File

@ -0,0 +1,41 @@
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Poetry Contest: Submission</title>
</head>
<body>
<form action="#" method="post" th:action="@{/web/feedback}" th:object="${feedback}">
<table border='0' cellpadding='2' cellspacing='2' width='480px'>
<tr>
<td align='center'>
<label for="email">Email:</label>
</td>
<td>
<input th:field=*{emailId} type="text"/>
</td>
</tr>
<tr>
<td align='center'>
<label for="comment">Comment:</label>
</td>
<td>
<textarea cols="30" rows="30" th:field=*{comment}/>
</td>
</tr>
<tr>
<td align='center'>
<input type="submit" value="Submit Feedback">
</td>
</tr>
</table>
</form>
</body>
</html>

View File

@ -0,0 +1,87 @@
package com.baeldung.spring.slash;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.net.URI;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
@AutoConfigureMockMvc
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class SlashParsingControllerIntTest {
@Autowired
private MockMvc mockMvc;
@Test
public void whenUsingPathVariablemWithoutSlashes_thenStatusOk() throws Exception {
final String stringWithoutSlashes = "noslash";
MvcResult mvcResult = mockMvc.perform(get("/slash/mypaths/" + stringWithoutSlashes))
.andExpect(status().isOk())
.andReturn();
assertEquals(stringWithoutSlashes, mvcResult.getResponse()
.getContentAsString());
}
@Test
public void whenUsingPathVariableWithSlashes_thenStatusNotFound() throws Exception {
final String stringWithSlashes = "url/with/slashes";
mockMvc.perform(get("/slash/mypaths/" + stringWithSlashes))
.andExpect(status().isNotFound());
}
@Test
public void givenAllFallbackEndpoint_whenUsingPathWithSlashes_thenStatusOk() throws Exception {
final String stringWithSlashes = "url/for/testing/purposes";
MvcResult mvcResult = mockMvc.perform(get("/slash/all/" + stringWithSlashes))
.andExpect(status().isOk())
.andReturn();
assertEquals(stringWithSlashes, mvcResult.getResponse()
.getContentAsString());
}
@Test
public void givenAllFallbackEndpoint_whenUsingConsecutiveSlashes_thenPathNormalized() throws Exception {
final String stringWithSlashes = "http://myurl.com";
MvcResult mvcResult = mockMvc.perform(get("/slash/all/" + stringWithSlashes))
.andExpect(status().isOk())
.andReturn();
String stringWithSlashesNormalized = URI.create("/slash/all/" + stringWithSlashes)
.normalize()
.toString()
.split("/slash/all/")[1];
assertEquals(stringWithSlashesNormalized, mvcResult.getResponse()
.getContentAsString());
}
@Test
public void whenUsingSlashesInQueryParam_thenParameterAccepted() throws Exception {
final String stringWithSlashes = "url/for////testing/purposes";
MvcResult mvcResult = mockMvc.perform(get("/slash/all").param("param", stringWithSlashes))
.andExpect(status().isOk())
.andReturn();
assertEquals(stringWithSlashes, mvcResult.getResponse()
.getContentAsString());
}
}