siye@r480:~/svlution/workspace/springmvc4322$ tree src/
src/
├── main
│ ├── java
│ │ ├── log4j.properties
│ │ └── ocn
│ │ └── site
│ │ └── springmvc
│ │ ├── controller
│ │ │ └── Manicontroller.java
│ │ ├── domain
│ │ │ └── User.java
│ │ └── setup
│ │ ├── Appconfig.java
│ │ └── Webxmlconfig.java
│ ├── resources
│ └── webapp
│ ├── index.jsp
│ └── WEB-INF
│ ├── register.jsp
│ ├── success.jsp
│ └── web.xml
└── test
├── java
│ └── ocn
│ └── site
│ └── springmvc
│ └── controller
│ └── Runtest.java
└── resources
└── config
└── application.xml
19 directories, 11 files
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.22.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.0.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.22.RELEASE</version>
<scope>test</scope>
</dependency>
package ocn.site.springmvc.controller;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import ocn.site.springmvc.domain.User;
@Controller
public class Manicontroller {
private final Logger logger = Logger.getLogger(this.getClass());
private @Autowired User user;
private final static String NAME_SUCCESS = "success";
private final static String NAME_REGISTER = "register";
@ModelAttribute
public void handlerConfig(ModelMap map) {
map.addAttribute("user", user);
logger.info("first config success");
}
@GetMapping("/test")
public String handlerPage() {
return NAME_REGISTER;
}
@PostMapping("/register")
public String handlerRegister(@ModelAttribute @Valid User user, BindingResult result, ModelMap map) {
if (result.hasErrors()) {
return NAME_REGISTER;
}
map.put("message", "register success");
return NAME_SUCCESS;
}
}
package ocn.site.springmvc.domain;
import java.io.Serializable;
import javax.validation.constraints.Size;
import org.springframework.stereotype.Component;
@Component
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
@Size(min = 4, message = "size must >= 4")
private String name;
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;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
package ocn.site.springmvc.setup;
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.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan({ "ocn.site.springmvc.controller", "ocn.site.springmvc.domain" })
public class Appconfig extends WebMvcConfigurerAdapter {
private final static String PREFIX = "/WEB-INF/";
private final static String SUFFIX = ".jsp";
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ViewResolver getViewResolver() {
return new InternalResourceViewResolver(PREFIX, SUFFIX);
}
}
package ocn.site.springmvc.setup;
import javax.servlet.Filter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class Webxmlconfig extends AbstractAnnotationConfigDispatcherServletInitializer {
private final static String ENCODING = "utf-8";
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { Appconfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {
return new Filter[] { new CharacterEncodingFilter(ENCODING, true), new HiddenHttpMethodFilter() };
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<base href="${pageContext.request.contextPath }/">
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<script src="https://libs.cdnjs.net/jquery/3.4.1/jquery.min.js"></script>
<script src="https://libs.cdnjs.net/json2/20160511/json2.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<form:form commandName="user" action="register" method="post">
id:<form:input path="id" />
<form:errors path="id"></form:errors>
<br>
name:<form:input path="name" />
<form:errors path="name"></form:errors>
<br>
<form:button>submit</form:button>
</form:form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<base href="${pageContext.request.contextPath }/">
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<script src="https://libs.cdnjs.net/jquery/3.4.1/jquery.min.js"></script>
<script src="https://libs.cdnjs.net/json2/20160511/json2.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<p>message:${message }</p>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>springmvc4322</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>false</el-ignored>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<base href="${pageContext.request.contextPath }/">
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<script src="https://libs.cdnjs.net/jquery/3.4.1/jquery.min.js"></script>
<script src="https://libs.cdnjs.net/json2/20160511/json2.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<a href="test">test</a>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="paramMap" class="org.springframework.util.LinkedMultiValueMap"></bean>
<context:component-scan base-package="ocn.site.springmvc.controller"></context:component-scan>
<context:component-scan base-package="ocn.site.springmvc.domain"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
package ocn.site.springmvc.controller;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:config/application.xml")
public class Runtest {
private final Logger logger = Logger.getLogger(this.getClass());
private @Autowired WebApplicationContext wac;
private MockMvc build;
private @Autowired @Qualifier("paramMap") LinkedMultiValueMap<String, String> map;
@Before
public void init() {
this.build = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void handlerPage() throws Exception {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/test");
ResultActions ra = build.perform(requestBuilder);
ra.andExpect(MockMvcResultMatchers.view().name("register"));
ra.andExpect(MockMvcResultMatchers.status().isOk());
logger.info("test finished");
}
@Test
public void handlerRegister4success() throws Exception {
map.add("id", "34");
map.add("name", "hack");
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/register");
requestBuilder.params(map);
ResultActions ra = build.perform(requestBuilder);
ra.andExpect(MockMvcResultMatchers.view().name("success"));
ra.andExpect(MockMvcResultMatchers.model().attribute("message", "register success"));
ra.andExpect(MockMvcResultMatchers.status().isOk());
logger.info("test finished");
}
@Test
public void handlerRegister4Failed() throws Exception {
map.add("id", "34");
map.add("name", "liy");
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/register");
requestBuilder.params(map);
ResultActions ra = build.perform(requestBuilder);
ra.andExpect(MockMvcResultMatchers.view().name("register"));
ra.andExpect(MockMvcResultMatchers.status().isOk());
logger.info("test finished");
}
}
19-09-04 22:11:01 org.springframework.test.context.web.WebTestContextBootstrapper =====>>> Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
19-09-04 22:11:01 org.springframework.test.context.web.WebTestContextBootstrapper =====>>> Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@5dfcfece, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@23ceabc1, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5d5eef3d, org.springframework.test.context.support.DirtiesContextTestExecutionListener@56f4468b]
19-09-04 22:11:01 org.springframework.beans.factory.xml.XmlBeanDefinitionReader =====>>> Loading XML bean definitions from class path resource [config/application.xml]
19-09-04 22:11:01 org.springframework.web.context.support.GenericWebApplicationContext =====>>> Refreshing org.springframework.web.context.support.GenericWebApplicationContext@31ef45e3: startup date [Wed Sep 04 22:11:01 CST 2019]; root of context hierarchy
19-09-04 22:11:02 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping =====>>> Mapped "{[/test],methods=[GET]}" onto public java.lang.String ocn.site.springmvc.controller.Manicontroller.handlerPage()
19-09-04 22:11:02 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping =====>>> Mapped "{[/register],methods=[POST]}" onto public java.lang.String ocn.site.springmvc.controller.Manicontroller.handlerRegister(ocn.site.springmvc.domain.User,org.springframework.validation.BindingResult,org.springframework.ui.ModelMap)
19-09-04 22:11:02 org.hibernate.validator.internal.util.Version =====>>> HV000001: Hibernate Validator 5.2.0.Final
19-09-04 22:11:02 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter =====>>> Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@31ef45e3: startup date [Wed Sep 04 22:11:01 CST 2019]; root of context hierarchy
19-09-04 22:11:02 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter =====>>> Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@31ef45e3: startup date [Wed Sep 04 22:11:01 CST 2019]; root of context hierarchy
19-09-04 22:11:02 org.springframework.mock.web.MockServletContext =====>>> Initializing Spring FrameworkServlet ''
19-09-04 22:11:02 org.springframework.test.web.servlet.TestDispatcherServlet =====>>> FrameworkServlet '': initialization started
19-09-04 22:11:02 org.springframework.test.web.servlet.TestDispatcherServlet =====>>> FrameworkServlet '': initialization completed in 20 ms
19-09-04 22:11:02 ocn.site.springmvc.controller.Manicontroller =====>>> first config success
19-09-04 22:11:03 ocn.site.springmvc.controller.Runtest =====>>> test finished
19-09-04 22:11:03 org.springframework.web.context.support.GenericWebApplicationContext =====>>> Closing org.springframework.web.context.support.GenericWebApplicationContext@31ef45e3: startup date [Wed Sep 04 22:11:01 CST 2019]; root of context hierarchy