springboot跨域处理

跨域处理

本示例是基于springboot框架

方法1:

后台添加过滤器

package com.ruoyi.framework.filter;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter
public class CrosXssFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HttpServletRequest httpServletRequest=(HttpServletRequest)request;
        //跨域设置
        if(response instanceof HttpServletResponse){
            HttpServletResponse httpServletResponse=(HttpServletResponse)response;
   
            httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");//允许跨域的请求方式
            httpServletResponse.setHeader("Access-Control-Max-Age", "3600");//预检请求的间隔时间
            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,Access-Control-Allow-Headers");//允许跨域请求携带的请求头
            httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");//若要返回cookie、携带seesion等信息则将此项设置我true
        }

        System.out.println("---------跨域处理");
    //    log.debug("CrosXssFilter.......orignal url:{},ParameterMap:{}",httpServletRequest.getRequestURI(), JSONObject.toJSONString(httpServletRequest.getParameterMap()));
    //    log.debug("CrosXssFilter..........doFilter url:{},ParameterMap:{}",xssHttpServletRequestWrapper.getRequestURI(), JSONObject.toJSONString(xssHttpServletRequestWrapper.getParameterMap()));

        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {

    }
}

启动类添加注解@ServletComponentScan扫描过滤器类

/**
 * 启动程序
 * 
 * @author ruoyi
 */
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@ServletComponentScan
public class RuoYiApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(RuoYiApplication.class, args);
    }
}

Controller

package com.ruoyi.web.controller.app;

import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/web")
public class WebController {

    @Autowired
    private ISysDeptService deptService;

    @PostMapping("/login")
    @ResponseBody
    public int login(String username, HttpSession session)
    {
        session.setAttribute("username", username);
        return 1;
    }

    @PostMapping("/list")
    @ResponseBody
    public List<SysDept> list(SysDept dept, HttpSession session)
    {
        String username= (String) session.getAttribute("username");
        System.out.println("username==="+username);
        List<SysDept> deptList = deptService.selectDeptList(dept);
        return deptList;
    }
}

页面1(登录页面):

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery-1.8.3.min.js" ></script>
		<script  type="text/javascript" >
			function toLogin() {
				$.ajax({
					url:"http://localhost/web/login",
					//加上这句话
					xhrFields: {
					    withCredentials: true
					},
					type: "post",
					data: {
						"username": $("#username").val()
					},
					success:function(result){
					    alert("请求成功");
					    console.log(result);
					    if(result==1) {
					    	window.location.href="index.html";
					    }
					},
					error:function(){
					}
				});
			}
		</script>
	</head>
	<body>
		<form action="" method="post">
			<input type="text" id="username" />
			<input type="button" onclick="toLogin();" value="登录" />
		</form>
	</body>
</html>

列表页面(测试获取session):

注意:如果$.get或者$.post,只能跨域,无法获取session值,因为无法添加xhrFields参数

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script type="text/javascript" src="js/jquery-1.8.3.min.js" ></script>
		<script  type="text/javascript" >
			$(function(){
				$.ajax({
					url:"http://localhost/web/list",
					//加上这句话
					xhrFields: {
					    withCredentials: true
					},
					type: "post",
					success:function(result){
					    console.log(result);
					},
					error:function(){
					}
				});
				
				/*$.post("http://localhost/web/list", function(data){
					console.log(data);
				});*/
			});
		</script>
	</head>
	<body>
		
	</body>
</html>

方法2:

使用@CrossOrigin注解方式

Controller

package com.ruoyi.web.controller.app;

import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

//@CrossOrigin(origins = "*", maxAge = 3600)//能跨域,但是session取不到
@CrossOrigin(origins = "*", maxAge = 3600, allowCredentials = "true")//能跨域,也能取session值
/*如果你使用的是高版本SpringBoot2.4.4则需要改动一下,否则后台报错
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:453) ~[spring-web-5.3.6.jar:5.3.6]
当allowCredentials为true时,alloedOrigins不能包含特殊值“*”,因为该值不能在“Access-Control-Allow-Origin”响应头部中设置。要允许凭据访问一组来源,请显式列出它们或考虑改用“AllowedOriginPatterns”。

解决:把 config.addAllowedOrigin("*"); 替换成 config.addAllowedOriginPattern("*");
*/
@Controller
@RequestMapping("/web")
public class WebController {

    @Autowired
    private ISysDeptService deptService;

    @PostMapping("/login")
    @ResponseBody
    public int login(String username, HttpSession session)
    {
        session.setAttribute("username", username);
        return 1;
    }

    @PostMapping("/list")
    @ResponseBody
    public List<SysDept> list(SysDept dept, HttpSession session)
    {
        String username= (String) session.getAttribute("username");
        System.out.println("username==="+username);
        List<SysDept> deptList = deptService.selectDeptList(dept);
        return deptList;
    }
}

页面1:(登录)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery-1.8.3.min.js" ></script>
		<script  type="text/javascript" >
			function toLogin() {
				$.ajax({
                                async:false,
                                type:"post",
                                //加上这句话
                            	xhrFields: {
                            	    withCredentials: true
                            	},
                                url:"http://localhost/web/login",
                                data: {
                                	"username": $("#username").val()
                                },
                                success:function(result){
                                    if(result==1) {
                            	    	window.location.href="index.html";
                            	    }
                                },
                                error: function (errorMsg) {
                                    //请求失败时执行该函数
                                    alert("请求数据失败!");
                                }
                            });
			}
		</script>
	</head>
	<body>
		<form action="" method="post">
			<input type="text" id="username" />
			<input type="button" onclick="toLogin();" value="登录" />
		</form>
	</body>
</html>

列表页面,测试session

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script type="text/javascript" src="js/jquery-1.8.3.min.js" ></script>
		<script  type="text/javascript" >
			$(function(){
				$.ajax({
					url:"http://localhost/web/list",
					//加上这句话
					xhrFields: {
					    withCredentials: true
					},
					type: "post",
					success:function(result){
					    console.log(result);
					},
					error:function(){
					}
				});
				
				/*$.post("http://localhost/web/list", function(data){
					console.log(data);
				});*/
			});
		</script>
	</head>
	<body>
		
	</body>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值