上传文件与下载文件图片,批量删除删除
Web下的文件
lib
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>分页</title>
</head>
<body>
<div style="float: left">
<span>总页码数:${pageModel.totalPage}</span>
<span>当前页:${pageModel.currentPage}</span>
<%-- 使用el表达式内置对象param 通过key值获取value值--%>
<sapn><a href="${param.path}currentPage=1">首页</a></sapn>
<%--
总记录数 总页码数
limit a,b
--%>
<span>总记录数:${pageModel.totalPage * 5}</span>
</div>
<div style="float:right">
<c:choose>
<c:when test="${pageModel.currentPage == 1}"><%--上一页逻辑---->是否等于第一页--%>
<a>上一页</a>
</c:when>
<c:otherwise>
<%--${param.path}----> ${pageContext.request.contextPath}/user/userList?page=--%>
<a href="${param.path}currentPage=${pageModel.currentPage -1}">上一页</a>
</c:otherwise>
</c:choose>
<c:forEach begin="${pageModel.beginPage}" end="${pageModel.endPage}" varStatus="status">
<%--<a href="${pageContext.request.contextPath}/page?">${status.index}</a>--%>
<c:choose>
<c:when test="${pageModel.currentPage == status.index}">
<a style="color: green" >${status.index}</a><%--当前页自然就在中间--%>
</c:when>
<c:otherwise>
<a href="${param.path}currentPage=${status.index}">${status.index}</a>
</c:otherwise>
</c:choose>
</c:forEach>
<c:choose>
<c:when test="${pageModel.currentPage == pageModel.totalPage}"><%--下一页逻辑是---->判断是否等于总页码数--%>
<a>下一页</a>
</c:when>
<c:otherwise>
<a href="${param.path}currentPage=${pageModel.currentPage + 1}">下一页</a>
</c:otherwise>
</c:choose>
<span><a href="${param.path}currentPage=${pageModel.totalPage}">尾页</a></span>
</div>
</body>
</html>
download.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件下载</title>
</head>
<body>
<%--本质就是一个超链接
如果浏览器能够直接解析的,它会把该文件打开
如果浏览器解析不了,会直接下载。
--%>
<a href="${pageContext.request.contextPath}/user/download?image=张三.jpg"><img src="images/张三.jpg"></a><br>
<a href="${pageContext.request.contextPath}/user/download?image=2.jpg"><img src="images/2.jpg"></a><br>
<a href="${pageContext.request.contextPath}/user/download?image=3.jpg"><img src="images/3.jpg"></a><br>
<a href="${pageContext.request.contextPath}/user/download?image=4.jpg"><img src="images/4.jpg"></a><br>
<a href="${pageContext.request.contextPath}/user/download?image=5.png"><img src="images/5.png"></a><br>
<a href="${pageContext.request.contextPath}/user/download?image=6.png"><img src="images/6.png"></a><br>
</body>
</html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/listUsers">查询所有的用户信息</a>
</body>
</html>
listUsers.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户管理界面</title>
<script src="${pageContext.request.contextPath}/js/jquery-1.12.4.min.js"></script>
<script>
/*实现批量删除等功能*/
// 定义一个需要删除项的个数
var deleteNum = 0;
// 选中所有
function selectAll(obj) {
// 让所有的子选框和头选框的选中状态保持一致
$(".one").prop("checked",obj.checked);
// 判断obj的选中状态是否为true
deleteNum = obj.checked ? $(".one").size() : 0;
// 把选中后的数量插入到span标签中
$("#tagNum").text(deleteNum);
}
// 选中一个
function selectOne(obj) {
// 判断obj中的checked属性是否为true
deleteNum = obj.checked ? ++deleteNum : --deleteNum;
// 判断当子选框中的全部被选中
$("#all").prop("checked",$(".one:checked").size() == $(".one").size());
// 把更改后的数量插入到span标签中
$("#tagNum").text(deleteNum);
}
// 批量删除
function batchDelete() {
// 先判断deleteNum是否为0
if (deleteNum == 0) {
alert("没有内容,不用删除!");
return;
} else{
if (confirm("这是全部删除,你确定吗")){
// 走异步请求
$.ajax({
url:"${pageContext.request.contextPath}/user/batchDelete",
type:"POST",
dataType:"text",
data:$("#formData").serialize(),
success:function (data) {
if (data == "success"){
alert("删除成功");
refresh();// 刷新当前页面
}else{
alert("删除失败!");
}
},
error:function () {
alert("请求批量删除失败!");
}
});
}
}
}
// 删除一个用户
function deleteOne(id) {
if (confirm("你确定要删除此记录吗")){
// 走异步请求
$.ajax({
url: "${pageContext.request.contextPath}/user/deleteOne",
dataType: "text",
data: {"u_id":id},
success:function (data) {
if (data == "success"){
alert("删除成功!")
//refresh();// 让页面刷新下
location.reload();// 页面刷新
}else {
alert("删除失败!")
}
},
error:function () {
alert("请求删除失败!");
}
});
}
}
// 刷新
function refresh() {
location.href = "${pageContext.request.contextPath}/user/listUsers";
//location.reload();
}
</script>
</head>
<body>
<%--模糊查询--%>
<form style="position:relative;left: 490px;" action="${pageContext.request.contextPath}/user/listUsers" id="fuzzyQuery" method="post">
<span>搜索内容:</span>
<input type="text" name="userKeyword" placeholder="请输入搜索关键字" />
<span>搜索字段:</span>
<select name = "userSearchField">
<option value="u_name">用户名</option>
<option value="password">密码</option>
<option value="u_phone">手机号</option>
</select>
<input type="submit" value="搜索" />
<input type="button" onclick="refresh();" value="刷新">
</form>
<form action="#" id="formData">
<table border="1" width="600px" align="center">
<%--批量删除--%>
<caption>
<input type="button" onclick="addUser();" value="添加用户" />
<button type="button" onclick="batchDelete();">
批量删除<span id = "tagNum">0</span>
</button>
</caption>
<tr align="center">
<%--确认标记 复选框--%>
<th><input type="checkbox" id="all" onclick="selectAll(this)"/></th>
<th>序号</th>
<th>用户名</th>
<th>密码</th>
<th>手机号</th>
<th>操作</th>
</tr>
<c:choose>
<c:when test="${not empty pageModel.list}">
<c:forEach items="${pageModel.list}" var="user" varStatus="status">
<tr align="center">
<td><input type="checkbox" value="${user.u_id}" name="checkId" class="one" onclick="selectOne(this);"></td>
<td>${status.count}</td>
<td>${user.u_name}</td>
<td>${user.password}</td>
<td>${user.u_phone}</td>
<td>
<a href="${pageContext.request.contextPath}/user/editUser?u_id=${user.u_id}">编辑</a>
 
