跨域問題時的Filter無效
阿新 • • 發佈:2018-06-14
一次 figure read iat print cross pan nco RR
wendal 1樓•404天前
蛋蛋的憂傷(qq_32b899df) 2樓•404天前
蛋蛋的憂傷(qq_32b899df) 3樓•404天前
wendal 4樓•404天前
蛋蛋的憂傷(qq_32b899df) 5樓•404天前
蛋蛋的憂傷(qq_32b899df) 6樓•404天前
wendal 7樓•404天前
wendal 8樓•404天前
蛋蛋的憂傷(qq_32b899df) 9樓•404天前
wendal 10樓•404天前
蛋蛋的憂傷(qq_32b899df) 11樓•404天前
我頁面用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 回復wendal 1樓•404天前
http://nutzam.com/core/mvc/cross_origin.html
蛋蛋的憂傷(qq_32b899df) 2樓•404天前
嗯.我的主模塊代碼如下:
@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 {
}
但是無效哎...
蛋蛋的憂傷(qq_32b899df) 3樓•404天前
好像根本就沒走過濾器....應該怎麽搞
wendal 4樓•404天前
加在具體方法上
蛋蛋的憂傷(qq_32b899df) 5樓•404天前
我這麽加了
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
蛋蛋的憂傷(qq_32b899df) 6樓•404天前
頁面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.
wendal 7樓•404天前
把你的PassHttpFilter刪了
wendal 8樓•404天前
然後把@POST也去掉
蛋蛋的憂傷(qq_32b899df) 9樓•404天前
打印日誌:
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.
wendal 10樓•404天前
用127.0.0.1
蛋蛋的憂傷(qq_32b899df) 11樓•404天前
厲害.了解得真全面,直接抓住問題重點,牛逼啊,中國的驕傲啊,我對你的崇拜如滔滔江水連綿不絕,黃河泛濫一發不可收拾矣,如果上天能給我再來一次的機會,我一定要跟你生在一個時代,跟你好好學習,啊哈哈哈哈,祝nutz越來越好,用戶越來越多~
跨域問題時的Filter無效