目录
1. 使用springmvc
(1)创建一个maven-web工程
注意:用原来的web.xml文件替换现在的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">
</web-app>
(2)引入springmvc的依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
</dependencies>
(3) 注册DispatcherServlet到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">
<!--默认DispactherServlet加载的springmvc配置文件:WEB-INF/[servlet-name]-servlet.xml
能不能你指定加载的配置文件呢:可以。
-->
<servlet>
<servlet-name>DispactherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--classpath:表示编译后的路径-->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispactherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
(4)创建springmvc配置文件
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--包扫描-->
<context:component-scan base-package="com.abc.controller"/>
</beans>
(5)创建一个controller类
@Controller //该注解标记该类为处理层类---类似@WebServlet
public class HelloController {
@RequestMapping(value = "/hello01") //把请求路径映射到该方法上。
public String hello01(){
System.out.println("业务处理");
return "hello01.jsp"; //响应一个页面
}
}
2. springmvc的运行流程
1. 客户端发生请求http://localhost:8080/qy151_springmvc01/abc
2. 来到tomcat服务器。
3. springmvc的前端控制器DipatcherServlet接受所有的请求。
4. 查看你的请求地址和哪个@RequestMaping匹配。
5. 执行对应的方法。方法会返回一个字符串。springmvc把该字符串解析为要转发的网页。
6. 把该字符串经过视图解析器拼接。
7. 拿到拼接的地址,找到对应的网页。
8. 渲染该网页给客户
3. 在controller接受请求的参数
3.1 接受少量的参数
譬如:删除
只需要给定方法的参数,参数必须要求和请求的参数名称一致
3.2 接受大量的参数
譬如: 表单提交。
封装一个实体类来接受这些参数:
接受的参数值乱码:---只能添加过滤器
(1)自己创建编码过滤器. jdk1.8一定要重写init和destory方法 1.9以后可以不写
public class MyEncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {
}
}
(2)springmvc提供的一个编码过滤器
3.3 接受的参数含有日期类型
解决办法:
在时间类型的属性上添加一个注解:@DateTimeFormat(pattern = "yyyy-MM-dd")
//yyyy年 MM:月 dd日 24小时制
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;//出生日期
在springmvc配置文件上开启注解驱动
<!--开启注解驱动-->
<mvc:annotation-driven/>
4. 处理静态资源
<!--放行静态资源:哪些资源为静态资源。css img js html-->
<mvc:default-servlet-handler/>
5. 如何把controller数据返回到网页并回显
package com.wyn.controller;
import com.wyn.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
@SessionAttributes(value = {"student4"})//设置哪些model的key在session范围
public class Controller2 {
@RequestMapping( "/a1")
public String a1(HttpServletRequest request){ //request和tomcat容器绑定
//查询到一个学生信息
Student student = new Student("梁小冰",new Date(),"男","上海");
//保存到request中,同一个请求可用
request.setAttribute("student",student);
int i=10/0;
return "abcc.jsp"; //转发请求
}
@RequestMapping("/a2")
public String a2(Model model){
Student student2 = new Student("梁小冰2",new Date(),"女","上海");
model.addAttribute("student2",student2);
return "abcc.jsp";
}
@RequestMapping("/a3")
public String a2(HttpSession session){
Student student3 = new Student("梁小冰3",new Date(),"女","上海");
session.setAttribute("student3",student3);//默认在request范围
return "abcc.jsp";
}
@RequestMapping("/a4")
public String a4(Model model){
Student student4 = new Student("梁小冰4",new Date(),"女","上海");
model.addAttribute("student4",student4);//保存到session范围
return "abcc.jsp";
}
}
6. 如何使用重定向跳转
//重定向跳转
@RequestMapping("/a5")
public String a5(){
System.out.println("-------");
return "redirect:abcc.jsp";//redirect: 重定向跳转
}
7. springmvc返回json数据
(1)引入一个jar. jackson的jar包
<!--jackson依赖 可以把java对象转换为json对象-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
(2) 在controller返回的数据类型变成javabean对象
//springmvc返回json数据
@RequestMapping("/json")
@ResponseBody//作用:把java对象转换为json对象
public List<Student> json(){
List<Student> list = new ArrayList<Student>();//返回类型为java对象
list.add(new Student("梁冰冰",new Date(),"女","上海"));
list.add(new Student("梁火火",new Date(),"女","上海"));
list.add(new Student("梁小火",new Date(),"女","上海"));
return list;//当中json
}
上面返回的时间类型的json数据显示的为毫秒,显示时间格式解决方法:
8. springmvc的全局异常处理类
全局异常处理类的作用: 当controller发生异常,则有全局异常类来处理并执行相应的处理方法。
(1)如何使用全局异常处理类
[1] 创建一个异常类: @ControllerAdvice注解
@ControllerAdvice //表示该为类controller的异常处理类
public class MyExceptinHandle {
@ExceptionHandler(value = RuntimeException.class) //当发生RuntimeException就会触发该方法
public String error(){
return "error.jsp";
}
@ExceptionHandler(value = Exception.class) //当发生Exception就会触发该方法
public String error2(){
return "error2.jsp";
}
}
[2] 保证springmvc能够扫描到该类
9. springmvc拦截器
过滤器: 过滤掉某些资源,
拦截器只会拦截controller层的资源路径
如何使用拦截器:
(1)创建一个类,并实现HandlerInterceptor
public class MyInterceptor implements HandlerInterceptor {
//拦截器的处理方法。
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("经过了该拦截器");
return true;//true:表示拦截器放行 false:不放行
}
}
(2)把该类注册到springmvc配置文件上
<!--拦截器的配置-->
<mvc:interceptors>
<mvc:interceptor>
<!--mapping:哪些路径需要经过拦截器
/**: 表示n层路径
/*:表示一层路径
-->
<mvc:mapping path="/**"/>
<!--exclude-mapping:设置不经过该拦截的路径-->
<mvc:exclude-mapping path="/list2"/>
<mvc:exclude-mapping path="/list3"/>
<!--bean表示自定义的拦截器类路径-->
<bean class="com.ykq.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
10. 文件上传到本地服务器
(1)因为文件上传的依赖
<!--文件上传的依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
(2)创建一个页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--
method: 提交方式 文件上传必须为post提交。
enctype:默认application/x-www-form-urlencoded 表示提交表单数据
multipart/form-data:可以包含文件数据
input的类型必须为file类型,而且必须有name属性
--%>
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="file"/>
</form>
</body>
</html>
(3)在springmvc中配置文件上传解析器
<!--
id的名称必须叫multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--这里的单位为字节10M*1024K*1024-->
<property name="maxUploadSize" value="10485760"/>
</bean>
(4)创建upload01接口方法
@RequestMapping("/upload")
//MultipartFile 参数名必须和<input type="file" name="myfile"/>中name属性相同
public String upload(MultipartFile file, HttpServletRequest request) throws Exception{
//获取本地服务目录的地址下的upload
String path = request.getSession().getServletContext().getRealPath("upload");
//创建了一个代表path这个文件的一个File对象 并没有创建文件
File file1 = new File(path);
//判断该目录是否存在
//如果不存在
if (!file1.exists()){
//创建文件
file1.mkdirs();
}
//设置文件名为随机生成名+传入的文件名 file.getOriginalFilename() 获取传进来的文件名字
String filename = UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename();
// 文件目录+文件名
File target = new File(path+"/"+filename);
//把文件位置设置为文件路径+文件名
file.transferTo(target);
return "";
}
11. elementui+vue+axios完成文件上传
(1)页面的布局
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<!--引入element得css样式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 这个必须在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="app">
<el-upload
class="avatar-uploader"
action="upload7"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
<script>
var app=new Vue({
el:"#app",
data:{
imageUrl:"",
},
methods: {
//上传成功触发的方法
handleAvatarSuccess(res, file) {
this.imageUrl = res.data;
},
//上传前触发的方法
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
})
</script>
</body>
</html>
(2)后台的接口
@RequestMapping("/upload")
@ResponseBody
public Map upload7(MultipartFile file,HttpServletRequest request){
try {
String path = request.getSession().getServletContext().getRealPath("upload");
File file1 = new File(path);
if (!file1.exists()){
file1.mkdirs();
}
String filename = UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename();
File target = new File(path+"/"+filename);
file.transferTo(target);
Map map = new HashMap();
map.put("code",2000);
map.put("msg","上传成功");
map.put("data","http://localhost:8080/springmvc0609/upload/"+filename);
return map;
}catch (Exception e){
e.printStackTrace();
}
Map map = new HashMap();
map.put("code",3000);
map.put("msg","上传失败");
return map;
}
12. 普通的文件上传到OSS文件服务器
(1)引入阿里云的OSS依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
(2)代码的书写
@RequestMapping("/upload1")
public String upload2(MultipartFile file){
//Endpoint以华东1(杭州)为例,其它Region请按实际情况填写
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户
String accessKeyId = "LTAI5tHY5kvY718cDVube";
String accessKeySecret = "oxaV7UI3aj32DN1mGs8v9rORCHy";
// 填写Bucket名称,例如examplebucket
String bucketName = "wynnn";
// 上传到oss后的名字
String objectName = UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename();
// 创建OSSClient实例
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = file.getInputStream();
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (Exception oe) {
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return "success.jsp";
}
13. elementui 异步上传OSS服务器
(1)前端
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
</head>
<body>
<div id="app">
<el-upload
class="avatar-uploader"
action="upload2"
:show-file-list="false"
:on-success="handleAvatarSuccess">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
<script>
var app=new Vue({
el:"#app",
data:{
imageUrl:"",
},
methods: {
//上传成功触发的方法
handleAvatarSuccess(res, file) {
this.imageUrl = res.data;
},
}
})
</script>
</body>
</html>
(2)后端代码
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;
public class OSSUtil {
public static String upload(MultipartFile file) {
//Endpoint以华东1(杭州)为例,其它Region请按实际情况填写
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户
String accessKeyId = "LTAI5tHY5kvY71jjg8cDVube";
String accessKeySecret = "oxaV7UI3aj32DNEw21mGs8v9rORCHy";
// 填写Bucket名称,例如examplebucket
String bucketName = "wynnn";
//你上传到oss后的名字
String objectName = fileName(file);
// 创建OSSClient实例
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = file.getInputStream();
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (Exception oe) {
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
String url="https://"+bucketName+"."+endpoint+"/"+objectName;
return url;
}
//封装获取上传到oss后的名字
static String fileName(MultipartFile file){
Calendar calendar = Calendar.getInstance();//获取日历
//根据日历设置文件名为年月日路径+随机生成名+原始文件名
String name=calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+ calendar.get(Calendar.DATE)
+"/"+ UUID.randomUUID().toString().replace("-","")+ file.getOriginalFilename();
//返回文件路径
return name;
}
}
(3)controller接口
@RequestMapping("/upload2")
@ResponseBody
public Map upload3(MultipartFile file){
try{
String url = OSSUtil.upload(file);
Map map = new HashMap();
map.put("code",2000);
map.put("msg","上传失败");
map.put("data",url);
return map;
}catch (Exception e){
e.printStackTrace();
}
HashMap map = new HashMap();
map.put("code",3000);
map.put("msg","上传失败");
return map;
}
14. 保存用户信息--头像
(1)前端的布局
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<!--引入element得css样式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 这个必须在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="app">
<el-form label-width="80px" :model="userForm">
<el-form-item label="头像:">
<el-upload
class="avatar-uploader"
action="user/avatarupload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
<el-form-item label="账号:">
<el-input v-model="userForm.name"></el-input>
</el-form-item>
<el-form-item label="密码:">
<el-input v-model="userForm.password"></el-input>
</el-form-item>
<el-form-item label="手机:">
<el-input v-model="userForm.phone"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">查询</el-button>
</el-form-item>
</el-form>
</div>
</body>
<script>
var app=new Vue({
el:"#app",
data:{
userForm:{},
imageUrl:""
},
methods:{
handleAvatarSuccess(res,file){
//为表单对象添加头像地址的属性
this.imageUrl=res.data;
this.userForm.avatarUrl=this.imageUrl;
},
//提交
onSubmit(){
axios.post("user/addUser",this.userForm).then(function(result){
});
},
//上传前触发的方法
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
})
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
</html>
(2)后台代码
package com.wyn.controller;
import com.wyn.entity.User;
import com.wyn.util.CommonResult;
import com.wyn.util.OSSUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController //该注解下所有的方法都是返回json数据
public class UserController {
@RequestMapping("/avatarupload")
public CommonResult avatarupload(MultipartFile file){
try{
String avatar = OSSUtil.upload(file);
return new CommonResult(2000,"上传成功",avatar);
}catch (Exception e){
e.printStackTrace();
}
return new CommonResult(3000,"上传失败",null);
}
@RequestMapping("/addUser")
public CommonResult addUser(@RequestBody User user){ //@RequestBody把请求的json数据转换为java对象 从前端到后端
System.out.println(user);
return new CommonResult(2000,"成功",null);
}
}
15. 补充内容
@RestController----类上等价于 @COntroller+@ResponseBody
该注解下所有的方法都是返回json数据
@RequestMapping: 作用: 把请求路径映射到响应的方法上。
@RequestParam(value = "u"):设置你接受的请求参数名。查询参数
@RequestMapping(value = "/addUser",method = RequestMethod.POST)
method:表示该接口接受的请求方式.不设置可以接受任意请求方式。
@GetMapping("addUser"):表示只接受get提交方式的请求
@RequestBody:把请求的json数据转换为java对象。从前端到后端
@ResponseBody:把java转换为json数据 从后端转前端