remove boot from spring-mvc-java

This commit is contained in:
Loredana Crusoveanu
2018-09-09 19:00:01 +03:00
parent 0469d6f63f
commit a056937a4f
37 changed files with 1738 additions and 346 deletions

View File

@@ -1,20 +0,0 @@
package com.baeldung.annotations;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.annotation.DependsOn;
@DependsOn
public class Bike implements Vehicle {
private String color;
@Required
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}

View File

@@ -1,24 +0,0 @@
package com.baeldung.annotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class Biker {
@Autowired
@Qualifier("bike")
private Vehicle vehicle;
@Autowired
public Biker(@Qualifier("bike") Vehicle vehicle) {
this.vehicle = vehicle;
}
@Autowired
public void setVehicle(@Qualifier("bike") Vehicle vehicle) {
this.vehicle = vehicle;
}
}

View File

@@ -1,30 +0,0 @@
package com.baeldung.annotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Component
@Primary
@DependsOn("engine")
public class Car implements Vehicle {
@Autowired
private Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
@Autowired
public void setEngine(Engine engine) {
this.engine = engine;
}
public Engine getEngine() {
return engine;
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.annotations;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
@Lazy
public class CarMechanic {
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.annotations;
import org.springframework.stereotype.Component;
@Component
public class CarUtility {
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.annotations;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public class CustomException extends RuntimeException {
}

View File

@@ -1,62 +0,0 @@
package com.baeldung.annotations;
import java.io.IOException;
import java.time.Year;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/customResponse")
public class CustomResponseController {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}
@GetMapping("/age")
public ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
if (isInFuture(yearOfBirth)) {
return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>("Your age is " + calculateAge(yearOfBirth), HttpStatus.OK);
}
private int calculateAge(int yearOfBirth) {
return currentYear() - yearOfBirth;
}
private boolean isInFuture(int year) {
return currentYear() < year;
}
private int currentYear() {
return Year.now().getValue();
}
@GetMapping("/customHeader")
public ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");
return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK);
}
@GetMapping("/manual")
public void manual(HttpServletResponse response) throws IOException {
response.setHeader("Custom-Header", "foo");
response.setStatus(200);
response.getWriter()
.println("Hello World!");
}
}

View File

@@ -1,52 +0,0 @@
package com.baeldung.annotations;
import java.time.Year;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/customResponseWithBuilder")
public class CustomResponseWithBuilderController {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return ResponseEntity.ok("Hello World!");
}
@GetMapping("/age")
public ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
if (isInFuture(yearOfBirth)) {
return ResponseEntity.badRequest()
.body("Year of birth cannot be in the future");
}
return ResponseEntity.status(HttpStatus.OK)
.body("Your age is " + calculateAge(yearOfBirth));
}
private int calculateAge(int yearOfBirth) {
return currentYear() - yearOfBirth;
}
private boolean isInFuture(int year) {
return currentYear() < year;
}
private int currentYear() {
return Year.now()
.getValue();
}
@GetMapping("/customHeader")
public ResponseEntity<String> customHeader() {
return ResponseEntity.ok()
.header("Custom-Header", "foo")
.body("Custom header set");
}
}

View File

@@ -1,32 +0,0 @@
package com.baeldung.annotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Driver {
@Autowired
private Vehicle vehicle;
@Autowired
public Driver(Vehicle vehicle) {
this.vehicle = vehicle;
}
@Autowired
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
public Vehicle getVehicle() {
return vehicle;
}
@Scheduled(fixedRate = 10000)
@Scheduled(cron = "0 * * * * MON-FRI")
public void checkVehicle() {
}
}

View File

@@ -1,26 +0,0 @@
package com.baeldung.annotations;
import org.springframework.beans.factory.annotation.Value;
public class Engine {
@Value("8")
private int cylinderCount;
@Value("${engine.fuelType}")
private String fuelType;
public Engine() {
this(8);
}
public Engine(@Value("8") int cylinderCount) {
this.cylinderCount = cylinderCount;
}
@Value("8")
public void setCylinderCount(int cylinderCount) {
this.cylinderCount = cylinderCount;
}
}

View File

@@ -1,4 +0,0 @@
package com.baeldung.annotations;
public interface Vehicle {
}

View File

