SpringMVC-15-(文档管理系统---文件管理+拦截器)

SpringMVC-15-(文档管理系统---文件管理+拦截器)

2019年03月15日 21:46:50 阅读数:19

6.文件管理

1.文件管理查询

1.修改Attachment
在这里插入图片描述
2.修改AttachmentMapper
在这里插入图片描述
3.修改AttachmentMapper.xml
在这里插入图片描述

4.创建AttachmentVo
在这里插入图片描述
5.创建AttachmentService
在这里插入图片描述
6.创建AttachmentServiceImpl

@Service
public class AttachmentServiceImpl implements AttachmentService{
	
	@Autowired
	private AttachmentMapper attachmentMapper;
	@Override
	public List<Attachment> queryAllAttachmentForPage(AttachmentVo attachmentVo,
			PageBean pageBean) {
		Page<Object> page=PageHelper.startPage(pageBean.getCurrentPage(), 
		pageBean.getPageSize());
		List<Attachment> list=this.attachmentMapper.queryAllAttachment(attachmentVo);
		pageBean.setTotalCount(page.getTotal());
		return list;
	}
	@Override
	public void addAttachment(AttachmentVo attachmentVo) {
		this.attachmentMapper.insertSelective(attachmentVo);
	}
	@Override
	public void updateAttachment(AttachmentVo attachmentVo) {
		this.attachmentMapper.updateByPrimaryKeySelective(attachmentVo);
		
	}
	@Override
	public void deleteAttachment(Integer fid) {
		this.attachmentMapper.deleteByPrimaryKey(fid);
	}
	@Override
	public Attachment queryAttachmentById(Integer fid) {
		return this.attachmentMapper.selectByPrimaryKey(fid);
	}

}

  • 1
  •  

7.创建AttachmentController
在这里插入图片描述
8.修改WEB-INF/view/index.jsp
在这里插入图片描述
9.创建WEB-INF/view/attachment/list.jsp
在这里插入图片描述

2.文件管理上传

1.修改WEB-INF/attachment/list.jsp
在这里插入图片描述
2.创建WEB-INF/attachment/add.jsp
在这里插入图片描述

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, 
initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="renderer" content="webkit">
<title>文件上传</title>
 <link rel="stylesheet" href="${ctx }/resources/css/pintuer.css">
    <link rel="stylesheet" href="${ctx }/resources/css/admin.css">
    <script src="${ctx }/resources/js/jquery.js"></script>
    <script src="${ctx }/resources/js/pintuer.js"></script>  
</head>
<body>
<div class="panel admin-panel margin-top">
  <div class="panel-head" id="add"><strong><span class="icon-pencil-square-o">
  </span>添加内容</strong></div>
  <div class="body-content">
    <form method="post" class="form-x" action="${ctx }/attachment/addAttachment.action" 
    enctype="multipart/form-data">
      <div class="form-group">
        <div class="label">
          <label>文件标签:</label>
        </div>
        <div class="button-group border-main checkbox">
         <label class="button active">
						<input name="fmark" value="逗逼" type="checkbox" checked="checked">逗逼
					</label>
					<label class="button">
						<input name="fmark" value="搞笑" type="checkbox">搞笑
					</label>
					<label class="button">
						<input name="fmark" value="严肃" type="checkbox">严肃
					</label>
					<label class="button">
						<input name="fmark" value="工作" type="checkbox">工作
					</label>
					<label class="button">
						<input name="fmark" value="回忆" type="checkbox">回忆
					</label>
        </div>
      </div>
      <div class="form-group">
        <div class="label">
          <label>所属文件夹:</label>
        </div>
        <div class="field">
          <select name="tid" class="input w80" style="line-height:17px;" 
          onchange="changesearch()">
              <c:forEach var="sn" items="${folders }">
              	<option value="${sn.tid }">${sn.tname }</option>
              </c:forEach>
            </select> 
        </div>
      </div> 
      <div class="form-group">
        <div class="label">
          <label>选择文件:</label>
        </div>
        <div class="field">
        	<button class="button bg-main icon-check-square-o" id="addFile" type="button"> 
        	添加一行</button>
        </div>
      </div>
      <div class="form-group">
        <div class="label">
        </div>
        <div class="field" id="myfile">
         	<div><a class="button input-file bg-green" href="javascript:void(0);">+ 浏览文件
         	<input size="100" type="file" name="mf" /></a>
         <a class="button input-file bg-red" href="javascript:void(0);"
          onclick="del(this)"> 删除</a>
         </div>
        </div>
      </div>
      <div class="form-group">
        <div class="label">
          <label></label>
        </div>
        <div class="field">
          <button class="button bg-main icon-check-square-o" type="submit"> 提交</button>
        </div>
      </div>
    </form>
  </div>
</div>
<script type="text/javascript">

		$("#addFile").click(function(){
			var html='<div><a class="button input-file bg-green" href="javascript:void(0);">
			+ 浏览文件<input size="100" type="file" name="mf" /></a>
			+  <a class="button input-file bg-
			red" onclick="del(this)"> 删除</a><div>'
			$("#myfile").append(html);
		});
		
		function del(obj){
			obj.parentElement.remove();
		}
</script>
</body>
</html>

3.修改AttachmentController