<a href="javascript:void(0);" onclick="deleteOne(${user.u_id})">删除</a>
</td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
没有查询到相关的用户信息。。。。。。
</c:otherwise>
</c:choose>
</table>
<%--引入分页--%>
<jsp:include page="./lib/pageInfo.jsp">
<jsp:param name="path"
value="${pageContext.request.contextPath}/user/listUsers?userKeyword=${userKeyword}&userSearchField=${userSearchField}&"/>
</jsp:include>
</form>
</body>
</html>
showMessage.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>展示个人信息</title>
</head>
<body>
<h3>个人信息展示---详情界面</h3>
姓名:${user.u_name} <br>
头像:<img src="${user.pic_path}" alt="图像路径不匹配">
</body>
</html>
upload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/upload" enctype="multipart/form-data"
method="post"><%--get方法传数据有大小限制,post方法不会限制--%>
姓名:<input type="text" name="username" placeholder="请输入姓名"/>
头像:<input type="file" name="headImage"/>
<input type="submit" value="上传">
</form>
</body>
</html>
java
# 连接数据库的组件参数
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///java31?characterEncoding=utf8
username=root
password=root
#初始化池子的连接数量
initialSize=10
#最大池子连接数量
maxActive=50
#最长等待时间
maxWait=3000
package com.zhiyou100.apartment.tools;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
// 德鲁伊连接池数据源工具类
public class DruidDBUtil {
private static DataSource pool;
static {
// 使用 Properties
Properties pro = new Properties();
// 使用Properties集合读取配置文件信息
InputStream is = DruidDBUtil.class.getClassLoader().getResourceAsStream("db.properties");
try {
// 读取配置文件信息
pro.load(is);
// 创建连接池
pool = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
System.out.println("创建数据源失败!!");
e.printStackTrace();
}
}
// 对外提供获取连接的方法
public static Connection getConnection() throws SQLException {
return pool.getConnection();
}
// 对外获取数据源的方法
public static DataSource getDataSource() {
return pool;
}
// 释放资源
public static void closeAll(ResultSet set,PreparedStatement ps,Connection conn) {
if (set != null) {
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package com.zhiyou100.apartment.pojo;
import java.io.Serializable;
/**
* @author: admin
* @date: 2021/1/25
*/
public class User {
private Integer u_id;
private String u_name;
private String password;
private String u_phone;
private String pic_path;
public String getPic_path() {
return pic_path;
}
public void setPic_path(String pic_path) {
this.pic_path = pic_path;
}
public Integer getU_id() {
return u_id;
}
public void setU_id(Integer u_id) {
this.u_id = u_id;
}
public String getU_name() {
return u_name;
}
public void setU_name(String u_name) {
this.u_name = u_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getU_phone() {
return u_phone;
}
public void setU_phone(String u_phone) {
this.u_phone = u_phone;
}
public User(Integer u_id, String u_name, String password, String u_phone) {
this.u_id = u_id;
this.u_name = u_name;
this.password = password;
this.u_phone = u_phone;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"u_id=" + u_id +
", u_name='" + u_name + '\'' +
", password='" + password + '\'' +
", u_phone='" + u_phone + '\'' +
", pic_path='" + pic_path + '\'' +
'}';
}
}
package com.zhiyou100.apartment.pojo;
import java.util.List;
/**
* @author: admin
* @date: 2021/1/21
*/
// 分页对象 使用泛型扩大使用范围
public class PageModel<T> {
private int currentPage;// 当前页
private int beginPage;// 起始页
private int endPage;// 结束页
private int totalPage;// 总页码数
private int pageNum;// 页码数 假定为奇数页
private List<T> list;
// 根据当前页去计算起始页和结束页
private void caluBeginAndEnd(){
// 写计算起始页和结束页的逻辑 页码数 11 9 7 5 5+4 => 9
// 先根据当前页计算结束页 ----> 右边的值
if (currentPage + (pageNum-1)/2 > totalPage){
// 说明已经到末尾了
endPage = totalPage;
// 结束页拿到之后,先推算起始页
beginPage = endPage - (pageNum - 1) < 1 ? 1 : endPage - (pageNum - 1);// 控制起始页数
} else{
// 当前页+5没有大于总页码数
//先计算起始页
beginPage = currentPage - (pageNum-1)/2 < 1 ? 1 : currentPage - (pageNum-1)/2;
endPage = beginPage + (pageNum - 1) > totalPage ? totalPage : beginPage + (pageNum-1);// 控制结束页数
}
}
public PageModel(int currentPage, int totalPage, int pageNum, List<T> list) {
this.currentPage = currentPage;
this.totalPage = totalPage;
this.pageNum = pageNum;
this.list = list;
caluBeginAndEnd();
}
public PageModel() {
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getBeginPage() {
return beginPage;
}
public void setBeginPage(int beginPage) {
this.beginPage = beginPage;
}
public int getEndPage() {
return endPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
@Override
public String toString() {
return "PageModel{" +
"currentPage=" + currentPage +
", beginPage=" + beginPage +
", endPage=" + endPage +
", totalPage=" + totalPage +
", pageNum=" + pageNum +
", list=" + list +
'}';
}
}
package com.zhiyou100.apartment.dao;
import com.zhiyou100.apartment.pojo.User;
import java.util.List;
public interface UserDao {
int findTotalCount();
List<User> findAllUsersByPage(int currentPage);
int batchDeleteUsers(String[] ids);
int deleteUserById(int u_id);
int findTotalCount(String userKeyword, String userSearchField);
List<User> findAllUsersByPage(int currentPage, String userKeyword, String userSearchField);
int updateUserPic(User user);
}
package com.zhiyou100.apartment.dao.impl;
import com.zhiyou100.apartment.dao.UserDao;
import com.zhiyou100.apartment.pojo.User;
import com.zhiyou100.apartment.tools.DruidDBUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
* @author: admin
* @date: 2021/1/25
*/
public class UserDaoImpl implements UserDao {
// 定义jdbc工具类
private JdbcTemplate jtp = new JdbcTemplate(DruidDBUtil.getDataSource());
// 查询总数量
@Override
public int findTotalCount() {
String sql = "select count(1) from user";
long count = jtp.queryForObject(sql, Long.class);
return (int)count;
}
// 查询总信息值
@Override
public List<User> findAllUsersByPage(int currentPage) {
String sql = "select * from user limit ?,5";
List<User> list = jtp.query(sql, new BeanPropertyRowMapper<>(User.class), (currentPage - 1) * 5);
return list;
}
@Override
public int batchDeleteUsers(String[] checkIds) {
/* String ids = "";
for (int i = 0; i < checkIds.length; i++) {
if (i == checkIds.length-1) {
ids+=checkIds[i];
break;
}
ids+=checkIds[i]+",";
}*/
StringBuilder sb = new StringBuilder();
for (String checkId : checkIds) {
sb.append(checkId).append(",");
}
String ids = sb.substring(0, sb.lastIndexOf(","));
System.out.println(ids);// 转换成字符串 根据id删除 id in(?)
String sql = "delete from user where u_id in (" + ids + ")";// 一条sql语句执行完毕
int count = jtp.update(sql);
return count;
}
@Override
public int deleteUserById(int u_id) {
String sql = "delete from user where u_id = ?";
int count = jtp.update(sql, u_id);
return count;
}
// 根据关键字查询总数
@Override
public int findTotalCount(String userKeyword, String userSearchField) {
// mysql中字段名称是不可以使用预编译方式 使用占位符?来替代表表中字段名称
String sql = " select count(1) from user where " + userSearchField + " like '%' ? '%'";
long count = jtp.queryForObject(sql, Long.class, userKeyword);
return (int) count;
}
// 根据关键字查询总信息值
@Override
public List<User> findAllUsersByPage(int currentPage, String userKeyword, String userSearchField) {
String sql= "select * from user where " + userSearchField + " like '%' ? '%' limit ?,5";
List<User> list = jtp.query(sql, new BeanPropertyRowMapper<>(User.class), userKeyword, (currentPage - 1) * 5);
return list;
}
//更新图像
@Override
public int updateUserPic(User user) {
String sql = "update user set pic_path = ? where u_name = ?";
int count = jtp.update(sql, user.getPic_path(), user.getU_name());
return count;
}
}
package com.zhiyou100.apartment.service;
import com.zhiyou100.apartment.pojo.PageModel;
import com.zhiyou100.apartment.pojo.User;
public interface UserService {
PageModel<User> loadPage(int currentPage);
boolean batchDelete(String[] ids);
boolean deleteUserById(int u_id);
PageModel<User> loadPage(int currentPage, String userKeyword, String userSearchField);
boolean addUserPic(User user);
}
package com.zhiyou100.apartment.service.impl;
import com.zhiyou100.apartment.dao.UserDao;
import com.zhiyou100.apartment.dao.impl.UserDaoImpl;
import com.zhiyou100.apartment.pojo.PageModel;
import com.zhiyou100.apartment.pojo.User;
import com.zhiyou100.apartment.service.UserService;
import java.util.List;
/**
* @author: admin
* @date: 2021/1/25
*/
public class UserServiceImpl implements UserService {
private UserDao ud = new UserDaoImpl();
@Override
public PageModel<User> loadPage(int currentPage) {
// 查询所有的数量
int count = ud.findTotalCount();
// 根据当前页查询对应的用户信息
List<User> list = ud.findAllUsersByPage(currentPage);
// totalPage count 假如你每次查询5条记录 页码数pageNum = 5
// totalPage = (count+4)/5
PageModel<User> page = new PageModel<>(currentPage,(count+4)/5,5,list);
return page;
}
@Override
public boolean batchDelete(String[] ids) {
/* */
// 判断删除的记录数是否等于ids的长度
int count = ud.batchDeleteUsers(ids);
if (count == ids.length) {
return true;
}
return false;
}
@Override
public boolean deleteUserById(int u_id) {
int count = ud.deleteUserById(u_id);
if (count > 0) {
return true;
}
return false;
}
// 分页带模糊查询
@Override
public PageModel<User> loadPage(int currentPage, String userKeyword, String userSearchField) {
// 查询所有的数量
int count = ud.findTotalCount(userKeyword,userSearchField);
// 根据当前页查询对应的用户信息
List<User> list = ud.findAllUsersByPage(currentPage,userKeyword,userSearchField);
// totalPage count 假如你每次查询5条记录 页码数pageNum = 5
// totalPage = (count+4)/5
PageModel<User> page = new PageModel<>(currentPage,(count+4)/5,5,list);
return page;
}
@Override
public boolean addUserPic(User user) {
int count = ud.updateUserPic(user);
if (count > 0) {
return true;
}
return false;
}
}
控制层
package com.zhiyou100.apartment.controller;
import com.zhiyou100.apartment.service.UserService;
import com.zhiyou100.apartment.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/user/batchDelete")
public class BatchDeleteServlet extends HttpServlet {
private UserService us = new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置编码字符集
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 获取所有的checkId值
String[] checkIds = request.getParameterValues("checkId");
// "["1","2","3","4",]"
// 批量删除
boolean flag = us.batchDelete(checkIds);
if (flag) {
//删除成功
response.getWriter().write("success");
}else{
response.getWriter().write("fail");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
package com.zhiyou100.apartment.controller;
import com.zhiyou100.apartment.service.UserService;
import com.zhiyou100.apartment.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/user/deleteOne")
public class DeleteOneServlet extends HttpServlet {
private UserService us = new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("u_id");
int u_id = Integer.parseInt(id);
boolean flag = us.deleteUserById(u_id);
if (flag) {
response.getWriter().write("success");
} else {
response.getWriter().write("fail");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
package com.zhiyou100.apartment.controller;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@WebServlet("/user/download")
public class DownloadFileServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request.setCharacterEncoding("utf-8");
String image = request.getParameter("image");
// 浏览器的编码字符集 latin iso-8859-1
//byte[] bytes = image.getBytes("ISO8859-1");
// image = new String(bytes, "UTF-8");
image = new String(image.getBytes("ISO-8859-1"),"UTF-8");
// 服务器告诉浏览器客户端以附件的形式打开
// 设置响应头 content-disposition 值为 attachment 附件
System.out.println(image);
response.setHeader("content-disposition","attachment;filename="+image);// 手动指定下载的文件名称
// 下载 还是以流的形式进行copy
String realPath = this.getServletContext().getRealPath("/images");
// 设置响应的mime类型
response.setContentType(this.getServletContext().getMimeType(image));// jpg --> image/jpeg
// 就是image的路径
File file = new File(realPath, image);
// 放进字节输入流中
FileInputStream fis = new FileInputStream(file);
// 获取字节输入流
ServletOutputStream os = response.getOutputStream();
// 一读一写
int len = 0;
byte[] buff = new byte[1024];
while ((len = fis.read(buff)) != -1) {
os.write(buff,0,len);
}
// 释放流资源
os.close();
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
package com.zhiyou100.apartment.controller;
import com.zhiyou100.apartment.pojo.PageModel;
import com.zhiyou100.apartment.pojo.User;
import com.zhiyou100.apartment.service.UserService;
import com.zhiyou100.apartment.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/user/listUsers")
public class ListUsersServlet extends HttpServlet {
private UserService us = new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 组装分页 获取当前页码
String nowPage = request.getParameter("currentPage");
String userKeyword = request.getParameter("userKeyword");
String userSearchField = request.getParameter("userSearchField");
// 非空校验
int currentPage = nowPage == null ? 1 : Integer.parseInt(nowPage);
userKeyword = userKeyword == null ? "" : userKeyword;
userSearchField = userSearchField == null ? "u_name" : userSearchField;
PageModel<User> page = us.loadPage(currentPage,userKeyword,userSearchField);
// 往客户端传输
request.setAttribute("pageModel", page);
request.setAttribute("userKeyword", userKeyword);
request.setAttribute("userSearchField",userSearchField);
// 资源跳转
request.getRequestDispatcher("/listUsers.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
package com.zhiyou100.apartment.controller;
import com.zhiyou100.apartment.pojo.User;
import com.zhiyou100.apartment.service.UserService;
import com.zhiyou100.apartment.service.impl.UserServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
@WebServlet("/user/upload")
public class UpLoadFileServlet extends javax.servlet.http.HttpServlet {
private UserService us = new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 判断请求是否是文件上传请求
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
// 表名当前的请求不是一个文件上传的请求。
return;// 程序结束
}
// 构造一个user对象
User user = new User();
try {
// 2. Create a factory for disk-based file items 创建FileItem工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
// this 指代 当前Servlet对象
// 3. Create a new file upload handler 创建一个文件上传处理器 核心对象
ServletFileUpload upload = new ServletFileUpload(factory);
// 3.2 设置文件上传的大小 单个文件的大小 文件上传总和值
// 单位:字节 byte
upload.setFileSizeMax(1024 * 1024 * 5);// 5MB
upload.setSizeMax(1024 * 1024 * 100); // 100MB
// 文件上传 transferTo()
// 4. Parse the request 解析客户端发送的请求 装配的是提交的一个个表单项
List<FileItem> items = upload.parseRequest(request);
// 5. 遍历表单项集合 进行循环判断
for (FileItem item : items) {
// 判断某一个表单项是不是一个文件上传的表单项
if (item.isFormField()) { // 是一个普通的表单项
//String fieldName = item.getFieldName();//--->表单项名称
String name = item.getFieldName();// 获取的是name属性名称
// 设置普通表单项的编码字符集
String value = item.getString("utf-8"); // 获取的是name属性名称对应的值
System.out.println(name + "------" + value);// username ------ 张三
// 把用户名的信息也放进到user对象中
user.setU_name(value);
} else {
// 不是一个普通的表单项
String fileName = item.getName();// 获取的是表单项的对应的值 文件名称
String path = "D:\\upload";// 上传文件的目标地址
// 文件的名称需要做单独处理 防止文件上传过程中文件重名覆盖现象
// 使用Java中提供的工具类 UUID
String headName = UUID.randomUUID().toString().replaceAll("-", "");
//long timeMillis = System.currentTimeMillis();
// 获取文件的字节输入流 流中包含上传文件的数据
InputStream is = item.getInputStream();
fileName = headName + fileName;
// 文件字节输出流
File destFile = new File(path);
if (!destFile.exists() && !destFile.isDirectory()) {
destFile.mkdirs();// 多级目录创建
}
// 真实的路径
//String realPath = path + "\\" + fileName;// 拼接路径
String realPath = "http://localhost:8080\\upload\\" + fileName;// 映射磁盘中的“D:\\upload”
// 将来需要把路径存储到数据库中
user.setPic_path(realPath);
// 真正上传的文件 指向"D:\\upload目录下
File file = new File(destFile, fileName);
FileOutputStream os = new FileOutputStream(file);
// 一读一写
int len = 0;
byte[] buff = new byte[1024];
while ((len = is.read(buff)) != -1) {
os.write(buff,0,len);
}
// 释放流对象
os.close();
is.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
// 关联service层 通过用户名添加到对应的记录中
boolean flag = us.addUserPic(user);
if (flag) {
// 添加到表中成功
request.setAttribute("user", user);
request.getRequestDispatcher("/showMessage.jsp").forward(request, response);
} else {
// 没有上传成功 再来一次
request.getRequestDispatcher("/upload.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}