SSM实现前后端分离,整合html作为视图引擎,解决跨域和拦截问题
按照csdn查的说sping4.2以上的jar 跨域使用@CrosssOrgin注解就可以跨域了但我不知道为啥没有用。不过使用跨域过滤器工具类的方式解决的跨域问题,后端的json数据能够跨域被接收到。
1. 写CrossingFilter过滤器类,实现(Interfaces)本地ApacheTomcat的Filter接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
public class CrossingFilter implements Filter { private boolean isCross = false;
@Override public void destroy() { isCross = false; }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (isCross) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; System.out.println("拦截请求: " + httpServletRequest.getServletPath()); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); httpServletResponse.setHeader("Access-Control-Max-Age", "0"); httpServletResponse.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"); httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true"); httpServletResponse.setHeader("XDomainRequestAllowed", "1"); } chain.doFilter(request, response); }
@Override public void init(FilterConfig filterConfig) throws ServletException { String isCrossStr = filterConfig.getInitParameter("IsCross"); isCross = isCrossStr.equals("true") ? true : false; System.out.println("跨域开启状态:" + isCrossStr); } }
|
2. 在web.xml文件中注册CrossingFilter过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13
| <filter> <filter-name>CrossingFilter</filter-name> <filter-class>com.dev.filter.CrossingFilter</filter-class> <init-param> <param-name>IsCross</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CrossingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
|
3. 配置web.xml,不拦截.html
1 2 3 4 5
| <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping>
|
总结:SSM我在学的时候就见识了它配置的复杂,这次接了的单子又是SSM+jQuery的,我还是一如既往的使用前后端分离,前端套的模板,就不得不解决跨域和配置html页面。(手动狗头)springboot是真香!
借鉴某老哥的博文解决问题,附上链接:
Java前后端分离SSM+Vue框架 后端解决跨域请求