文档章节

javaWeb项目跨域问题解决方案:

文文1
 文文1
发布于 2018/11/26 10:30
字数 1284
阅读 7
收藏 2

1.简单的servlet项目

1.配置一个filter过滤器,过滤所有的请求,并且设置响应头

 

package Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*自定义拦截器 用于给每个都加上跨域的头*/
public class CORSFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //变成http的
        HttpServletResponse resp = (HttpServletResponse) response;
        // 添加参数,允许任意domain访问
        resp.setContentType("text/html;charset=UTF-8");
        //禁用缓存,确保网页信息是最新数据
        resp.setHeader("Pragma","No-cache");
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, HEAD, DELETE, PUT");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers",
                "X-Requested-With, Content-Type, Authorization, Accept, Origin, User-Agent, Content-Range, Content-Disposition, Content-Description");

        resp.setDateHeader("Expires", -10);
        chain.doFilter(request, resp);
    }
    public void init(FilterConfig filterConfig) {}


    public void destroy() {}
}

 

2.在web.xml中声明该过滤器(注意:最好放在最前面)

<filter>
        <filter-name>cors</filter-name>
        <filter-class>Filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

 

3.然后就可以直接解决跨域问题了

  2.使用springMVC下的跨域问题解决方案

1.先把整个springMVC项目搭建起来

  1.1在pom.xml中引入maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>smart_blog</name>
  <groupId>com.kylin</groupId>
  <artifactId>smart_blog</artifactId>
  <version>1.0-SNAPSHOT</version>

  <build>
    <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.7</version>
        <configuration>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8888</port>
              <maxIdleTime>30000</maxIdleTime>
            </connector>
          </connectors>
          <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
          <contextPath>/</contextPath>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>6</source>
          <target>6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12-beta-3</version>
      <scope>test</scope>
    </dependency>
    <!-- log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- spring 的基本依赖 开始 -->

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- spring 的基本依赖 结束 -->

    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.2.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.2.4</version>
    </dependency>

  </dependencies>

</project>

 

  1.2编写springMVC的核心配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />

    <context:component-scan base-package="com.kylin.Controller" />



    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

 

  1.3在web.xml中进行基本配置

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>com.kylin.Filter.CORSFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--拦截器的配置-->



  <!--前端控制器的配置-->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--配置核心配置文件的位置-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/springMVC.xml</param-value>
    </init-param>
    <!--随服务器启动而启动-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

 

2.编写过滤器CORSFilter来处理跨域问题

package com.kylin.Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*自定义拦截器 用于给每个都加上跨域的头*/
public class CORSFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //变成http的
        HttpServletResponse resp = (HttpServletResponse) response;
        // 添加参数,允许任意domain访问
        resp.setContentType("text/html;charset=UTF-8");
        //禁用缓存,确保网页信息是最新数据
        resp.setHeader("Pragma","No-cache");
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, HEAD, DELETE, PUT");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers",
                "X-Requested-With, Content-Type, Authorization, Accept, Origin, User-Agent, Content-Range, Content-Disposition, Content-Description");

        resp.setDateHeader("Expires", -10);
        chain.doFilter(request, resp);
    }
    public void init(FilterConfig filterConfig) {}


    public void destroy() {}
}

 

3.在web.xml中声明该过滤器(注意:位置最好放在最前面)

  由于web.xml中上面已经有了,就不再重复拷贝代码

4.就能正常的解决跨域问题

下面附上项目的目录结构:

  

 

附上前端vue框架的代码:

  ps:前端vue框架刚刚学,很多东西不懂~别介意

附上项目目录:

 

1.在config/index.js中配置代理

2.在router/index.js中配置路由

3.在组件中使用axios来发送post请求

src/components/Login.vue

