| 名称 | 说明 |
|---|---|
| page | 当前页面有效【当前jsp页面内有效】 |
| request | 当前请求中有效 |
| session | 当前会话中有效【浏览器不关闭,session不失效的情况下】 |
| application | 所有应用程序中有效 |
测试:
TestScopeController:
package com.zi.controller;
import com.zi.pojo.User;
import com.zi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
public class TestScopeController {
@Autowired
private UserService userService;
@RequestMapping("/testScope")
public String testScope(HttpServletRequest request, HttpSession session){
ServletContext application = request.getServletContext();
List<User> users = userService.findAllUser();
request.setAttribute("users", users);
session.setAttribute("users", users);
application.setAttribute("users", users);
return "showData";
}
}
showData.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
【request】:${requestScope.users[0].uname}
【session】:${sessionScope.users[0].uname}
【application】:${applicationScope.users[0].uname}
/**
* model对象主要是针对请求域传递数据进行了API上的封装【request】
* model中的字符串类型的键值对信息会转换为请求参数,转发给目标组件
* @param model
* @return
*/
@RequestMapping("/testScope2")
public String testScope2(Model model){
List<User> users = userService.findAllUser();
model.addAttribute("users", users);
return "showData";
}
/**
* Model 数据
* View 视图
* @return
*/
@RequestMapping("/testScope3")
public ModelAndView testScope3(){
ModelAndView mv = new ModelAndView();
Map<String, Object> model = mv.getModel();
List<User> users = userService.findAllUser();
model.put("users", users);
mv.setViewName("forward:/showData.jsp");
return mv;
}
控制文件类型:
//控制文件格式:只能上传.png
if(!extendsName.equals(".png")){
map.put("message", "文件格式只能为.png");
return map;
}
控制文件大小:
//控制文件上传大小 不能超过400kb
long size = headPhoto.getSize();
if(size > 1024*400){
map.put("message", "文件大小不能超过400kb");
return map;
}
图片回显:
【注意在springmvc中配置静态资源放行】
<mvc:resources mapping="/upload/**" location="/upload/">
整个代码:
login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册页面title>
<script src="js/jquery-3.4.1.js">script>
<style>
.progress {
width: 200px;
height: 10px;
border: 1px solid #ccc;
border-radius: 10px;
margin: 10px 0px;
overflow: hidden;
}
/* 初始状态设置进度条宽度为0px */
.progress > div {
width: 0px;
height: 100%;
background-color: yellowgreen;
transition: all .3s ease;
}
style>
<script>
$(function () {
$("#uploadFile").click(function () {
//获取要上传的文件
var photoFile = $("#photo")[0].files[0]
if (photoFile == undefined) {
alert("您还未选中文件");
return;
}
//将文件装入FormData对象
var formData = new FormData();
formData.append("headPhoto", photoFile);
//ajax向后台发送图像
$.ajax({
type: "post",
data: formData,
url: "fileUpload",
processData: false,
contentType: false,
success: function (result) {
//接收后台的响应
// alert(result.message);
console.log(result)
//图片回显
$("#headImg").attr("src","upload/" + result.newFileName);
},
xhr: function () {
var xhr = new XMLHttpRequest();
//使用XMLHttpRequest.upload监听上传过程,
// 注册progress事件,打印回调函数中的event事件
xhr.upload.addEventListener('progress',
function (e) {
//loaded代表上传了多少
//total代表总数为多少
var progressRate = (e.loaded / e.total)
* 100 + '%';
//通过设置进度条的宽度达到效果
$('.progress > div').css('width',
progressRate);
})
return xhr;
}
})
})
})
script>
head>
<body>
<form action="addPlayer" method="post">
账号:<input type="text" name="name"><br/>
密码:<input type="password" name="password"><br/>
昵称:<input type="text" name="nickname"><br/>
头像:
<input id="photo" type="file" name="filetype"><br/>
<%--图片回显--%>
<img id="headImg" style="width: 200px;height: 100px" alt="你还未上传图片"/>
<%--进度条设置--%>
<div class="progress">
<div>div>
div>
<a id="uploadFile" href="javascript:void(0)">立即上传a>
<input type="submit" value="注册">
form>
body>
html>
FileUploadController:
package com.zi.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Controller
public class FileUploadController{
@ResponseBody
@RequestMapping("/fileUpload")
public Map<String, String> fileUpload(MultipartFile headPhoto, HttpServletRequest request) throws IOException {
Map<String, String> map = new HashMap<>();
//控制文件上传大小 不能超过400kb
long size = headPhoto.getSize();
if(size > 1024*400){
map.put("message", "文件大小不能超过400kb");
return map;
}
//指定文件目录为项目部署环境下的upload目录
String realPath = request.getServletContext().getRealPath("/upload");
File dir = new File(realPath);
//如果不存在则创建目录
if(!dir.exists()){
dir.mkdirs();
}
//获取文件名
String originalFilename = headPhoto.getOriginalFilename();
//为了避免文件名冲突,使用UUID替换文件名
String uuid = UUID.randomUUID().toString();
//获取文件拓展名
String extendsName = originalFilename.substring(originalFilename.lastIndexOf("."));
//控制文件格式:只能上传.png
if(!extendsName.equals(".png")){
map.put("message", "文件格式只能为.png");
return map;
}
//新的文件名
String newFileName = uuid.concat(extendsName);
//文件存储位置
File file = new File(dir, newFileName);
//文件保存
headPhoto.transferTo(file);
map.put("message", "文件上传成功");
map.put("fileType", headPhoto.getContentType());
map.put("newFileName", newFileName);
return map;
}
}
测试结果;

