Struts2文件上传与拦截器
1、文件上传
首先,我们需要了解文件上传的三种方式
a、上传到tomcat服务器
b、上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系
c、在数据库表中建立二进制字段,将图片存储到数据库
今天,我们用的就是第二种上传方式,不多说,直接上代码(在上一节的基础上完成图片上传)
jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="z" uri="/yj" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>小说目录</h2>
<br>
<form action="${pageContext.request.contextPath}/sy/clz_list.action"
method="post">
<!-- <input type="hidden" name="rows" value="20" /> -->
班級名:<input type="text" name="cname"> <input type="submit"
value="确定">
</form>
<a href="${pageContext.request.contextPath}/sy/clz_preSave.action">新增</a>
<table border="1" width="100%">
<tr>
<td>编号</td>
<td>班级名</td>
<td>教员</td>
<td>图片</td>
<td>操作</td>
</tr>
<c:forEach items="${clzList }" var="c">
<tr>
<td>${c.cid }</td>
<td>${c.cname }</td>
<td>${c.cteacher }</td>
<td>
<img alt="" style="width: 60px; height: 60px;" src="${pageContext.request.contextPath}${c.pic}">
</td>
<td>
<a href="${pageContext.request.contextPath}/sy/clz_preSave.action?cid=${c.cid}">修改</a>
<a href="${pageContext.request.contextPath}/sy/clz_del.action?cid=${c.cid}">删除</a>
<a href="${pageContext.request.contextPath}/sy/clz_preUpload.action?cid=${c.cid}">上传图片</a>
</td>
</tr>
</c:forEach>
</table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>
upload jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/sy/clz_upload.action" method="post" enctype="multipart/form-data">
<input type="hidden" name="cid" value="${clz.cid }"><br>
<input type="hidden" name="cname" value="${clz.cname }"><br>
<input type="hidden" name="cteacher" value="${clz.cteacher }"><br>
<!-- 注意:name对应的值决定了子控制器action属性的值 -->
<input type="file" name="file">
<input type="submit" >
</form>
</body>
</html>
action页面:
package com.yj.crud.web;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ModelDriven;
import com.yj.crud.dao.ClazzDao;
import com.yj.crud.entity.Clazz;
import com.yj.crud.util.PageBean;
public class ClazzAction extends BaseAction implements ModelDriven<Clazz>{
private ClazzDao clzDao = new ClazzDao();
private Clazz clz = new Clazz();
private File file;
private String fileContentType;
private String fileFileName;
public String list() {
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
try {
List<Clazz> list = this.clzDao.list(clz, pageBean);
// this.result = this.clzDao.list(clz, pageBean);
request.setAttribute("clzList", list);
request.setAttribute("pageBean", pageBean);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
return "list";
}
/**
* 文件上传
* @return
*/
public String upload() {
try {
// 注意:在Linux下是没有F盘的,Linux下只有一个盘符,那么意味着,当打包到LInux服务器的时候需要改动代码,
// 这个时候通常是这么解决的,将targetPath对应目录串,配置到资源文件中,通过properties类进行动态读取
// 那么当需要将项目发布到Linux服务器的时候,只需要改变xxx.properties文件中targetPth=/zking/T224/img即可
// 实际图片存储的位置
String targetDir = "F:/图片";
// 存储到数据库中的地址
String severPath = "/upload";
// FileUtils.copyFile(file, new File(targetDir+"/"+fileFileName));
copyBufFile(file, new File(targetDir+"/"+fileFileName));
// 注意:数据库存放的是网络请求地址,而不是本地图片存放地址
clz.setPic(severPath+"/"+fileFileName);
this.clzDao.edit(clz);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
/**
* FileUtils.copyFile的底层,并且通过缓冲区进行了增强
* @param source
* @param target
* @throws Exception
*/
public void copyBufFile(File source,File target) throws Exception{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target));
byte[] bbuf = new byte[1024];
int len = 0;
while((len = in.read(bbuf)) != -1) {
out.write(bbuf , 0 , len);
}
in.close();
out.close();
}
/**
* 跳转文件上传页面
* @return
*/
public String preUpload() {
try {
Clazz clazz = this.clzDao.list(clz, null).get(0);
request.setAttribute("clz", clazz);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
return "toUpload";
}
/**
* 跳转新增修改页面的通用方法
* @return
*/
public String preSave() {
if(clz.getCid()!=0) {
try {
Clazz clazz = this.clzDao.list(clz, null).get(0);
request.setAttribute("clz", clazz);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
return "preSave";
}
/**
* 新增
* @return
*/
public String add() {
try {
result = this.clzDao.add(clz);
} catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
| SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
/**
* 修改
* @return
*/
public String edit() {
try {
this.clzDao.edit(clz);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
/**
* 删除
* @return
*/
public String del() {
try {
this.clzDao.del(clz);
} catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
@Override
public Clazz getModel() {
return clz;
}
}
配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="sy" extends="base" namespace="/sy">
<!-- <action name="/demo_*" class="com.yj.web.HelloAction" method="{1}">
<result name="rs">/rs.jsp</result>
</action>
<action name="/stack_*" class="com.yj.test.DemoAction" method="{1}">
<result name="rs">/rs.jsp</result>
</action> -->
<action name="/clz_*" class="com.yj.crud.web.ClazzAction" method="{1}">
<result name="list">/clzList.jsp</result>
<result name="preSave">/clzEdit.jsp</result>
<result name="toList" type="redirectAction">/clz_list</result>
<result name="toUpload">/upload.jsp</result>
</action>
</package>
</struts>
结果如下:
与struts2的crud相比,图片加载出来了
2、拦截器
新建两个拦截器类
package com.yj.crud.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class OneInterceptor implements Interceptor {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("======OneInterceptor======1");
String invoke = invocation.invoke();
System.out.println("======OneInterceptor======2");
return invoke;
}
}
package com.yj.crud.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class TwoInterceptor implements Interceptor {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("======TwoInterceptor======1");
String invoke = invocation.invoke();
System.out.println("======TwoInterceptor======2");
return invoke;
}
}
package com.yj.crud.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class TwoInterceptor implements Interceptor {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("======TwoInterceptor======1");
String invoke = invocation.invoke();
System.out.println("======TwoInterceptor======2");
return invoke;
}
}
配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="sy" extends="base" namespace="/sy">
<!-- 配置拦截器 -->
<interceptors>
<interceptor name="one" class="com.yj.crud.interceptor.OneInterceptor"></interceptor>
<interceptor name="two" class="com.yj.crud.interceptor.TwoInterceptor"></interceptor>
</interceptors>
<!-- <action name="/demo_*" class="com.yj.web.HelloAction" method="{1}">
<result name="rs">/rs.jsp</result>
</action>
<action name="/stack_*" class="com.yj.test.DemoAction" method="{1}">
<result name="rs">/rs.jsp</result>
</action> -->
<action name="/clz_*" class="com.yj.crud.web.ClazzAction" method="{1}">
<!-- 配置拦截器 -->
<interceptor-ref name="one"></interceptor-ref>
<interceptor-ref name="two"></interceptor-ref>
<result name="list">/clzList.jsp</result>
<result name="preSave">/clzEdit.jsp</result>
<result name="toList" type="redirectAction">/clz_list</result>
<result name="toUpload">/upload.jsp</result>
</action>
</package>
</struts>
结果可以看出:页面被拦截,且报了空指针了