Refactor Velocity example

This commit is contained in:
Grzegorz Piwowarek 2016-07-26 09:22:36 +03:00
parent 09d6e1852f
commit bf78a04b68
7 changed files with 134 additions and 160 deletions

View File

@ -1,29 +1,24 @@
package com.baeldung.mvc.velocity.controller; package com.baeldung.mvc.velocity.controller;
import java.util.List; import com.baeldung.mvc.velocity.domain.Tutorial;
import com.baeldung.mvc.velocity.service.ITutorialsService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import com.baeldung.mvc.velocity.domain.Tutorial; import java.util.List;
import com.baeldung.mvc.velocity.service.ITutorialsService;
@Controller @Controller @RequestMapping("/") public class MainController {
@RequestMapping("/")
public class MainController {
private final ITutorialsService tutService; private final ITutorialsService tutService;
@Autowired @Autowired public MainController(ITutorialsService tutService) {
public MainController(ITutorialsService tutService) {
this.tutService = tutService; this.tutService = tutService;
} }
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET) public String listTutorialsPage(Model model) {
public String listTutorialsPage(Model model) {
List<Tutorial> list = tutService.listTutorials(); List<Tutorial> list = tutService.listTutorials();
model.addAttribute("tutorials", list); model.addAttribute("tutorials", list);
return "index"; return "index";

View File

@ -30,5 +30,4 @@ public class Tutorial {
return author; return author;
} }
} }

View File

@ -1,25 +1,23 @@
package com.baeldung.mvc.velocity.spring.config; package com.baeldung.mvc.velocity.spring.config;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer; import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet; 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 { public class MainWebAppInitializer implements WebApplicationInitializer {
/** /**
* Register and configure all Servlet container components necessary to * Register and configure all Servlet container components necessary to
* power the web application. * power the web application.
*/ */
@Override @Override public void onStartup(final ServletContext sc) throws ServletException {
public void onStartup(final ServletContext sc) throws ServletException {
// Create the 'root' Spring application context // Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
@ -29,15 +27,12 @@ public class MainWebAppInitializer implements WebApplicationInitializer {
sc.addListener(new ContextLoaderListener(root)); sc.addListener(new ContextLoaderListener(root));
// Handles requests into the application // Handles requests into the application
final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1); appServlet.setLoadOnStartup(1);
final Set<String> mappingConflicts = appServlet.addMapping("/"); final Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) { if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " 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");
+ "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

@ -5,11 +5,9 @@ import org.springframework.context.annotation.Configuration;
import com.baeldung.mvc.velocity.service.TutorialsService; import com.baeldung.mvc.velocity.service.TutorialsService;
@Configuration @Configuration public class SpringConfig {
public class SpringConfig {
@Bean @Bean public TutorialsService tutService() {
public TutorialsService tutService(){
return new TutorialsService(); return new TutorialsService();
} }
} }

View File

@ -11,27 +11,21 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
import org.springframework.web.servlet.view.velocity.VelocityConfigurer; import org.springframework.web.servlet.view.velocity.VelocityConfigurer;
import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
@Configuration @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller" }) public class WebConfig extends WebMvcConfigurerAdapter {
@EnableWebMvc
@ComponentScan(basePackages={"com.baeldung.mvc.velocity.controller"})
public class WebConfig extends WebMvcConfigurerAdapter {
public WebConfig() { public WebConfig() {
super(); super();
} }
@Override @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
} }
@Override @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable(); configurer.enable();
} }
@Bean @Bean public ViewResolver viewResolver() {
public ViewResolver viewResolver() {
final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver(); final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
bean.setCache(true); bean.setCache(true);
bean.setPrefix("/WEB-INF/views/"); bean.setPrefix("/WEB-INF/views/");
@ -40,8 +34,7 @@ public class WebConfig extends WebMvcConfigurerAdapter {
return bean; return bean;
} }
@Bean @Bean public VelocityConfigurer velocityConfig() {
public VelocityConfigurer velocityConfig() {
VelocityConfigurer velocityConfigurer = new VelocityConfigurer(); VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
velocityConfigurer.setResourceLoaderPath("/"); velocityConfigurer.setResourceLoaderPath("/");
return velocityConfigurer; return velocityConfigurer;

View File

@ -1,18 +1,9 @@
package com.baeldung.mvc.velocity.test; package com.baeldung.mvc.velocity.test;
import static org.hamcrest.Matchers.allOf; import com.baeldung.mvc.velocity.domain.Tutorial;
import static org.hamcrest.Matchers.hasItem; import com.baeldung.mvc.velocity.service.ITutorialsService;
import static org.hamcrest.Matchers.hasProperty; import com.baeldung.mvc.velocity.spring.config.WebConfig;
import static org.hamcrest.Matchers.hasSize; import com.baeldung.mvc.velocity.test.config.TestConfig;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath;
import java.util.Arrays;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -25,48 +16,58 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import com.baeldung.mvc.velocity.domain.Tutorial; import java.util.Arrays;
import com.baeldung.mvc.velocity.service.ITutorialsService;
import com.baeldung.mvc.velocity.spring.config.WebConfig; import static org.hamcrest.Matchers.allOf;
import com.baeldung.mvc.velocity.test.config.TestConfig; import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(locations = {"classpath:mvc-servlet.xml"}) // @ContextConfiguration(locations = {"classpath:mvc-servlet.xml"})
@ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) @ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) @WebAppConfiguration public class DataContentControllerTest {
@WebAppConfiguration
public class DataContentControllerTest {
private MockMvc mockMvc; private MockMvc mockMvc;
@Autowired @Autowired private ITutorialsService tutServiceMock;
private ITutorialsService tutServiceMock;
@Autowired @Autowired private WebApplicationContext webApplicationContext;
private WebApplicationContext webApplicationContext;
@Before @Before public void setUp() {
public void setUp() {
Mockito.reset(tutServiceMock); Mockito.reset(tutServiceMock);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
} }
@Test @Test public void testModel() throws Exception {
public void testModel() throws Exception {
Mockito.when(tutServiceMock.listTutorials()) Mockito.when(tutServiceMock.listTutorials())
.thenReturn(Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), .thenReturn(Arrays.asList(
new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor"))); new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")));
mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")) mockMvc.perform(get("/"))
.andExpect(status().isOk()).andExpect(view().name("index"))
.andExpect(model().attribute("tutorials", hasSize(2))) .andExpect(model().attribute("tutorials", hasSize(2)))
.andExpect(model().attribute("tutorials", .andExpect(model()
hasItem(allOf(hasProperty("tutId", is(1)), hasProperty("author", is("GuavaAuthor")), .attribute("tutorials",
hasItem(allOf(hasProperty("tutId", is(1)),
hasProperty("author", is("GuavaAuthor")),
hasProperty("title", is("Guava")))))) hasProperty("title", is("Guava"))))))
.andExpect(model().attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(2)), .andExpect(model()
hasProperty("author", is("AndroidAuthor")), hasProperty("title", is("Android")))))); .attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(2)),
hasProperty("author", is("AndroidAuthor")),
hasProperty("title", is("Android"))))));
mockMvc.perform(get("/")).andExpect(xpath("//table").exists()); mockMvc.perform(get("/"))
mockMvc.perform(get("/")).andExpect(xpath("//td[@id='tutId_1']").exists()); .andExpect(xpath("//table").exists());
mockMvc.perform(get("/"))
.andExpect(xpath("//td[@id='tutId_1']").exists());
} }
} }