@@ -1,66 +0,0 @@
package com.baeldung.annotations;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
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;
@Controller
@RequestMapping(value = "/vehicles", method = RequestMethod.GET)
public class VehicleController {
@CrossOrigin
@ResponseBody
@RequestMapping("/hello")
public String hello() {
return "Hello World!";
}
@RequestMapping("/home")
public String home() {
return "home";
}
@PostMapping("/save")
public void saveVehicle(@RequestBody Vehicle vehicle) {
}
@RequestMapping("/{id}")
public Vehicle getVehicle(@PathVariable("id") long id) {
return null;
}
@RequestMapping
public Vehicle getVehicleByParam(@RequestParam("id") long id) {
return null;
}
@RequestMapping("/buy")
public Car buyCar(@RequestParam(defaultValue = "5") int seatCount) {
return null;
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void onIllegalArgumentException(IllegalArgumentException exception) {
}
@PostMapping("/assemble")
public void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicle) {
}
@ModelAttribute("vehicle")
public Vehicle getVehicle() {
return null;
}
}

View File

@@ -1,13 +0,0 @@
package com.baeldung.annotations;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// @SpringBootApplication
public class VehicleFactoryApplication {
// public static void main(String[] args) {
// SpringApplication.run(VehicleFactoryApplication.class, args);
// }
}

View File

