NutzCN Logo
问答 跨域问题时的Filter无效
发布于 2745天前 作者 蛋蛋的忧伤 2815 次浏览 复制 上一个帖子 下一个帖子
标签:

我页面用Web Uploader进行图片上传,后台使用一个过滤器解决跨域的options问题,然后我给入口类加上了这个过滤器注解配置,但是无效
页面代码:

<body>
<div id="uploader-demo">
    <!--用来存放item-->
    <div id="fileList" class="uploader-list"></div>
    <div id="filePicker">选择图片</div>
</div>
<script>
    // 初始化Web Uploader
    var uploader = WebUploader.create({

        // 选完文件后,是否自动上传。
        auto: true,
        withCredentials: true,  // 支持CORS跨域带cookie

        // 文件接收服务端。
        server: 'http://127.0.0.1:8080/mychat/upload/image',

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建,可能是input元素,也可能是flash.
        pick: '#filePicker',

        // 只允许选择图片文件。
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        }
    });
</script>

入口类代码:

package com.mychat.controol;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import com.mychat.filter.PassHttpFilter;

@IocBean
@At("/upload")
@Ok("json")
@Filters(@By(type=PassHttpFilter.class))
public class UploadModule {
	
	/**
	 * 发送图片,上传图片接口
	 * @param file
	 * @param context
	 * @return
	 */
	@At
	@POST
	@AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
	public Object image(@Param("file") TempFile file,ServletContext context){
		System.out.println(file.getName());
		System.out.println(file.getMeta().getFileLocalName());
		InputStream in = null;
		OutputStream out = null;
		File f = file.getFile();
		String relpath = context.getRealPath("upload")+"\\"+file.getMeta().getFileLocalName();
		try {
			 in = new FileInputStream(file.getFile());
			 out = new FileOutputStream(relpath);
			byte[] buf = new byte[1024];
			int len = 0;
			while((len = in.read(buf))!=-1){
				out.write(buf,0,buf.length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		String url = "/mychat/upload/"+file.getMeta().getFileLocalName();	//eclipse默认的tomcat目录是在其缓存文件中,你要自己指定到tomcat所在目录
		
		//构建json数据
		Map<String,Object> data = new HashMap<String,Object>();
		data.put("code", "0");
		data.put("msg", "");
		Map<String,String> sourceUrl = new HashMap<String,String>();
		sourceUrl.put("src", url);
		data.put("data", sourceUrl);
		
		return data;
	}
	
	@At
	public void test(){
		System.out.println("lalala");
	}
	
}

Filter代码:

package com.mychat.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.View;

public class PassHttpFilter implements ActionFilter  {

	@Override
	public View match(ActionContext actionContext) {
			System.out.println("execute passHttpFilter...");
			HttpServletResponse res = actionContext.getResponse();
			HttpServletRequest request = actionContext.getRequest();
	        res.setContentType("textml;charset=UTF-8");
	        res.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
	        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
	        res.setHeader("Access-Control-Max-Age", "0");
	        res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
	        res.setHeader("Access-Control-Allow-Credentials", "true");
	        res.setHeader("XDomainRequestAllowed","1");
	        return null;
	}
	
}

页面进行文件上传后,控制台打印了这句话:

2017-05-04 16:11:30,016 org.nutz.mvc.impl.ActionInvoker.getActionChain(ActionInvoker.java:87) DEBUG - Path=[/upload/image] available methods[POST] but request [OPTIONS], using the wrong http method?
2017-05-04 16:11:30,017 org.nutz.mvc.impl.UrlMappingImpl.get(UrlMappingImpl.java:110) DEBUG - Search mapping for [OPTIONS] path=/upload/image : NOT Action match

这个意思就是没走filter,但为何没走呢? 还有我在主模块上加上这个过滤器也试过,但是还没用

11 回复

嗯.我的主模块代码如下:


@Modules(scanPackage=true) @IocBy(type=ComboIocProvider.class, args={"*js", "ioc/",// 这个package下所有带@IocBean注解的类,都会登记上 "*anno", "com.mychat", "*tx", // 事务拦截 aop "*async"}) // 异步执行aop @Encoding(input="utf-8",output="utf-8") @Filters({@By(type=CrossOriginFilter.class)}) @ChainBy(args="mvc/nutzbook-mvc-chain.js") public class MainModule { }

但是无效哎...

好像根本就没走过滤器....应该怎么搞

加在具体方法上

我这么加了

package com.mychat.controol;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CrossOriginFilter;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import com.mychat.filter.PassHttpFilter;

@IocBean
@At("/upload")
@Ok("json")
public class UploadModule {
	
	/**
	 * 发送图片,上传图片接口
	 * @param file
	 * @param context
	 * @return
	 */
	@At
	@POST
	@AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
	@Filters({@By(type=CrossOriginFilter.class),@By(type=PassHttpFilter.class)})
	public Object image(@Param("file") TempFile file,ServletContext context){
		System.out.println(file.getName());
		System.out.println(file.getMeta().getFileLocalName());
		InputStream in = null;
		OutputStream out = null;
		File f = file.getFile();
		String relpath = context.getRealPath("upload")+"\\"+file.getMeta().getFileLocalName();
		try {
			 in = new FileInputStream(file.getFile());
			 out = new FileOutputStream(relpath);
			byte[] buf = new byte[1024];
			int len = 0;
			while((len = in.read(buf))!=-1){
				out.write(buf,0,buf.length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		String url = "/mychat/upload/"+file.getMeta().getFileLocalName();	//eclipse默认的tomcat目录是在其缓存文件中,你要自己指定到tomcat所在目录
		
		//构建json数据
		Map<String,Object> data = new HashMap<String,Object>();
		data.put("code", "0");
		data.put("msg", "");
		Map<String,String> sourceUrl = new HashMap<String,String>();
		sourceUrl.put("src", url);
		data.put("data", sourceUrl);
		
		return data;
	}
	
	
	@At
	public void test(){
		System.out.println("lalala");
	}
	
}

日志依然是:

2017-05-04 16:20:00,956 org.nutz.mvc.impl.ActionInvoker.getActionChain(ActionInvoker.java:87) DEBUG - Path=[/upload/image] available methods[POST] but request [OPTIONS], using the wrong http method?
2017-05-04 16:20:00,957 org.nutz.mvc.impl.UrlMappingImpl.get(UrlMappingImpl.java:110) DEBUG - Search mapping for [OPTIONS] path=/upload/image : NOT Action match

页面js报错为:

跨域文件上传.html:1 XMLHttpRequest cannot load http://127.0.0.1:8080/mychat/upload/image. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.

把你的PassHttpFilter删了

然后把@POST也去掉

打印日志:

2017-05-04 16:26:37,383 org.nutz.mvc.impl.UrlMappingImpl.get(UrlMappingImpl.java:101) DEBUG - Found mapping for [OPTIONS] path=/upload/image : UploadModule.image(UploadModule.java:44)
2017-05-04 16:26:37,385 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:151) DEBUG - Get 'uploadModule'<class com.mychat.controol.UploadModule>
2017-05-04 16:26:37,385 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:151) DEBUG - Get '$aop_async'<interface org.nutz.ioc.aop.config.AopConfigration>
2017-05-04 16:26:37,387 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:177) DEBUG - 	 >> Load definition name=$aop_async
2017-05-04 16:26:37,391 org.nutz.ioc.loader.combo.ComboIocLoader.load(ComboIocLoader.java:169) DEBUG - Found IocObject($aop_async) in AsyncAopIocLoader@2118378618
2017-05-04 16:26:37,392 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:209) DEBUG - 	 >> Make...'$aop_async'<interface org.nutz.ioc.aop.config.AopConfigration>
2017-05-04 16:26:37,395 org.nutz.ioc.impl.ScopeContext.save(ScopeContext.java:64) DEBUG - Save object '$aop_async' to [app] 
2017-05-04 16:26:37,407 org.nutz.ioc.aop.SimpleAopMaker.<init>(SimpleAopMaker.java:79) DEBUG - Load AopConfigure for anno=org.nutz.ioc.aop.Aop by type=org.nutz.ioc.aop.config.impl.AnnotationAopConfigration
2017-05-04 16:26:37,408 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:177) DEBUG - 	 >> Load definition name=uploadModule
2017-05-04 16:26:37,408 org.nutz.ioc.loader.combo.ComboIocLoader.load(ComboIocLoader.java:169) DEBUG - Found IocObject(uploadModule) in AnnotationIocLoader(packages=[com.mychat])
2017-05-04 16:26:37,408 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:209) DEBUG - 	 >> Make...'uploadModule'<class com.mychat.controol.UploadModule>
2017-05-04 16:26:37,408 org.nutz.ioc.aop.impl.DefaultMirrorFactory.getMirror(DefaultMirrorFactory.java:70) DEBUG - Load class com.mychat.controol.UploadModule without AOP
2017-05-04 16:26:37,409 org.nutz.ioc.impl.ScopeContext.save(ScopeContext.java:64) DEBUG - Save object 'uploadModule' to [app] 
2017-05-04 16:26:37,409 org.nutz.mvc.filter.CrossOriginFilter.match(CrossOriginFilter.java:49) DEBUG - Feedback -- [*] [get, post, put, delete, options] [origin, content-type, accept] [true]
2017-05-04 16:26:37,411 com.mychat.mvc.LogTimeProcessor.process(LogTimeProcessor.java:31) DEBUG - [OPTIONS]URI=/mychat/upload/image 28ms

js报错:

XMLHttpRequest cannot load http://127.0.0.1:8080/mychat/upload/image. Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:63342' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

厉害.了解得真全面,直接抓住问题重点,牛逼啊,中国的骄傲啊,我对你的崇拜如滔滔江水连绵不绝,黄河泛滥一发不可收拾矣,如果上天能给我再来一次的机会,我一定要跟你生在一个时代,跟你好好学习,啊哈哈哈哈,祝nutz越来越好,用户越来越多~

添加回复
请先登陆
回到顶部