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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM