图片上传,图片删除,导出poi(controller):
package com.bw.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.bw.pojo.Meeting;
import com.bw.pojo.Power;
import com.bw.pojo.User;
import com.bw.service.MeetingService;
import com.bw.utils.PoiUtils;
import com.github.pagehelper.PageInfo;
@Controller
public class MeetingController {
@Autowired
private MeetingService meetingService;
@RequestMapping("/list")
public String list(Integer curPage, String startDate, String endDate, String search, HttpServletRequest request) {
PageInfo<Meeting> meetingPage = meetingService.findMeetingList(curPage, 3, startDate, endDate, search);
request.setAttribute("meetingPage", meetingPage);
request.setAttribute("startDate", startDate);
request.setAttribute("endDate", endDate);
request.setAttribute("search", search);
return "list";
}
@RequestMapping("/toMod")
public String toMod(Integer id, HttpServletRequest request) {
Meeting meeting = meetingService.findMeetingById(id);
request.setAttribute("meeting", meeting);
return "mod";
}
@RequestMapping("/mod")
public String mod(Meeting meeting, @RequestParam("choosePic")MultipartFile pic, HttpServletRequest request) throws IllegalStateException, IOException {
if (!pic.isEmpty()) {
String originalFileName = pic.getOriginalFilename();
String newFileName = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf("."));
//设置图片上传路径
String url = request.getSession().getServletContext().getRealPath("/upload");
pic.transferTo(new File(url+"/"+newFileName));
meeting.setPicName(newFileName);
}
try {
meetingService.modMeetingById(meeting);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("修改失败");
}
return "redirect:list";
}
@RequestMapping("/add")
public String add(Meeting meeting, @RequestParam("choosePic")MultipartFile pic, HttpServletRequest request) throws IllegalStateException, IOException {
if (!pic.isEmpty()) {
String originalFileName = pic.getOriginalFilename();
String newFileName = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf("."));
//设置图片上传路径
String url = request.getSession().getServletContext().getRealPath("/upload");
pic.transferTo(new File(url+"\\"+newFileName));
meeting.setPicName(newFileName);
}
try {
meetingService.addMeeting(meeting);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("添加失败");
}
return "redirect:list";
}
@RequestMapping("/toAdd")
public String toAdd() {
return "add";
}
@RequestMapping("/del")
@ResponseBody
public boolean del(String strids, HttpServletRequest request) {
String url = request.getSession().getServletContext().getRealPath("/upload");
String[] split = strids.split(",");
Integer[] ids = new Integer[split.length];
for(int i = 0 ; i < split.length ; i++) {
ids[i] = Integer.parseInt(split[i]);
String picName = meetingService.findPicNameById(ids[i]);
File f = new File(url+"\\"+picName);
f.delete();
}
try {
meetingService.delMeeting(ids);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
@RequestMapping("toLogin")
public String toLogin() {
return "login";
}
@RequestMapping("/login")
public String login(User user, HttpSession session) {
User sessionUser = meetingService.login(user);
if(sessionUser != null) {
session.setAttribute("user", sessionUser);
return "redirect:toMain";
}else {
return "error";
}
}
@RequestMapping("/logout")
public String logout(HttpSession session) {
session.removeAttribute("user");
return "login";
}
@RequestMapping("/toMain")
public String toMain() {
return "main";
}
@RequestMapping("/toLeft")
public String toLeft() {
return "left";
}
@RequestMapping("/toRight")
public String toRight() {
return "right";
}
@RequestMapping("/toTop")
public String toTop() {
return "top";
}
@RequestMapping("/getTree")
@ResponseBody
public List<Power> getTree() {
List<Power> powerList = new ArrayList<Power>();
Power power1 = new Power(1, "公司管理", 0, "", "");
Power power2 = new Power(2, "会议管理", 1, "/list", "right");
Power power3 = new Power(3, "部门管理", 1, "", "");
powerList.add(power1);
powerList.add(power2);
powerList.add(power3);
return powerList;
}
@RequestMapping("/export")
@ResponseBody
public void export(HttpServletResponse response){
String[] rowName = {"id","name","picName","startDate","endDate","place","status"};
List<Object[]> dataList = new ArrayList<Object[]>();
List<Meeting> meetingList = meetingService.findAllMeeting();
for (int i = 0; i < meetingList.size(); i++) {
Object[] element = {meetingList.get(i).getId(),meetingList.get(i).getName(),meetingList.get(i).getPicName(),meetingList.get(i).getStartDate(),meetingList.get(i).getEndDate(),meetingList.get(i).getPlace(),meetingList.get(i).getStatus()};
dataList.add(element);
}
PoiUtils utils = new PoiUtils("测试", rowName, dataList );
try {
utils.export(response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
list.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<link rel="styleSheet" href="css/index_work.css">
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
function sel() {
$(":checkbox:gt(0)").map(function(i,n){
if(n.checked == false) {
n.checked = true;
}else {
n.checked = false;
}
});
}
function del() {
var strids = "";
$(":checkbox:gt(0)").map(function(i,n){
if(n.checked == true) {
strids = strids + n.value + ",";
}
});
strids = strids.substring(0,strids.length-1);
var con = confirm("确定要删除吗?");
if(con) {
$.post(
"del",
{strids:strids},
function(obj) {
if(obj == false) {
alert("删除失败")
}else {
location.reload();
}
}, "json"
);
}
}
function toExport() {
location.href="export";
}
</script>
<body>
<form action="list" method="post">
日期:<input type="date" name="startDate" value="${startDate}" />至<input type="date" name="endDate" value="${endDate}" />
名称:<input type="text" name="search" value="${search}" />
<input type="submit" value="搜索" />
</form>
<table>
<tr>
<td><input type="checkbox" id="sel" onchange="sel()" /></td>
<td>ID</td>
<td>名称</td>
<td>图片</td>
<td>开始日期</td>
<td>结束日期</td>
<td>地点</td>
<td>状态</td>
<td>操作<a href="toAdd">添加</a> <a href="javascript:del()">删除</a> <a href="javascript:toExport()">导出</a></td>
</tr>
<c:forEach items="${meetingPage.list}" var="meeting">
<tr>
<td><input type="checkbox" value="${meeting.id}" /></td>
<td>${meeting.id}</td>
<td>${meeting.name}</td>
<td><img src="upload/${meeting.picName}" width="40" height="40"></td>
<td>${meeting.startDate}</td>
<td>${meeting.endDate}</td>
<td>${meeting.place}</td>
<td>
<c:if test="${meeting.status == 0}">未发布</c:if>
<c:if test="${meeting.status == 1}">已发布</c:if>
</td>
<td><a href="toMod?id=${meeting.id}">修改</a></td>
</tr>
</c:forEach>
</table>
<p>
<a href="list?curPage=1&startDate=${startDate}&endDate=${endDate}&search=${search}">首页</a>
<a href="list?curPage=${meetingPage.prePage}&startDate=${startDate}&endDate=${endDate}&search=${search}">上一页</a>
<a href="list?curPage=${meetingPage.nextPage}&startDate=${startDate}&endDate=${endDate}&search=${search}">下一页</a>
<a href="list?curPage=${meetingPage.total}&startDate=${startDate}&endDate=${endDate}&search=${search}">尾页</a>
</p>
</body>
</html>
add.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<link rel="styleSheet" href="css/index_work.css">
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
function refreshPic() {
var path = $("#choosePic").val();
var arr = path.split("\\");
var fileName = arr[2];
$("#picName").val(fileName);
//获取input file的files文件数组;
//$('#filed')获取的是jQuery对象,.get(0)转为原生对象;
//这边默认只能选一个,但是存放形式仍然是数组,所以取第一个元素使用[0];
var file = $('#choosePic').get(0).files[0];
//创建用来读取此文件的对象
var reader = new FileReader();
//使用该对象读取file文件
reader.readAsDataURL(file);
//读取文件成功后执行的方法函数
reader.function(e){
//读取成功后返回的一个参数e,整个的一个进度事件
console.log(e);
//选择所要显示图片的img,要赋值给img的src就是e中target下result里面
//的base64编码格式的地址
$('#pic').get(0).src = e.target.result;
}
}
</script>
<body>
<form action="add" method="post" enctype="multipart/form-data">
名称:<input type="text" name="name" /><br>
图片:<img width="40" height="40" id="pic" name="pic" >
<input type="file" accept="image/*" name="choosePic" id="choosePic" onchange="refreshPic()" />
<input type="hidden" id="picName" name="picName" /><br>
开始时间:<input type="date" name="startDate" /><br>
结束时间:<input type="date" name="endDate" /><br>
发布地点:<input type="text" name="place" /><br>
发布状态:
<select name="status">
<option value="1">已发布</option>
<option value="0">未发布</option>
</select><br>
<input type="submit" value="提交" />
</form>
</body>
</html>
mod.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<link rel="styleSheet" href="css/index_work.css">
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
function refreshPic() {
var path = $("#choosePic").val();
var arr = path.split("\\");
var fileName = arr[2];
$("#picName").val(fileName);
//获取input file的files文件数组;
//$('#filed')获取的是jQuery对象,.get(0)转为原生对象;
//这边默认只能选一个,但是存放形式仍然是数组,所以取第一个元素使用[0];
var file = $('#choosePic').get(0).files[0];
//创建用来读取此文件的对象
var reader = new FileReader();
//使用该对象读取file文件
reader.readAsDataURL(file);
//读取文件成功后执行的方法函数
reader.function(e){
//读取成功后返回的一个参数e,整个的一个进度事件
console.log(e);
//选择所要显示图片的img,要赋值给img的src就是e中target下result里面
//的base64编码格式的地址
$('#pic').get(0).src = e.target.result;
}
}
</script>
<body>
<form action="mod" method="post" enctype="multipart/form-data">
ID:<input type="text" readonly="readonly" value="${meeting.id}" name="id" /><br>
名称:<input type="text" value="${meeting.name}" name="name" /><br>
图片:<img src="upload/${meeting.picName}" width="40" height="40" id="pic" name="pic" >
<input type="file" accept="image/*" name="choosePic" id="choosePic" onchange="refreshPic()" />
<input type="hidden" value="${meeting.picName}" id="picName" name="picName" /><br>
开始时间:<input type="date" value="${meeting.startDate}" name="startDate" /><br>
结束时间:<input type="date" value="${meeting.endDate}" name="endDate" /><br>
发布地点:<input type="text" value="${meeting.place}" name="place" /><br>
发布状态:
<select name="status">
<option value="1" <c:if test="${meeting.status == 1}">selected="selected"</c:if> >已发布</option>
<option value="0" <c:if test="${meeting.status == 0}">selected="selected"</c:if> >未发布</option>
</select><br>
<input type="submit" value="提交" />
</form>
</body>
</html>
tree(left.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Insert title here</title>
<link rel="styleSheet" href="css/index_work.css">
<link rel="styleSheet" href="ztree/css/zTreeStyle/zTreeStyle.css">
<script type="text/javascript" src="ztree/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="ztree/js/jquery.ztree.core.js"></script>
<script type="text/javascript">
$(function(){
$.ajaxSetup({
async:false
});
var setting = {
data:{
simpleData:{
enable:true
}
}
};
var zNodes = null;
$.post(
"getTree",
function(obj) {
zNodes = obj;
}, "json"
);
$.fn.zTree.init($("#zTree"),setting,zNodes);
});
</script>
</head>
<body>
<ul id="zTree" class="zTree"></ul>
</body>
</html>
拦截器部分:
WebConfig.java
package com.bw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.bw.config.MyInterceptor;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// TODO Auto-generated method stub
registry.addInterceptor(myInterceptor).addPathPatterns("/**").excludePathPatterns("/toLogin","/login");
}
}
interceptor/MyInterceptor.java
package com.bw.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.bw.pojo.User;
@Component
public class MyInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
User user = (User) request.getSession().getAttribute("user");
if(user!=null) {
return true;
}else {
response.sendRedirect("/toLogin");
return false;
}
}
}