SpringMVC学习(一)

概览

1.导入JAR包
2.配置web.xml
3.配置springmvc.xml
4.创建controller层
5.创建JSP测试页面
6.测试
7.注意

准备

工具:eclipse
JAR包版本:spring4.1.0和2.5.6
JQuery版本:jquery-3.3.1.js
资料参考:https://www.cnblogs.com/sunniest/p/4555801.html

1.导入JAR包

创建个web项目
在spring的官网上下载4.1.0和2.5.6版本的spring-framework
然后分别在两个文件下找到以下的jar包,将其导入到项目中
在这里插入图片描述

2.配置web.xml

在项目的WebContent/WEB-INF下生成web.xml文件
在这里插入图片描述
在web.xml中配置springmvc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>springmvc1</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>

<!-- 配置springmvc的核心过滤器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定配置文件的路径 如果不写默认为WEB-INF下的{servlet-name}-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 类似于过滤任何的请求地址 -->
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

3.配置springmvc.xml

然后在src下创建个springmvc(名字与web.xml中的servlet-name相同)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.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">

<!-- 扫描标注注解的对象 -->
<context:component-scan base-package="com.zy.springmvc1.controller"></context:component-scan>

<!-- 使用注解配置 -->
<mvc:annotation-driven></mvc:annotation-driven>

<!-- 不过滤静态资源 -->
<mvc:default-servlet-handler/>


<!-- 配置springmvc的视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前缀 -->
<property name="prefix" value="/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>

<!-- 文件上传的配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大值 -->
<property name="maxUploadSize" value="102400000"></property>
</bean>

</beans>

4.创建controller层

创建一个controller包,在其中创建一个TestController的控制器(注意不是servlet了,而是普通的class)
springmvc最为便捷的便是可以用注释替代大量的设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package com.zy.springmvc1.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zy.springmvc1.pojo.User;

//把类作为springmvc的控制器
@Controller //会自动创建控制器对象
@RequestMapping("/mvc") //类似于路径或文件夹
public class TestController {

//定义一个方法,返回到根目录下index.jsp页面
@RequestMapping("/toIndex")
public String toIndex(){

//现在看返回的页面名称,实际上是一个路径
//由于配置过了前缀和后缀,所以其表示的还是index.jsp页面
return "index";
}

//访问web-inf/jsp下的文件
@RequestMapping("/toIndex2")
public String toIndex2(){

//返回的是路径
return "WEB-INF/jsp/index";
}


//接受方法入参
@RequestMapping("revParm")
public void revParm(String name,Integer age,Double weight){
System.out.println(name+" "+age+" "+weight);
}

//注入对象属性值
@RequestMapping("/getUser")
public String toIndex3(User user){
System.out.println(user);
return "index";
}

//springmvc日期类型默认是以yyyy/MM/dd的格式,但咱们自己的习惯是yyyy-MM-dd的格式
//400 badrequest 参数格式有问题
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}


//向前台页面发送数据展示
@RequestMapping("/showMsg")
public ModelAndView showMsg(Model model){
User user = new User(10, "lala", 22, null);
//把对象放入到作用域,model类似于request作用域
model.addAttribute("u",user);

return new ModelAndView("showMsg");
}

//向前台发送数据展示
@RequestMapping("/showMsg2")
public String showMsg2(HttpServletRequest request){
User user = new User(10, "lala", 22, null);

request.setAttribute("u", user);
return "showMsg";
}

//向前台发送数据展示map
@RequestMapping("/showMsg3")
public String showMsg3(Map<String,Object> map){
//放入到作用域
User user = new User(10, "lala", 22, null);
map.put("u",user);
return "showMsg";
}

//ajax的调用
@RequestMapping("/ajax")
public void ajax(String name,PrintWriter out){
System.out.println("name="+name);
out.print("hello "+name);
}

//解决中文乱码问题
@RequestMapping("/ajax1")
public void ajax1(String name,HttpServletResponse resp) throws IOException{
resp.setCharacterEncoding("utf-8");
resp.getWriter().write(name+"hello2");
}

//跳转到ajax.jsp
@RequestMapping("/toAjax")
public String toAjax(){
return "WEB-INF/jsp/ajax";
}


//在同一个控制器下实现跳转操作,从一个方法跳转到另外一个方法
@RequestMapping("/goTo")
public String goToIndex(){

return "redirect:toIndex";
}

//在同一个控制器下实现转发的操作
@RequestMapping("/goTo2")
public String goToIndex1(){
//转发跳转,地址栏不变化
return "forward:toIndex";
}


//实现不同控制器之间的跳转
@RequestMapping("goTo3")
public String goToController2(){

return "redirect:/mvc2/test";
}

@RequestMapping("goTo4")
public String goToController22(){

return "forward:/mvc2/test";
}

}