<template>
  <div class="Login">
    <input type="tel" placeholder="innput your phone...." v-model="phone">
    <input type="password" placeholder="input your password" v-model="password">
    <button @click="postMethod">提交</button>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'Login',
  data () {
    return {
      phone:'',
      password:'',
    }
  },
  methods:{
    postMethod:function(){
      axios.post('http://192.168.253.13:8080/smart_blog/user',{
        phone:this.phone,
        password:this.password,
      })
      .then(function(res){
        console.log(res)
        // alert(res.data.message)
        alert(res.data.status)
      })
      .catch(function(err){
        console.log(err)
      })
    }
  }
  

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

4.打开vue项目所在的目录,输入npm start命令启动项目即可

5.开心的实现前后端分离~~~~~

本文转载自:https://www.cnblogs.com/shan-kylin/p/9428490.html

共有 人打赏支持
文文1
粉丝 23
博文 391
码字总数 124158
作品 0
长沙
程序员
私信 提问
ajax跨域,这应该是最全的解决方案了

前言 搬运的历史文章 从刚接触前端开发起,这个词就一直以很高的频率在身边重复出现,一直到现在,已经调试过N个跨域相关的问题了,16年时也整理过一篇相关文章,但是感觉还是差了点什么,于...

dailc
02/18
0
0
vue-cli创建项目,并且引入element-ui

注:本项目全部是按vue-cli3版本,旧版本有差异 1.创建项目,项目名称不能有大写字母 vue create project-name 2.进入项目目录,添加element-ui cd project-name vue add element 3.一般用v...

shatian
2018/10/25
0
0
跨域 webpack + vue-cil 中 proxyTable 处理跨域

跨域 了解同源政策:所谓"同源"指的是"三个相同"。 协议相同 域名相同 端口相同 解决跨域 jsonp 缺点:只能get请求 ,需要修改B网站的代码 cors 这个方案缺点 是 ie6 7 兼容不好(倒是不见得...

筱月
2018/07/19
0
0
ajax测试与校验工具

前言 时至今日,仍然是前端必用的一个功能。 但是,在实际的工作中,发现存在大量的接口人员无法区分和请求的区别,导致某些接口在接口人员自己的请求工具中测试正常,但是实际用到请求时,就...

撒网要见鱼
2017/08/06
0
0
springboot中通过cors协议解决跨域问题

1、对于前后端分离的项目来说,如果前端项目与后端项目部署在两个不同的域下,那么势必会引起跨域问题的出现。 针对跨域问题,我们可能第一个想到的解决方案就是jsonp,并且以前处理跨域问题...

灌南高手No1
2018/12/26
0
0

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 周二乱弹 —— 我敢给你上菜,你敢吃么?

Osc乱弹歌单(2019)请戳(这里) 【今日歌曲】 @花间小酌 :分享周深的单曲《缘起 (前世今生版)》人间多的是长了两只脚的恶人, 《缘起 (前世今生版)》- 周深 手机党少年们想听歌,请使劲儿...

小小编辑
57分钟前
121
9
万能的Python,还能用来制作高大上的进度条?

对于开发或者运维来说,使用Python去完成一些跑批任务,或者做一些监控事件是非常正常的情况。那么如何有效的监控任务的进度,除了在任务中加上log外,还能不能有另一种方式来了解任务进展到...

上海小胖
今天
8
0
如何嵌入 HTML 到 iPython notebook的输出

如何嵌入 HTML 到 iPython notebook的输出 iPython notebook中可以嵌入 HTML,也适用于JupyterHub和JupyterLab环境。不仅可以显示常用的HTML标签文本,甚至可以嵌入脚本交互操作和Frame分隔框...

openthings
今天
2
0
四、RabbitMQ3.7在CentOS7下的安装

安装依赖 sudo yum install -y gcc gcc-c++ glibc-devel make ncurses-devel openssl-devel autoconf java-1.8.0-openjdk-devel git 创建yum源 vi /etc/yum.repos.d/rabbitmq-erlang.repo [......

XuePeng77
今天
2
0
android 延长Toast的时长

示例:myToast(5000,"hello"); public void myToast(int showTime, String msg) { Toast hello = Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT); new CountDownTimer(......

雨焰
昨天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部