pom.xml
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</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>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.8</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
webapp/WEB-INF/web.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置全局过滤的filter-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置SpringMVC的前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!--它的值必须是一个整数,表示servlet被加载的先后顺序。-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--全局初始化参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<!--<param-value>applicationContex.xml</param-value>-->
<param-value>classpath:applicationContex.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<!--<listener-class>com.wf.listener.ContextLoaderListener</listener-class>-->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>UserSevlet</servlet-name>
<servlet-class>com.wf.web.UserSevlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserSevlet</servlet-name>
<url-pattern>/userSevlet</url-pattern>
</servlet-mapping>
</web-app>
spring-mvc.xml
<?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">
<!--Controller的组件扫描-->
<context:component-scan base-package="com.wf.controller"/>
<!--配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置处理器映射器-->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">-->
<!--<property name="messageConverters">-->
<!--<list>-->
<!--<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>-->
<!--</list>-->
<!--</property>-->
<!--</bean>-->
<!--注解驱动,代替上方的处理器映射器,因为默认用的就是jackson-->
<mvc:annotation-driven conversion-service="conversionService"/>
<!--资源地址-->
<!--<mvc:resources mapping="/js/**" location="/js/"/>-->
<mvc:default-servlet-handler/>
<!--配置处理Date日期解析-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.wf.converter.DateConverter"></bean>
</list>
</property>
</bean>
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="500000"/>
</bean>
</beans>
controller里的@RequestMapping写类外面,和里面的作用不一样
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/save")
public String save() {
System.out.println("Controller sava running...");
return "/success.jsp";
}
}
访问的时候要这样访问
http://localhost:8080/user/save
还可以有其它的参数,如method, params
二、处理数据响应
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value="/save23")
@ResponseBody
public void save23(String username, MultipartFile[] uploadFiles) throws IOException {
for (MultipartFile uploadFile : uploadFiles) {
System.out.println(username);
System.out.println(uploadFile);
// 获得上传文件的名称
String originalFilename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("/Users/username/Desktop/MyJava/upload/" + originalFilename));
}
}
@RequestMapping(value="/save22")
@ResponseBody
public void save22(String username, MultipartFile uploadFile) throws IOException {
System.out.println(username);
System.out.println(uploadFile);
// 获得上传文件的名称
String originalFilename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("/Users/username/Desktop/MyJava/upload/" + originalFilename));
}
@RequestMapping(value="/save21")
@ResponseBody
public void save21(@CookieValue("JSESSIONID") String SESSIONID) throws IOException {
System.out.println(SESSIONID);
}
@RequestMapping(value="/save20")
@ResponseBody
public void save20(@RequestHeader(value = "User-Agent", required = false) String user_agent) throws IOException {
System.out.println(user_agent);
}
@RequestMapping(value="/save19")
@ResponseBody
public void save19(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
System.out.println(request);
System.out.println(response);
System.out.println(session);
}
@RequestMapping("/save18")
@ResponseBody
public void save18(Date data) {
System.out.println(data);
}
@RequestMapping("/save17/{username}")
@ResponseBody
public void save17(@PathVariable(value = "username") String username) {
System.out.println(username);
}
@RequestMapping("/save16")
@ResponseBody
public void save16(@RequestParam("name") String username) {
System.out.println(username);
}
// ajax提交的body里的集合用这种
@RequestMapping("/save15")
@ResponseBody
public void save15(@RequestBody List<User> userList) {
System.out.println(userList);
}
// 集合,form表单提交集合用这种
@RequestMapping("/save14")
@ResponseBody
public void save13(VO vo) {
System.out.println(vo);
}
// http://localhost:8080/user/save?a=111,b=222,c=333
@RequestMapping(value="/save13")
@ResponseBody
public void save13(String[] strs) throws IOException {
System.out.println(Arrays.asList(strs));
}
@RequestMapping("/save12")
@ResponseBody
public void save12(User user) {
System.out.println(user);
}
@RequestMapping("/save11")
@ResponseBody
public void save11(String username, int age) {
System.out.println(username);
System.out.println(age);
}
@RequestMapping("/save10")
@ResponseBody
public User save10() throws JsonProcessingException {
User user = new User();
user.setUsername("lilei");
user.setAge(30);
// ObjectMapper objectMapper = new ObjectMapper();
// String json = objectMapper.writeValueAsString(user);
return user;
}
@RequestMapping("/save9")
@ResponseBody
public String save9() throws JsonProcessingException {
User user = new User();
user.setUsername("lilei");
user.setAge(30);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
return json;
}
@RequestMapping("/save7")
@ResponseBody // 告知SpringMVC框架不进行跳转。直接写入字符串。
public String save7() {
return "hello xiaoming";
}
@RequestMapping("/save6")
public void save6(HttpServletResponse response) throws IOException {
response.getWriter().println("hello spring mvc");
}
@RequestMapping("/save5")
public String save5(HttpServletRequest request) {
request.setAttribute("name", "我很快乐");
return "success";
}
@RequestMapping(value="/quick4")
public String save4(Model model){
model.addAttribute("username","姓名");
return "success";
}
@RequestMapping(value="/quick3")
public ModelAndView save3(ModelAndView modelAndView){
modelAndView.addObject("username","zhangsan");
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping("/save2")
public ModelAndView save2() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("name", "lisi");
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping("/save")
public String save() {
System.out.println("Controller sava running...");
return "success";
}
}
对应用上的前端页面
ajax.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ajax</title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<button class="btn">点击发送</button>
<script>
var btn = document.querySelector(".btn")
btn.addEventListener("click", click)
function click() {
var userList = new Array();
userList.push({username: "zhangsan", age: 24})
userList.push({username: "lisi", age: 28})
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/user/save15",
data: JSON.stringify(userList),
contentType: "application/json;charset=utf-8"
})
}
</script>
</body>
</html>
form.jsp 表单提交集合
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/save14" method="post">
<%--表明是第一个User对象的username age--%>
<input type="text" name="userList[0].username"><br/>
<input type="text" name="userList[0].age"><br/>
<input type="text" name="userList[1].username"><br/>
<input type="text" name="userList[1].age"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
upload.jsp,上传文件。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<div>多文件</div>
<form action="${pageContext.request.contextPath}/user/save23" method="post" enctype="multipart/form-data">
文件<input type="file" multiple name="uploadFiles"> <br>
<input type="submit" value="提交">
</form>
<div>单文件</div>
<form action="${pageContext.request.contextPath}/user/save22" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"> <br>
文件<input type="file" name="uploadFile"> <br>
<input type="submit" value="提交">
</form>
</body>
</html>
User实体类
public class User {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
}
Vo实体类
public class VO {
List<User> userList;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
@Override
public String toString() {
return "VO{" +
"userList=" + userList +
'}';
}
}