Struts2的拦截器与简单的文件上传

一:Interceptor(拦截器)
1、有两种形式写拦截器
①、implements Interceptor:实现拦截器接口
②、extends AbstractInterceptor:继承抽象类
在这里插入图片描述
注意:
①、com.opensymphony.xwork2.interceptor.Interceptor;包下的
②、与过滤器一样,拦截器也需要放行

2、配置(struts-sy.xml)
在这里插入图片描述
注意:
①、所有的拦截器,自定义的或引用别人的都需要配置在interceptors中
②、在action中调用

3、 与filter的区别:先过filter再过interceptor

二、简单的文件上传
1、文件上传的三种方案
①、将上传的文件以二进制的形式存放到数据库 oa系统 activiti工作流框架
②、将文件上传到文件服务器(硬盘足够大)中
③、将文件上传到tomcat所在的普通web服务器

2、真实路径与虚拟路径的概念
①、所谓真实路径指的是在自己电脑上能够找到的路径
②、所谓虚拟路径,在自己的电脑上是看不到的,路径在别人的电脑(tomcat所在的位置)上能够看得到

3、上传文件
①、在action里面写方法:

package com.zking.five;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import com.zking.test.web.BaseAction;


public class UploadAction extends BaseAction {
	
	private File file;//变量名指的是jsp的name属性,就是你要上传的文件   xxx
	private String fileContentType;//xxxContentType
	private String fileFileName;//xxxFileName
	
	private String serverDir = "/upload";
	