@@ -1,30 +0,0 @@
package com.baeldung.annotations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan(basePackages = "com.baeldung.annotations")
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
@ImportResource("classpath:/annotations.xml")
@PropertySource("classpath:/annotations.properties")
@Lazy
@EnableAutoConfiguration
@EnableAsync
@EnableScheduling
public class VehicleFactoryConfig {
@Bean
@Lazy(false)
public Engine engine() {
return new Engine();
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.annotations;
import org.springframework.stereotype.Repository;
@Repository
public class VehicleRepository {
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.annotations;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class VehicleRestController {
}

View File

@@ -1,13 +0,0 @@
package com.baeldung.annotations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class VehicleService {
@Async
public void repairCar() {
}
}

View File

@@ -1,17 +0,0 @@
package com.baeldung.app;
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;
@EnableAutoConfiguration
@ComponentScan(value = {"com.baeldung.web.controller"}, resourcePattern = "**/FileUploadController.class")
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@@ -14,13 +14,20 @@ public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("org.baeldung.config");
context.scan("com.baeldung");
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container.addServlet("java-servlet", new DispatcherServlet(context));
ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/java-servlet/*");
dispatcher.addMapping("/");
// final MultipartConfigElement multipartConfigElement = new
// MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE,
// MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2);
//
// appServlet.setMultipartConfig(multipartConfigElement);
}
}

View File

@@ -1,23 +0,0 @@
package com.baeldung.rss;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Spring Boot launcher for an application which exposes an RSS Feed.
*
* @author Donato Rimenti
*
*/
@SpringBootApplication
public class RssFeedApplication {
/**
* Launches a Spring Boot application which exposes an RSS Feed.
*
* @param args null
*/
public static void main(final String[] args) {
SpringApplication.run(RssFeedApplication.class, args);
}
}

View File

@@ -1,32 +0,0 @@
package com.baeldung.rss;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.View;
/**
* REST Controller which returns an RSS Feed created by {@link RssFeedView}.
*
* @author Donato Rimenti
*
*/
@RestController
public class RssFeedController {
/**
* View used by this controller.
*/
@Autowired
private RssFeedView view;
/**
* Returns an RSS Feed created by {@link #view}.
*
* @return an RSS Feed
*/
@GetMapping("/rss")
public View getFeed() {
return view;
}
}

View File

@@ -1,98 +0,0 @@
package com.baeldung.rss;
import java.sql.Date;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.feed.AbstractRssFeedView;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Item;
/**
* View for a RSS feed.
*
* @author Donato Rimenti
*/
@Component
public class RssFeedView extends AbstractRssFeedView {
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.view.feed.AbstractFeedView#
* buildFeedMetadata(java.util.Map, com.rometools.rome.feed.WireFeed,
* javax.servlet.http.HttpServletRequest)
*/
@Override
protected void buildFeedMetadata(Map<String, Object> model, Channel feed, HttpServletRequest request) {
feed.setTitle("Baeldung RSS Feed");
feed.setDescription("Learn how to program in Java");
feed.setLink("http://www.baeldung.com");
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.view.feed.AbstractRssFeedView#
* buildFeedItems(java.util.Map, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) {
// Builds the single entries.
Item entryOne = new Item();
entryOne.setTitle("JUnit 5 @Test Annotation");
entryOne.setAuthor("donatohan.rimenti@gmail.com");
entryOne.setLink("http://www.baeldung.com/junit-5-test-annotation");
entryOne.setPubDate(Date.from(Instant.parse("2017-12-19T00:00:00Z")));
Item entryTwo = new Item();
entryTwo.setTitle("Creating and Configuring Jetty 9 Server in Java");
entryTwo.setAuthor("donatohan.rimenti@gmail.com");
entryTwo.setLink("http://www.baeldung.com/jetty-java-programmatic");
entryTwo.setPubDate(Date.from(Instant.parse("2018-01-23T00:00:00Z")));
Item entryThree = new Item();
entryThree.setTitle("Flyweight Pattern in Java");
entryThree.setAuthor("donatohan.rimenti@gmail.com");
entryThree.setLink("http://www.baeldung.com/java-flyweight");
entryThree.setPubDate(Date.from(Instant.parse("2018-02-01T00:00:00Z")));
Item entryFour = new Item();
entryFour.setTitle("Multi-Swarm Optimization Algorithm in Java");
entryFour.setAuthor("donatohan.rimenti@gmail.com");
entryFour.setLink("http://www.baeldung.com/java-multi-swarm-algorithm");
entryFour.setPubDate(Date.from(Instant.parse("2018-03-09T00:00:00Z")));
Item entryFive = new Item();
entryFive.setTitle("A Simple Tagging Implementation with MongoDB");
entryFive.setAuthor("donatohan.rimenti@gmail.com");
entryFive.setLink("http://www.baeldung.com/mongodb-tagging");
entryFive.setPubDate(Date.from(Instant.parse("2018-03-27T00:00:00Z")));
Item entrySix = new Item();
entrySix.setTitle("Double-Checked Locking with Singleton");
entrySix.setAuthor("donatohan.rimenti@gmail.com");
entrySix.setLink("http://www.baeldung.com/java-singleton-double-checked-locking");
entrySix.setPubDate(Date.from(Instant.parse("2018-04-23T00:00:00Z")));
Item entrySeven = new Item();
entrySeven.setTitle("Introduction to Dagger 2");
entrySeven.setAuthor("donatohan.rimenti@gmail.com");
entrySeven.setLink("http://www.baeldung.com/dagger-2");
entrySeven.setPubDate(Date.from(Instant.parse("2018-06-30T00:00:00Z")));
// Creates the feed.
return Arrays.asList(entryOne, entryTwo, entryThree, entryFour, entryFive, entrySix, entrySeven);
}
}

View File

@@ -1,36 +0,0 @@
package com.baeldung.spring.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.baeldung.web.controller" })
public class ApplicationConfig extends WebMvcConfigurerAdapter {
public ApplicationConfig() {
super();
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/").setViewName("index");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/jsp/");
bean.setSuffix(".jsp");
return bean;
}
}

View File

@@ -1,89 +0,0 @@
package com.baeldung.spring.web.config;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
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.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
@EnableWebMvc
@Configuration
public class ClientWebConfig implements WebMvcConfigurer {
public ClientWebConfig() {
super();
}
// API
@Autowired
private ServletContext ctx;
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver thymeleafViewResolver() {
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
return viewResolver;
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
@Bean
@Description("Thymeleaf template resolver serving HTML 5")
public ServletContextTemplateResolver templateResolver() {
final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
}
@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
@Description("Spring message resolver")
public MessageSource messageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}

View File

@@ -1,46 +0,0 @@
package com.baeldung.spring.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
public class ContentManagementWebConfig extends WebMvcConfigurerAdapter {
public ContentManagementWebConfig() {
super();
}
// API
@Override
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useJaf(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json",
MediaType.APPLICATION_JSON);
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
}

View File

@@ -1,48 +0,0 @@
package com.baeldung.spring.web.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.util.Set;
public class MainWebAppInitializer implements WebApplicationInitializer {
private static final String TMP_FOLDER = "/tmp";
private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB
/**
* Register and configure all Servlet container components necessary to power the web application.
*/
@Override
public void onStartup(final ServletContext sc) throws ServletException {
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.scan("com.baeldung.spring.web.config");
// root.getEnvironment().setDefaultProfiles("embedded");
sc.addListener(new ContextLoaderListener(root));
// Handles requests into the application
final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
// final MultipartConfigElement multipartConfigElement = new
// MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE,
// MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2);
//
// appServlet.setMultipartConfig(multipartConfigElement);
final Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
}
}
}

View File

@@ -3,40 +3,105 @@ package com.baeldung.spring.web.config;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
import org.springframework.web.servlet.view.XmlViewResolver;
import org.springframework.web.util.UrlPathHelper;
import com.baeldung.excel.*;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import com.baeldung.excel.ExcelPOIHelper;
@Configuration
@EnableWebMvc
@ComponentScan("com.baeldung.web")
public class WebConfig extends WebMvcConfigurerAdapter {
@Configuration
@ComponentScan(basePackages = { "com.baeldung.web.controller" })
public class WebConfig implements WebMvcConfigurer {
public WebConfig() {
super();
@Autowired
private ServletContext ctx;
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
@Bean
public ViewResolver thymeleafViewResolver() {
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
return viewResolver;
}
// @Bean
// public StandardServletMultipartResolver multipartResolver() {
// return new StandardServletMultipartResolver();
// }
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
@Bean
@Description("Thymeleaf template resolver serving HTML 5")
public ServletContextTemplateResolver templateResolver() {
final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
}
@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
@Description("Spring message resolver")
public MessageSource messageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useRegisteredExtensionsOnly(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json",
MediaType.APPLICATION_JSON);
}
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
@@ -45,23 +110,7 @@ public class WebConfig extends WebMvcConfigurerAdapter {
return multipartResolver;
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver internalResourceViewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(2);
return bean;
}
@Bean
public ViewResolver xmlViewResolver() {
final XmlViewResolver bean = new XmlViewResolver();
@@ -112,5 +161,4 @@ public class WebConfig extends WebMvcConfigurerAdapter {
public ExcelPOIHelper excelPOIHelper() {
return new ExcelPOIHelper();
}
}
}

View File

@@ -2,13 +2,13 @@ package com.baeldung.spring.web.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(final MessageBrokerRegistry config) {

View File

@@ -6,9 +6,9 @@ import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
import javax.servlet.http.HttpSession;
@@ -16,7 +16,7 @@ import java.util.Map;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketSendToUserConfig extends AbstractWebSocketMessageBrokerConfigurer {
public class WebSocketSendToUserConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {

View File

@@ -0,0 +1,13 @@
package com.baeldung.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class SampleController {
@GetMapping("/sample")
public String showForm() {
return "sample";
}
}

View File

@@ -1,62 +0,0 @@
package com.baeldung.rss;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
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;
/**
* Test for {@link RssFeedApplication}.
*
* @author Donato Rimenti
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = RssFeedApplication.class)
public class RssFeedUnitTest {
/**
* Application context.
*/
@Autowired
private WebApplicationContext context;
/**
* Mock to perform tests on Spring Web Controller.
*/
private MockMvc mvc;
/**
* Sets the test up.
*/
@Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).build();
}
/**
* Calls the RSS feed endpoint and checks that the result matches an
* expected one.
*
* @throws Exception
*/
@Test
public void givenRssFeed_whenComparedWithExisting_thenEquals() throws Exception {
// The expected response.
String expectedResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss version=\"2.0\"> <channel> <title>Baeldung RSS Feed</title> <link>http://www.baeldung.com</link> <description>Learn how to program in Java</description> <item> <title>JUnit 5 @Test Annotation</title> <link>http://www.baeldung.com/junit-5-test-annotation</link> <pubDate>Tue, 19 Dec 2017 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>Creating and Configuring Jetty 9 Server in Java</title> <link>http://www.baeldung.com/jetty-java-programmatic</link> <pubDate>Tue, 23 Jan 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>Flyweight Pattern in Java</title> <link>http://www.baeldung.com/java-flyweight</link> <pubDate>Thu, 01 Feb 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>Multi-Swarm Optimization Algorithm in Java</title> <link>http://www.baeldung.com/java-multi-swarm-algorithm</link> <pubDate>Fri, 09 Mar 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>A Simple Tagging Implementation with MongoDB</title> <link>http://www.baeldung.com/mongodb-tagging</link> <pubDate>Tue, 27 Mar 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>Double-Checked Locking with Singleton</title> <link>http://www.baeldung.com/java-singleton-double-checked-locking</link> <pubDate>Mon, 23 Apr 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> <item> <title>Introduction to Dagger 2</title> <link>http://www.baeldung.com/dagger-2</link> <pubDate>Sat, 30 Jun 2018 00:00:00 GMT</pubDate> <author>donatohan.rimenti@gmail.com</author> </item> </channel></rss>";
// Performs a post against the RSS feed endpoint and checks that the
// result is equals to the expected one.
mvc.perform(MockMvcRequestBuilders.get("/rss")).andExpect(status().isOk())
.andExpect(content().xml(expectedResult));
}
}

View File

@@ -20,12 +20,12 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.spring.web.config.ApplicationConfig;
import com.baeldung.spring.web.config.WebConfig;
import com.baeldung.spring.web.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { ApplicationConfig.class, WebConfig.class })
@ContextConfiguration(classes = { WebConfig.class, WebConfig.class })
public class GreetControllerIntegrationTest {
@Autowired