/**
	 * 跳转到添加页面
	 */
	@RequestMapping("toAddAttachment")
	public String toAddAttachment(HttpSession session, Model model) {
		User user = (User) session.getAttribute("user");
		// 根据用户ID查询文件夹列表
		List<Folder> folders = folderService.queryAllFolderByUidForList(user
				.getUid());
		model.addAttribute("folders", folders);
		return "attachment/add";
	}

	/**
	 * 添加
	 */
	@RequestMapping("addAttachment")
	public String toAddAttachment(MultipartFile[] mf, HttpSession session
	,AttachmentVo attachmentVo) {
		// 1,得到文件上传的目录
		String realPath = session.getServletContext().getRealPath("/upload");
		// 2,得到文件夹的名字
		String dirName = RandomUtils.createDirNameUserDate();
		// 3,构造文件夹对象
		File dirFile = new File(realPath, dirName);
		// 4,判断文件夹是否存在
		if (!dirFile.exists()) {
			dirFile.mkdirs();// 创建文件夹
		}
		for (int i = 0; i < mf.length; i++) {
			// 5,得到文件名
			String oldName = mf[i].getOriginalFilename();
			// 6,生成新的文件名
			String newName = RandomUtils.createFileNameUseTime(oldName);
			// 7,构造文件对象
			File file = new File(dirFile, newName);
			// 5,上传文件
			try {
				mf[i].transferTo(file);
				attachmentVo.setFoldname(oldName);
				attachmentVo.setFcontenttype(mf[i].getContentType());
				attachmentVo.setFcreatetime(new Date());
				attachmentVo.setFsize(Double.valueOf(mf[i].getSize()));
				// 存放相对路径
				attachmentVo.setFpath("upload/" + dirName + "/" + newName);
				// 说明文件上传成功
				attachmentService.addAttachment(attachmentVo);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "redirect:loadAllAttachment.action";
	}


  •  

3.文件管理下载
在AttachmentController中加入下载的方法

/**
	 * 下载
	 */
	@RequestMapping("downloadAttachment")
	public ResponseEntity downloadAttachment(AttachmentVo attachmentVo)throws Exception{
	
		Attachment attachment = attachmentService.queryAttachmentByFid(attachmentVo.getFid());
		String fpath = attachment.getFpath();
		String oldName = attachment.getFoldname();
		String realPath = WebUtils.getServletContext().getRealPath("/");
		String ablPath=realPath+"/"+fpath;
		File file=new File(ablPath);
		if(file.exists()){
			byte[] bytes=FileUtils.readFileToByteArray(file);
			HttpHeaders header=new HttpHeaders();
			header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			
			String filename = URLEncoder.encode(oldName, "UTF-8");
			header.setContentDispositionFormData("attachment", filename);
			ResponseEntity entity = new ResponseEntity(bytes, header,
					HttpStatus.CREATED);
			
			
			return entity;
		} else {
			PrintWriter out = WebUtils.getCurrentHttpServletResponse().getWriter();
			out.write("file not found");
			out.flush();
			out.close();
		}
		return null;
	}
		
  •  

最后改变jsp里面地址即可

4.文件管理删除
在AttachmentController中加入删除的方法

/**
	 * 删除
	 */
	@RequestMapping("deleteAttachment")
	public String deleteAttachment(AttachmentVo attachmentVo) {
		this.attachmentService.deleteAttachment(attachmentVo.getFid());
		return "redirect:loadAllAttachment.action";
	}

最后修改jsp里面网页地址

二、拦截器

servlet里面的过滤器 url-patten /* 默认拦截所有求
|–请求servlet
|–请求 静态资源文件

springmvc里面的拦截器只会拦截 controller
只能经过前端控制器的请求才有可能进入拦截器

创建拦截器

/**
 * 拦截器
 * @author LJH
 *
 */
public class SessionInteceptor implements HandlerInterceptor{

	/**
	 * 确定是否拦截的回调方法
	 * 返回值boolean      
	 * 		|--true  代表放行
	 * 		|--false 拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		System.out.println("preHandle");
		Object object = request.getSession().getAttribute("user");
		if(null!=object){
			return true;
		}
		//跳转到登陆页面
		response.sendRedirect("index.jsp");
		return false;
	}

	/**
	 * 当Controller里面的方法执行完成之后回调的方法
	 * @param request
	 * @param response
	 * @param handler 当前请求的Controller的对象
	 * @param modelAndView   就是Controller里面的方法执行完成之后要
	 * 交给视图解析器去解析的ModelAndView对象
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("postHandle--"+modelAndView.getViewName());
	}

	/**
	 * postHandle方法执行完成之后回调方法
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("afterCompletion");
		
	}
}

配置拦截器

	<!-- 拦截器配置 -->
	<mvc:interceptors>
		<!-- 配置未登陆的拦截器 -->
		<mvc:interceptor>
			<!-- 配置要拦截的路径   所有路径都拦截-->
			<mvc:mapping path="/**"/>
			<!-- 配置要放行的路径 -->
			<mvc:exclude-mapping path="/login/toLogin*"/>
			<mvc:exclude-mapping path="/login/login*"/>
			<!-- 注入拦截器 -->
			<bean class="com.sxt.inteceptor.SessionInteceptor"></bean>
		</mvc:interceptor>
	</mvc:interceptors>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值