Filter实例,读取地址栏,servlet重定向,servlet上传

1.上面配置filter

2.Filter中如果不满足条件可以写chain.doFilter(request);return;

首先,你要明白过滤器的原理。过滤器执行完chain.dofilter(req,resp)后,放行到你所在的servlet或jsp,执行完servlet或者jsp后,或重新回到过滤器执行完剩余代码,要是你在剩余代码中又有请求发出,程序就会发生发出多次请求错误。总的来说,就是chain.dofilter(req,resp)下面的代码不能有请求,如果有,请加上return。

如果在filter中,先call了response.sendRedirect(),然后执行chain.doFilter()。将会报错:response has committed;就是说sendRedirect和doFilter是一样的效果的,就是放行当前过滤器。所以下次,不要再重定向后加doFilter了。

3.下面配置servlet,Servlet中根据session中的值进行转发

 

获取真实IP地址
/**
	 * 获取当前真实Ip
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if("127.0.0.1".equals(ip)||"0:0:0:0:0:0:0:1".equals(ip)){
                //根据网卡取本机配置的IP
                 InetAddress inet=null;
                 try {
                     inet = InetAddress.getLocalHost();
                 } catch (UnknownHostException e) {
                     e.printStackTrace();
                 }
                 ip= inet.getHostAddress();
            }
		}
		return ip;
	}

servlet上传实现

前台

<-- 定义form表单 类型为enctype="MULTIPART/FORM-DATA" -->
<div class="_formDiv">
	<form action="./FileResource" enctype="MULTIPART/FORM-DATA" method=post class="_form" target="fileResourceIFrame">
		<table class="dialog_editformitems flat">
			<tr>			
				<td width="100px" style="font-size: 16px;">${File}${Colon}<font color="red" >*</font></td>
				<td style="font-size: 14px;"><input type="file" name="_file"  class="_file" style="width:100%;"/></td>
			</tr>
		</table>
	<form>
</div>
<!-- 显示加载中字体 -->
<label class="_msg" style="display: none">&nbsp;&nbsp;${Note}${Colon}<font color="red">${Uploadingfiles}. . . </font></label>
<!-- 显示加载中图形 -->
<div class="_loadingDiv" style="display: none; width: 100%; height: 150px; overflow: auto; background: url(img/loading.gif) no-repeat center center"></div>
<!-- 通过这个隐藏的iframe来接收后台响应的数据 -->
<span style="display:none"><iframe name="fileResourceIFrame"></iframe></span>

 js

var BaseDialogEx = jsloader.resolve("freequery.dialog.BaseDialogEx");
var util = jsloader.resolve("freequery.common.util");
var dialogFactory = jsloader.resolve("freequery.dialog.dialogFactory");

//构造器初始化一个对话框
var UploadFileDialog = function() {
	UploadFileDialog.superclass.constructor.call(this);
};

lang.extend(UploadFileDialog, BaseDialogEx);

//初始化方法,包括加载html,绑定事件等
UploadFileDialog.prototype.init = function(parent, param, fn, obj) {
	UploadFileDialog.superclass.init.call(this,parent, param, fn, obj);

	var template = domutils.doGet("template/freequery/dialog/UploadFileDialog.template");
	this.dialogBody.innerHTML = template;
	parent=this.dialogBody;
	this.form = domutils.findElementByClassName(parent, "_form");
	this.file = domutils.findElementByClassName(parent, "_file");
	if(domutils.isFirefox()){
		this.file.style.height = "auto";
	}
	this.loadingDiv = domutils.findElementByClassName(parent, "_loadingDiv");
	this.formDiv = domutils.findElementByClassName(parent, "_formDiv");
	this.titleDiv = domutils.findElementByClassName(parent, "_titleDiv");
	this.msgLabel = domutils.findElementByClassName(parent, "_msg");
};

//关闭对话框
UploadFileDialog.prototype.doClose = function(e) {
	this.close(false);
};

//点击提交按钮的方法
UploadFileDialog.prototype.doOK = function(e) {
	if (this.file.value==""){
		alert("${Thelinkscannotbeempty}!");
		this.file.focus();
		return;
	}
		this.msgLabel.style.display = "";
		this.loadingDiv.style.display = "";
		this.btnOK.disabled = true;
		this.btnCancel.disabled = true;
		this.formDiv.style.display = "none";
		this.titleDiv.style.display = "none";
		this.doExcute();
};

//后台servlet返回数据给iframe中,然后parent.callbackHandler调用这边
UploadFileDialog.prototype.callbackHandler = function(msg) {
	this.close(false);
	alert(msg);
	if(msg.indexOf("${Failed}") != -1){
		this.msgLabel.style.display = "none";
		this.loadingDiv.style.display = "none";
		this.btnOK.disabled = false;
		this.btnCancel.disabled = false;
		this.formDiv.style.display = "";
		this.titleDiv.style.display = "";
		return;
	}
}

//提交方法
UploadFileDialog.prototype.doExcute = function() {
	this.form.action = "./uploadFile";
	if (!domutils.isIE6()) {
		this.form.submit();
	}
	else {
		try {
			this.form.submit();
		}
		catch(e) {
			var modalWindow = jsloader.resolve("freequery.common.modalWindow");
			modalWindow.open("${Fileorpathisnotexisting}");
			this.msgLabel.style.display = "none";
			this.loadingDiv.style.display = "none";
			this.btnOK.disabled = false;
			this.btnCancel.disabled = false;
			this.formDiv.style.display = "";
			this.titleDiv.style.display = "";
		}
	}
}

注意:设置文件下载或导出格式为:如果是导出下载的话

response.setHeader("Content-disposition", "attachment; filename=Excel.xls")

package com.wangm.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import smartbi.config.SystemConfigService;
import smartbi.repository.SystemConfig;
import smartbi.util.StringUtil;

public class UploadFileServlet extends HttpServlet {

	private static final long serialVersionUID = -8699756399405416385L;
	private static final Logger LOG = LoggerFactory.getLogger(UploadFileServlet.class);

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		this.doPost(req, res);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//返回信息
		String info;
		//解决post请求的乱码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		// 核心Api
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload fileUpload = new ServletFileUpload(factory);

		// 判断是否是muitipart/form-data类型
		if (!ServletFileUpload.isMultipartContent(request)) {
			response.getWriter().println("表单的enctype属性不是multipart/form-data类型");
            return;		
        }

		// 设置单个文件上传大小 2M
		// fileUpload.setFileSizeMax(2*1024*1024);
		// 设置表单总大小
		fileUpload.setSizeMax(10 * 1024 * 1024);
		// 解析请求
		try {
			List<FileItem> parseRequest = fileUpload.parseRequest(request);
			// 获取数据
			for (FileItem fileItem : parseRequest) {
				// 判断数据类型是不是普通的form表单字段
				if (!fileItem.isFormField()) {
					// 上传文件
					String fileName = fileItem.getName();
					InputStream fileStream = fileItem.getInputStream();
					
					SystemConfig systemConfig = SystemConfigService.getInstance().getSystemConfig("SYSTEM_CONFIG_EXT_FILEUPLOADADDRESS");
					if(systemConfig == null || StringUtil.isNullOrEmpty(systemConfig.getValue())){
						throw new RuntimeException("系统选项中,文件上传地址为空,请配置后上传!");
					}
					String systemPath = systemConfig.getValue();
					systemPath = systemPath.replace("/", File.separator).replace("\\", File.separator);
					// 使用UUID+文件名的方式,避免文件重名
					String realFileName = UUID.randomUUID().toString() + "-" + fileName;
					// 创建要保存的文件
					File file = new File(systemPath, realFileName);
					// 判断文件夹是否存在
					if (!file.getParentFile().exists()) {
						// 创建文件夹[多级文件夹]file.madir是创建单一文件夹
						file.getParentFile().mkdirs();
					}

					// 创建输出流
					OutputStream out = new FileOutputStream(file);
					// 创建字节缓存
					byte[] buffer = new byte[1024];
					int len = -1;
					// 一次读取1kb(1024byte),返回-1表明读取完毕
					while ((len = fileStream.read(buffer)) != -1) {
						// 一次写入1kb(1024byte)
						out.write(buffer, 0, len);
					}

					// 冲刷流资源
					out.flush();
					// 关闭流
					out.close();
					fileStream.close();
				}
			}
			response.setHeader("Content-Disposition", "");
			response.setContentType("text/html; charset=UTF-8");
			info = "上传文件成功";
			StringBuffer sb = new StringBuffer();
			sb.append("<head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head>");
			sb.append("<script>");
			sb.append("  if(parent.dialog && parent.dialog.callbackHandler){");
			sb.append("    parent.dialog.callbackHandler('" + info + "');");
			sb.append("  }else{");
			sb.append("    parent.alert('" + info + "');");
			sb.append("  }");
			sb.append("</script>");
			info = sb.toString();
			response.getOutputStream().write(info.getBytes("UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("FileResourse Error", e);
			response.setHeader("Content-Disposition", "");
			response.setContentType("text/html; charset=UTF-8");
			info = e.getMessage();
			StringBuffer sb = new StringBuffer();
			sb.append("<head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head>");
			sb.append("<script>");
			sb.append("  if(parent.dialog && parent.dialog.callbackHandler){");
			sb.append("    parent.dialog.callbackHandler('" + info + "');");
			sb.append("  }else{");
			sb.append("    parent.alert('" + info + "');");
			sb.append("  }");
			sb.append("</script>");
			response.getOutputStream().write(sb.toString().getBytes("UTF-8"));
		}

	}

	public void init(ServletConfig config) throws ServletException {
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值