PlayerController:
@Controller
public class PlayerController {
private static final String FILESERVER = "http://192.168.145.1:8090/upload/";
@ResponseBody
@RequestMapping("/fileUpload")
public Map<String, String> addPlayer(MultipartFile headPhoto, HttpServletRequest request) throws IOException {
Map<String, String> map = new HashMap<>();
//获取文件名
String originalFilename = headPhoto.getOriginalFilename();
//为了避免文件名冲突,使用UUID替换文件名
String uuid = UUID.randomUUID().toString();
//获取文件拓展名
String extendsName = originalFilename.substring(originalFilename.lastIndexOf("."));
//新的文件名
String newFileName = uuid.concat(extendsName);
//创建sun公司提供的jersey包中的client对象
Client client = Client.create();
WebResource resource = client.resource(FILESERVER + newFileName);
//文件保存到另一台tomcat上
resource.put(String.class, headPhoto.getBytes());
map.put("message", "文件上传成功");
map.put("fileType", headPhoto.getContentType());
map.put("newFileName", newFileName);
return map;
}
}
login.jsp:
//图片回显
$("#headImg").attr("src","http://192.168.145.1:8090/upload/"+result.newFileName);
将用户数据注册到数据库:
PlayerController:
@Controller
public class PlayerController {
@Autowired
private PlayerService playerService;
@RequestMapping("/addPlayer")
public String addPlayer(Player player){
playerService.addPlayer(player);
return "redirect:/html/showPlayer.html";
}
}
login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册页面</title>
<script src="js/jquery-3.4.1.js"></script>
<style>
.progress {
width: 200px;
height: 10px;
border: 1px solid #ccc;
border-radius: 10px;
margin: 10px 0px;
overflow: hidden;
}
/* 初始状态设置进度条宽度为0px */
.progress > div {
width: 0px;
height: 100%;
background-color: yellowgreen;
transition: all .3s ease;
}
</style>
<script>
$(function () {
$("#uploadFile").click(function () {
//获取要上传的文件
var photoFile = $("#photo")[0].files[0]
if (photoFile == undefined) {
alert("您还未选中文件");
return;
}
//将文件装入FormData对象
var formData = new FormData();
formData.append("headPhoto", photoFile);
//ajax向后台发送图像
$.ajax({
type: "post",
data: formData,
url: "fileUpload",
processData: false,
contentType: false,
success: function (result) {
//接收后台的响应
// alert(result.message);
console.log(result)
//图片回显
$("#headImg").attr("src","http://192.168.145.1:8090/upload/"+result.newFileName);
//将文件类型和文件名放入form表单
$("#photoInput").val(result.newFileName)
// alert(result.newFileName);
// alert(result.filetype);
$("#filetypeInput").val(result.filetype)
},
xhr: function () {
var xhr = new XMLHttpRequest();
//使用XMLHttpRequest.upload监听上传过程,
// 注册progress事件,打印回调函数中的event事件
xhr.upload.addEventListener('progress',
function (e) {
//loaded代表上传了多少
//total代表总数为多少
var progressRate = (e.loaded / e.total)
* 100 + '%';
//通过设置进度条的宽度达到效果
$('.progress > div').css('width',
progressRate);
})
return xhr;
}
})
})
})
</script>
</head>
<body>
<form action="addPlayer" method="post">
账号:<input type="text" name="name"><br/>
密码:<input type="password" name="password"><br/>
昵称:<input type="text" name="nickname"><br/>
头像:
<input id="photo" type="file" name="filetype"><br/>
<%--图片回显--%>
<img id="headImg" style="width: 200px;height: 100px" alt="你还未上传图片"/>
<%--进度条设置--%>
<div class="progress">
<div></div>
</div>
<a id="uploadFile" href="javascript:void(0)">立即上传</a>
<input type="submit" value="注册">
<input type="hidden" id="photoInput" name="photo">
<input type="hidden" id="filetypeInput" name="filetype">
</form>
</body>
</html>
showPlayer.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<style>
#playerTable{
width: 50%;
border: 3px solid sienna;
margin: 0px auto;
text-align: center;
}
#playerTable th, td{
border: 1px solid goldenrod;
}
#playerTable img{
width: 100px;
height: 100px;
}
</style>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script>
$(function(){
$.ajax({
type:"get",
url:"getAllPlayer",
success:function (players){
$.each(players, function (i, e){//i表示是第几个 e是代表单个player
$("#playerTable").append('\n' +
' '+e.id+' \n' +
' '+e.name+' \n' +
' '+e.password+' \n'
+
' '+e.nickname+' \n'
+
' \n' +
'
+e.photo+'" alt="" src>\n' +
' \n' +
' \n' +
' +e.photo+'&filetype='+e.filetype+'">下载\n'
+
' \n' +
' ')
})
}
})
})
</script>
</head>
<body>
<table id="playerTable" cellspacing="0px" cellpadding="0px">
<tr>
<th>编号</th>
<th>用户名</th>
<th>密码</th>
<th>昵称</th>
<th>头像</th>
<th>操作</th>
</tr>
</table>
</body>
</html>
playerController.java:
package com.zi.controller;
import com.zi.pojo.Player;
import com.zi.service.PlayerService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
@Controller
public class PlayerController {
private static final String FILESERVER = "http://192.168.145.1:8090/upload/";
@Autowired
private PlayerService playerService;
@RequestMapping("/addPlayer")
public String addPlayer(Player player){
playerService.addPlayer(player);
return "redirect:/html/showPlayer.html";
}
@RequestMapping("/getAllPlayer")
@ResponseBody
public List<Player> getAllPlayer(){
System.out.println("--------------");
return playerService.getAll();
}
@RequestMapping("/fileDownload")
public void fileDownload(String photo, String filetype, HttpServletResponse response) throws IOException {
//设置响应头
//告知浏览器要将数据保存在磁盘上,不在浏览器上直接解析
response.setHeader("Content-Disposition", "attachment;filename="+photo);
//告诉浏览器下载的文件类型
response.setContentType(filetype);
//获取一个文件的输入流
InputStream inputStream = new URL(FILESERVER + photo).openStream();
//获取一个指向浏览器的输出流
ServletOutputStream outputStream = response.getOutputStream();
//向浏览器响应文件
IOUtils.copy(inputStream, outputStream);
}
}
效果展示:

