JAVA-84: Move articles out of spring-boot part 1 (#9950)

* JAVA-84: Moved 1 article to spring-boot-actuator

* JAVA-84: Moved 2 articles to spring-boot-mvc

* JAVA-84: README changes for spring-boot module

* JAVA-84: Moved classes to com.baeldung pkg to correct compilation issue
This commit is contained in:
Sampada
2020-08-31 20:41:47 +05:30
committed by GitHub
parent 8cf889d27e
commit e0ebf5904f
29 changed files with 181 additions and 36 deletions
@@ -8,12 +8,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring)
- [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan)
- [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet)
- [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils)
- [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization)
- [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation)
- [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom)
- [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions)
- [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class)
- [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer)
@@ -1,25 +0,0 @@
package com.baeldung.annotation.servletcomponentscan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* using the following annotations are equivalent:
* <ul><li>
* <code>@ServletComponentScan</code>
* </li><li>
* <code>@ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components")</code>
* </li><li>
* <code>@ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class})</code>
* </li></ul>
*/
@SpringBootApplication
@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components")
public class SpringBootAnnotatedApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootAnnotatedApp.class, args);
}
}
@@ -1,13 +0,0 @@
package com.baeldung.annotation.servletcomponentscan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components")
public class SpringBootPlainApp {
public static void main(String[] args) {
}
}
@@ -1,21 +0,0 @@
package com.baeldung.annotation.servletcomponentscan.components;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AttrListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
servletContextEvent.getServletContext().setAttribute("servlet-context-attr", "test");
System.out.println("context init");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("context destroy");
}
}
@@ -1,27 +0,0 @@
package com.baeldung.annotation.servletcomponentscan.components;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
@WebServlet(name = "echo servlet", urlPatterns = "/echo")
public class EchoServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
Path path = File.createTempFile("echo", "tmp").toPath();
Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
Files.copy(path, response.getOutputStream());
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -1,30 +0,0 @@
package com.baeldung.annotation.servletcomponentscan.components;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;
@WebFilter(urlPatterns = "/hello", description = "a filter for hello servlet", initParams = { @WebInitParam(name = "msg", value = "filtering ") }, filterName = "hello filter", servletNames = { "echo servlet" })
public class HelloFilter implements Filter {
private FilterConfig filterConfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("filter init");
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletResponse.getOutputStream().print(filterConfig.getInitParameter("msg"));
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("filter destroy");
}
}
@@ -1,30 +0,0 @@
package com.baeldung.annotation.servletcomponentscan.components;
import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello") })
public class HelloServlet extends HttpServlet {
private ServletConfig servletConfig;
@Override
public void init(ServletConfig servletConfig) {
this.servletConfig = servletConfig;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
response.getOutputStream().write(servletConfig.getInitParameter("msg").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -1,26 +0,0 @@
package com.baeldung.endpoints.info;
import java.util.HashMap;
import java.util.Map;
import com.baeldung.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;
@Component
public class TotalUsersInfoContributor implements InfoContributor {
@Autowired
UserRepository userRepository;
@Override
public void contribute(Info.Builder builder) {
Map<String, Integer> userDetails = new HashMap<>();
userDetails.put("active", userRepository.countByStatus(1));
userDetails.put("inactive", userRepository.countByStatus(0));
builder.withDetail("users", userDetails);
}
}
@@ -1,14 +0,0 @@
package com.baeldung.internationalization;
import javax.annotation.security.RolesAllowed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class InternationalizationApp {
@RolesAllowed("*")
public static void main(String[] args) {
SpringApplication.run(InternationalizationApp.class, args);
}
}
@@ -1,36 +0,0 @@
package com.baeldung.internationalization.config;
import java.util.Locale;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
@Configuration
@ComponentScan(basePackages = "com.baeldung.internationalization.config")
public class MvcConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US);
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
@@ -1,14 +0,0 @@
package com.baeldung.internationalization.config;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class PageController {
@GetMapping("/international")
public String getInternationalPage() {
return "international";
}
}
@@ -21,12 +21,6 @@ spring.jmx.enabled=true
## for pretty printing of json when endpoints accessed over HTTP
http.mappers.jsonPrettyPrint=true
## Configuring info endpoint
info.app.name=Spring Sample Application
info.app.description=This is my first spring boot application G1
info.app.version=1.0.0
info.java-vendor = ${java.specification.vendor}
logging.level.org.springframework=INFO
#Servlet Configuration
@@ -1,4 +0,0 @@
greeting=Hello! Welcome to our website!
lang.change=Change the language
lang.eng=English
lang.fr=French
@@ -1,4 +0,0 @@
greeting=Bonjour! Bienvenue sur notre site!
lang.change=Changez la langue
lang.eng=Anglais
lang.fr=Francais
@@ -1,8 +0,0 @@
$(document).ready(function() {
$("#locales").change(function () {
var selectedOption = $('#locales').val();
if (selectedOption != ''){
window.location.replace('international?lang=' + selectedOption);
}
});
});
@@ -1,20 +0,0 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1" />
<title>Home</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="internationalization.js"></script>
</head>
<body>
<h1 th:text="#{greeting}"></h1>
<br /><br />
<span th:text="#{lang.change}"></span>:
<select id="locales">
<option value=""></option>
<option value="en" th:text="#{lang.eng}"></option>
<option value="fr" th:text="#{lang.fr}"></option>
</select>
</body>
</html>
@@ -1,61 +0,0 @@
package com.baeldung.annotation.servletcomponentscan;
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.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class)
public class SpringBootWithServletComponentIntegrationTest {
@Autowired
private ServletContext servletContext;
@Test
public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() {
assertNotNull(servletContext);
assertNotNull(servletContext.getAttribute("servlet-context-attr"));
assertEquals("test", servletContext.getAttribute("servlet-context-attr"));
}
@Test
public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() {
assertNotNull(servletContext);
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNotNull(filterRegistration);
assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet"));
}
@Autowired
private TestRestTemplate restTemplate;
@Test
public void givenServletFilter_whenGetHello_thenRequestFiltered() {
ResponseEntity<String> responseEntity = this.restTemplate.getForEntity("/hello", String.class);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertEquals("filtering hello", responseEntity.getBody());
}
@Test
public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() {
ResponseEntity<String> responseEntity = this.restTemplate.postForEntity("/echo", "echo", String.class);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertEquals("filtering echo", responseEntity.getBody());
}
}
@@ -1,49 +0,0 @@
package com.baeldung.annotation.servletcomponentscan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class)
public class SpringBootWithoutServletComponentIntegrationTest {
@Autowired
private ServletContext servletContext;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void givenServletContext_whenAccessAttrs_thenNotFound() {
assertNull(servletContext.getAttribute("servlet-context-attr"));
}
@Test
public void givenServletFilter_whenGetHello_thenEndpointNotFound() {
ResponseEntity<String> responseEntity = this.restTemplate.getForEntity("/hello", String.class);
assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
}
@Test
public void givenServletContext_whenCheckFilterMappings_thenEmpty() {
assertNotNull(servletContext);
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNull(filterRegistration);
}
}