再创建一个TestController2为了实现不同控制器间的跳转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.zy.springmvc1.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.zy.springmvc1.pojo.User;

@Controller
@RequestMapping("/mvc2")
public class TestController2 {

@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}

//修饰的方法 --- 在执行控制中的其他方法之前会执行此方法
@ModelAttribute
public void test(){
System.out.println("000000000000");
}


@RequestMapping("/te")
public String test3(@ModelAttribute("u") User user){
System.out.println(user);
return "showMsg";
}

//定义一个方法
@RequestMapping("/test")
public void test2(){
System.out.println("successful");
}


//required默认为true 参数必须存在,false参数可以不传入
@RequestMapping(value="/reqParm",method=RequestMethod.GET)
public void reqParm(@RequestParam(value="no",required=false) Integer no,@RequestParam(value="sex") String sex){
//查看结果
System.out.println("no="+no +"\t sex="+sex);
}
}

还要创建一个测试的实体类,随便创建一个User

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.zy.springmvc1.pojo;

import java.util.Date;

public class User {

private Integer no;
private String name;
private Integer age;
private Date birthDay;
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(Integer no, String name, Integer age, Date birthDay) {
super();
this.no = no;
this.name = name;
this.age = age;
this.birthDay = birthDay;
}
@Override
public String toString() {
return "User [no=" + no + ", name=" + name + ", age=" + age + ", birthDay=" + birthDay + "]";
}

}

然后创建一个Upload的控制器,控制文件的上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.zy.springmvc1.controller;


import java.io.FileOutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
@RequestMapping("/upload")
public class UploadFile {


//跳转到upload.jsp页面
@RequestMapping("/toup")
public String toUp(){
return "/WEB-INF/jsp/upload";
}


//文件上传操作的方法
@RequestMapping("/up")
public String upload(HttpServletRequest req) throws Exception{
//强制类型转换
MultipartHttpServletRequest msr = (MultipartHttpServletRequest)req;
//获得上传的文件
MultipartFile file = msr.getFile("img");
//拿到文件的名称
String oriName = file.getOriginalFilename();
//文件名称需要处理
//System.out.println(oriName);
//得到文件的后缀名称
String ext = oriName.substring(oriName.lastIndexOf("."));
//System.out.println(ext);
//上传操作,知道上传的路径
String path = req.getServletContext().getRealPath("/upload");
//System.out.println("服务器的上传地址"+path);
//通过输出流直接写入文件到服务器端的绝对路径下
FileOutputStream fos = new FileOutputStream(path+"/"+UUID.randomUUID().toString()+ext);
//fos.write(file.getBytes());
IOUtils.copy(file.getInputStream(), fos);
//关闭流
fos.close();
return "success";
}

}

5.创建JSP测试页面

在Webcontent下创建index.jsp,showMsg.jsp,success.jsp
index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
hello world!!!
</body>
</html>

showMsg.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${u.no }--${u.name }--${u.age }
</body>
</html>

success.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
success
</body>
</html>

再在WEB-INF下创建一个jsp的文件夹,在其中再创建ajax.jsp,index.jsp,upload.jsp

ajax.jsp
这里你需要导入JQuery的js
在Webcontent下创建个js文件夹,将JQuery放入进去这里使用的是jquery-3.3.1.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<!-- 引入JQuery -->
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-3.3.1.js"></script>
<script type="text/javascript">
/* onload函数 */
$(function(){
//获得文本框的对象
$("#name").blur(function(){
var value=$(this).val();
//alert(value);
$.ajax({
type : "POST",
url : "ajax1",
data : "name="+value,
success : function(msg) {
alert("Data Saved: " + msg);
}
});
})
})


</script>
</head>
<body>
<input name="name" id="name">
</body>
</html>

WEB-INF/jsp/index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
hello world!!!222
</body>
</html>

upload.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- post提交
enctype:multipart/form-data -->
<form action="up" method="post" enctype="multipart/form-data">
名称:<input name="name" /><br/>
图片:<input name="img" type="file" /><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>

6.测试

将项目布置到tomcat中,启动tomcat
打开浏览器在地址栏分别输入你要测试的方法的RequestMapping注释
然后查看jsp页面和控制台输出(有些是没有页面的所以会404,这是正常的,查看控制台有没有输出)

在这里插入图片描述
在这里插入图片描述

7.注意

1.springmvc的默认路径不是src下[classpath],默认路径在web-inf下
2.springmvc默认名称有命名规则:web.xml中的servlet的[name-servlet.xml]
3.springmvc是面向方法编程的,定义方法实现跳转
4.springmvc的文件上传必须用post提交,还要有enctype属性 enctype:multipart/form-data

具体还是参考:https://www.cnblogs.com/sunniest/p/4555801.html
这里对springmvc的讲解十分详细,所以本文就拿来自己实验测试用下