zoukankan      html  css  js  c++  java
  • java跨域请求的方式

    1、基于servlet和过滤器的方式

    /**
     * 设置跨域请求相关参数的过滤器
     * @Author LQY
     * @Date 2018/12/3
     */
    @WebFilter("/*")
    public class MyFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void destroy() {
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest)request;
            HttpServletResponse resp = (HttpServletResponse)response;
            req.setCharacterEncoding("utf-8");
            //设置哪些域可以跨域访问,*代表所有域
            resp.setHeader("Access-Control-Allow-Origin","*");
            //设置支持那种访问方法
            resp.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE");
            chain.doFilter(request,response);
        }
    }
    /**
     * @Author LQY
     * @Date 2018/12/3
     */
    @WebServlet("/UserLogin")
    public class LoginServlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String userName = req.getParameter("userName");
            String password = req.getParameter("password");
            System.out.println(userName+":"+password);
            resp.setContentType("text/html;charset=utf-8");
            if("user".equals(userName) && "123".equals(password)){
                resp.getWriter().print("success");
            }else{
                resp.getWriter().print("fail");
            }
        }
    }

    前端页面发起ajax请求

    <script>
                $('#loginBtn').on('click',function(){
                    var formData = $("#f1").serialize();
                    $.ajax("http://localhost:8080/UserLogin",{
                        type:"post",
                        data:formData,
                        success:function(data){
                            alert(data);
                        }
                    })
                })
    </script>

    2、springmvc通过@CrossOrigin注解设置跨域请求

    设置在方法上:

    /**
     * @Author LQY
     * @Date 2018/12/3
     */
    @RestController
    public class LoginController {
        /**
         * @CrossOrigin注解用来配置跨域请求,第一个参数origins表示那些域名可以跨域访问这个方法,
         * 第二个参数表示表示支持哪些访问的方法。
         * @return
         */
        @RequestMapping("/UserLogin")
        @CrossOrigin(origins = "*",methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.PUT})
        public String userLogin(String userName, String password){
            if("user1".equals(userName) && "6666".equals(password)){
                return "success";
            }else{
                return "fail";
            }
        }
    }

    设置在controller上:

    package edu.nf.demo2.controller;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @CrossOrigin标注在类上表示当前类的所有方法都支持跨域访问,
     * 标注在方法上时表示当前的请求处理方法支持跨域,但会合并属性配置。
     * 注意,这种方式的配置只对当前类有效,对其他的Controller是不起作用的,
     * 如果需要所有的Controller都支持跨域访问,那么可以配置全局的跨域访问
     * (通过xml或者是java配置)
     * @Author LQY
     * @Date 2018/12/3
     */
    @RestController
    @CrossOrigin(origins = "*",methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.PUT})
    public class LoginController {
        /**
         * @CrossOrigin注解用来配置跨域请求,第一个参数origins表示那些域名可以跨域访问这个方法,
         * 第二个参数表示表示支持哪些访问的方法。
         * @return
         */
        @RequestMapping("/UserLogin")
        public String userLogin(String userName, String password){
            if("user1".equals(userName) && "6666".equals(password)){
                return "success";
            }else{
                return "fail";
            }
        }
    }

    通过xml配置文件配置全局的跨域访问

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <context:component-scan base-package="edu.nf.demo2.controller"/>
    
        <mvc:annotation-driven/>
    
        <mvc:default-servlet-handler/>
        <!-- 全局的跨域访问配置 -->
       <mvc:cors>
            <!--&lt;!&ndash; /** 表示所有请求都将支持跨域方法 &ndash;&gt;-->
            <mvc:mapping path="/**" allowed-origins="*" allowed-methods="GET,POST,PUT,DELETE"/>
       </mvc:cors>
    </beans>
    学会用不同的角度看待每个问题!
  • 相关阅读:
    Codeforces Ilya and Matrix
    poj 1308 Is It A Tree?
    Codeforces Sereja and Array
    poj 1041 John's trip
    Codeforces Continued Fractions
    WM_COPYDATA实现进程间数据通信
    虚拟机中安装ubuntu后,终端模式和图形模式切换
    IIS上配置运行cgi,php,aspx运行环境
    linux c main函数参数
    Linux网络编程入门 (转载)
  • 原文地址:https://www.cnblogs.com/nisiweiLIQIYONG/p/10062485.html
Copyright © 2011-2022 走看看