View File

@ -1,15 +1,9 @@
package com.baeldung.mvc.velocity.test; package com.baeldung.mvc.velocity.test;
import com.baeldung.mvc.velocity.controller.MainController;
import static org.junit.Assert.assertEquals; import com.baeldung.mvc.velocity.domain.Tutorial;
import static org.junit.Assert.assertNotNull; import com.baeldung.mvc.velocity.service.TutorialsService;
import static org.mockito.Mockito.times; import com.baeldung.mvc.velocity.test.config.TestConfig;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.Arrays;
import java.util.List;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mockito; import org.mockito.Mockito;
@ -19,27 +13,26 @@ import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import com.baeldung.mvc.velocity.controller.MainController; import java.util.Arrays;
import com.baeldung.mvc.velocity.domain.Tutorial; import java.util.List;
import com.baeldung.mvc.velocity.service.TutorialsService;
import com.baeldung.mvc.velocity.test.config.TestConfig;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
//@ContextConfiguration(locations = {"classpath:mvc-servlet.xml"}) @ContextConfiguration(classes = { TestConfig.class })
@ContextConfiguration(classes = {TestConfig.class})
public class NavigationControllerTest { public class NavigationControllerTest {
private MainController mainController = new MainController(Mockito.mock(TutorialsService.class)); private MainController mainController = new MainController(Mockito.mock(TutorialsService.class));
private final Model model = new ExtendedModelMap(); private final Model model = new ExtendedModelMap();
@Test public void shouldGoToTutorialListView() {
@Test Mockito.when(mainController.getTutService().listTutorials()).thenReturn(createTutorialList());
public void shouldGoToTutorialListView() {
Mockito.when(mainController.getTutService().listTutorials())
.thenReturn(createTutorialList());
final String view = mainController.listTutorialsPage(model); final String view = mainController.listTutorialsPage(model);
final List<Tutorial> tutorialListAttribute = (List<Tutorial>) model.asMap().get("tutorials"); final List<Tutorial> tutorialListAttribute = (List<Tutorial>) model.asMap().get("tutorials");
@ -48,14 +41,14 @@ public class NavigationControllerTest {
assertNotNull(tutorialListAttribute); assertNotNull(tutorialListAttribute);
} }
@Test @Test public void testContent() throws Exception {
public void testContent() throws Exception{
List<Tutorial> tutorials = Arrays.asList( List<Tutorial> tutorials = Arrays.asList(
new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor") new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor"));
);
Mockito.when(mainController.getTutService().listTutorials()).thenReturn(tutorials); Mockito.when(mainController.getTutService().listTutorials())
.thenReturn(tutorials);
String view = mainController.listTutorialsPage(model); String view = mainController.listTutorialsPage(model);