	public String upload() {
		String realPath = getRealPath(serverDir + "/" +fileFileName);
		try {
			/**
			 * 参数1:本地图片文件
			 * 参数2:在服务器生成的文件
			 */
			FileUtils.copyFile(file, new File(realPath));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 获取Linux下的上传文件的具体所在位置
	 * @param path
	 * @return
	 */
	
	private String getRealPath(String path) {
		// TODO Auto-generated method stub
		return application.getRealPath(path);
	}

	public String openAs() {
		String type = "image/jpeg";
		String name = "1.jpg";
		response.setContentType(type);
		response.setHeader("Content-Disposition","filename=" + name);//文件名
		/**
		 *  将远程的图片输出到本地
		 * 	数据源inputstream:远程   new file(realPath)
		 * 	目的:输出到本地的jsp  response.getOutputStream()
		 */
		String realPath = getRealPath(serverDir + "/" +name);
		System.out.println(realPath);
		try {
			/**
			 * 别人提供的上传图片时间流
			 */
//			FileUtils.copyFile(new File(realPath), response.getOutputStream());
			/**
			 * 自定义上传图片时间流(速度较快)
			 */
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(realPath)));
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			copyStream(in, out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private void copyStream(BufferedInputStream in,BufferedOutputStream out) throws IOException {
		byte[] bbuf = new byte[1024];
		int len = 0;
		try {
			while((len = in.read(bbuf))!=-1) {
				out.write(bbuf, 0, len);
			}
			in.close();
			out.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public String download() {
		String type = "image/jpeg";
		String name = "1.jpg";
		response.setContentType(type);
		response.setHeader("Content-Disposition","attachment;filename=" + name);
		
		/**
		 * 将远程的图片输出到本地
		 * 	数据源inputstream:远程   new file(realPath)
		 * 	目的:输出到本地的jsp  response.getOutputStream()
		 */
		String realPath = getRealPath(serverDir + "/" +name);
		try {
//			FileUtils.copyFile(new File(realPath), response.getOutputStream());
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(realPath)));
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			copyStream(in, out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	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;
	}
}

②、配置(struts-sy.xml):

<?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>
<!-- 
	namespace:在内存中划分具体的控件
	name:给package包取个名字
 -->
	<package name="sy" extends="base" namespace="/sy">

		
		<action name="interAction" class="com.zking.five.InterceptorAction">
			<interceptor-ref name="oneInter"></interceptor-ref>
			<interceptor-ref name="twoInter"></interceptor-ref>
		</action>
		
		<action name="uploadAction_*" class="com.zking.five.UploadAction" method="{1}">
			<result name="success">/success.jsp</result>
		</action>
		
	</package>
</struts>

③、展示页面(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>
</body>
<h1>struts的上传下载</h1>
<!-- enctype="multipart/form-data" method="post" 指定是复杂的表单 -->
<form action="${pageContext.request.contextPath }/sy/uploadAction_upload.action" enctype="multipart/form-data" method="post">
	<input type="file" name="file">
	<input type="submit" value="上传">
</form>

</html>

④、最后的展示结果:
在这里插入图片描述
在这里插入图片描述
ps:上面的只是定死的。

4、要从数据库中调用图片,上传图片:
①、首先需要在表中加入图片名称(name)和图片类型(type),也可以自己定义
②、在实体类中加入这两个列
③、在dao方法中加入一个根据id修改图片名称和图片类型的方法

public void upload(Student student) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, SQLException {
		String sql = "update t_struts_student set type=?,name=? where sid=?";
		super.executeUpdate(sql, new String[] {"type","name","sid"}, student);
	}

④、在action里面需要修改方法

package com.zking.five;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ModelDriven;
import com.zking.test.dao.StudentDAO;
import com.zking.test.entity.Student;
import com.zking.test.web.BaseAction;

/**
 * 文件上传的三种方案
 * 	1、将上传的文件以二进制的形式存放到数据库   oa系统    activiti工作流框架
 * 	2、将文件上传到文件服务器(硬盘足够大)中
 * 	3、将文件上传到tomcat所在的普通web服务器
 * 
 * 真实路径与虚拟路径的概念
 * 	1、所谓真是路径指的是在自己电脑上能够找到的路径
 * 	2、所谓虚拟,在自己的电脑上是看不到的,路径在别人的电脑(tomcat所在位置)上能够看到
 * @author PSS
 *
 */

public class UploadAction extends BaseAction implements ModelDriven<Student>{
	private Student student = new Student();
	private StudentDAO studenDAO = new StudentDAO();
	private File file;//变量名指的是jsp的name属性,就是你要上传的文件   xxx
	private String fileContentType;//xxxContentType
	private String fileFileName;//xxxFileName
	
	private String serverDir = "/upload";
	
	public String upload() {
		String realPath = getRealPath(serverDir + "/" +fileFileName);
		System.out.println(fileContentType);
		System.out.println(fileFileName);
		System.out.println(realPath);
		System.out.println(student.getSid());
		try {
			FileUtils.copyFile(file, new File(realPath));
			/**
			 * 参数1:本地图片文件
			 * 参数2:在服务器生成的文件
			 */
			student.setType(fileContentType);
			student.setName(fileFileName);
			this.studenDAO.upload(student);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 获取Linux下的上传文件的具体所在位置
	 * @param path
	 * @return
	 */
	
	private String getRealPath(String path) {
		// TODO Auto-generated method stub
		return application.getRealPath(path);
	}

	public String openAs() {
		response.setContentType(student.getType());
		response.setHeader("Content-Disposition","filename=" + student.getName());
		System.out.println(student.getName());
		System.out.println(student.getType());
		/**
		 * 将远程的图片输出到本地
		 * 	数据源inputstream:远程   new file(realPath)
		 * 	目的:输出到本地的jsp  response.getOutputStream()
		 */
		String realPath = getRealPath(serverDir + "/" +student.getName());
		try {
//			FileUtils.copyFile(new File(realPath), response.getOutputStream());
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(realPath)));
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			copyStream(in, out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private void copyStream(BufferedInputStream in,BufferedOutputStream out) throws IOException {
		byte[] bbuf = new byte[1024];
		int len = 0;
		try {
			while((len = in.read(bbuf))!=-1) {
				out.write(bbuf, 0, len);
			}
			in.close();
			out.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public String download() {
		response.setContentType(student.getType());
		response.setHeader("Content-Disposition","attachment;filename=" + student.getName());
		
		/**
		 * 将远程的图片输出到本地
		 * 	数据源inputstream:远程   new file(realPath)
		 * 	目的:输出到本地的jsp  response.getOutputStream()
		 */
		String realPath = getRealPath(serverDir + "/" +student.getName());
		try {
			FileUtils.copyFile(new File(realPath), response.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	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 Student getModel() {
		// TODO Auto-generated method stub
		return student;
	}
}

⑤、配置:

<?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>
<!-- 
	namespace:在内存中划分具体的控件
	name:给package包取个名字
 -->
	<package name="sy" extends="base" namespace="/sy">
	
		<action name="clazzAction" class="com.zking.test.web.ClazzAction"></action>
		<action name="studentAction_*" class="com.zking.test.web.StudentAction" method="{1}">
			<result name="list">/jsp/listStudent.jsp</result>
			<result name="add">/jsp/addStudent.jsp</result>
			<result name="edit">/jsp/editStudent.jsp</result>
			<result name="success" type="redirect">/sy/studentAction_list.action</result>
		</action>
		
		<action name="uploadAction_*" class="com.zking.five.UploadAction" method="{1}">
			<result name="success" type="redirect">/sy/studentAction_list.action</result>
		</action>
		
	</package>
</struts>

⑥、jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="/jsp/common/head.jsp" %>
<!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>
<h1>List</h1>
<!-- var是非根对象 -->
<s:action name="clazzAction" namespace="/sy" var="clazzList"></s:action>
<s:form namespace="/sy" action="studentAction_list">
	<s:textfield label="姓名" name="sname"/>
	<s:select label="班级" name="cid" list="#clazzList.result" listKey="cid" listValue="cname" headerKey="" headerValue="===请选择==="></s:select>
	<s:submit value="ok"></s:submit>
</s:form>
<s:url namespace="/sy" action="studentAction_toAdd" var="toAddUrl"></s:url>
<s:a href="%{#toAddUrl}">新增</s:a>
	<table border="1" width="100%">
		<tr>
			<td>序号</td>
			<td>学号</td>
			<td>姓名</td>
			<td>拼音</td>
			<td>图片</td>
			<td>性别</td>
			<td>标记</td>
			<td>班级</td>
			<td>操作</td>
		</tr>
			<s:iterator var="s" value="result">
		<tr>
			<td>序号</td>
			<td><s:property value="#s.sid"/></td>
			<td><s:property value="#s.sname"/></td>
			<td><s:property value="#s.spin"/></td>
			<td>
				<s:url var="openAsUrl" namespace="/sy" action="uploadAction_openAs.action">
					<s:param name="name" value="#s.name"></s:param>
					<s:param name="type" value="#s.type"></s:param>
				</s:url>
				<img alt="" src='<s:property value="openAsUrl"/>' width="60px" height="60px">
			</td>
			<td><s:property value="#s.sex"/></td>
			<td><s:property value="#s.mark"/></td>
			<td><s:property value="#s.cname"/></td>
			<td>
			<form action="${pageContext.request.contextPath }/sy/uploadAction_upload.action"  enctype="multipart/form-data" method="post">
				<input type="file" name="file"/>
				<input type="hidden" name="sid" value='<s:property value="#s.sid"/>'/>
				<input type="submit" value="提交">
			</form>
				<s:url var="downloadUrl" namespace="/sy" action="uploadAction_download.action">
				    <s:param name="name" value="#s.name"></s:param>
				    <s:param name="type" value="#s.type"></s:param>
				</s:url>
				<s:a href="%{#downloadUrl}">下载</s:a>
				<s:url namespace="/sy" action="studentAction_toEdit" var="toEditUrl">
					<s:param name="sid" value="#s.sid"></s:param>
				</s:url>
				<s:a href="%{#toEditUrl}">修改</s:a>
				<s:url namespace="/sy" action="studentAction_delete" var="toDeleteUrl">
					<s:param name="sid" value="#s.sid"></s:param>
				</s:url>
				<s:a href="%{#toDeleteUrl}">删除</s:a>
			</td>
		</tr>
		</s:iterator>
	</table>
</body>
</html>

⑦、展示的结果:
在这里插入图片描述

ps:可能会有些长,但是还是很详细的。

相关推荐
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页