念念不忘
必有回响

JavaWeb解决跨域的两种方式

如果使用了SpringMVC,那么只需要使用Filter就可以实现,此时需要使用@ResponseBody注解。

package com.navercorp.pinpoint.web.filter;

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

/**
 * Created with IntelliJ IDEA.
 * User: liyang
 * Date: 2017/11/14
 * Time: 上午11:33
 * DESCIPTION: 跨域过滤器
 */
public class HeadersCORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

此时在spring-mvc.xml中配置Filter

<filter>
    <filter-name>cors</filter-name>
    <filter-class>com.xxx.xxx.web.filter.HeadersCORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

如果未使用SpringMVC的话可以使用继承父Controller的方式,给每个Controller的header加上跨域的作用域。

public abstract class BaseController {
  /**
     * description:send the ajax response back to the client side
     * @param responseObj
     * @param response
     */
    protected void writeAjaxJSONResponse(Object responseObj, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0

        /**
         * for ajax-cross-domain request TODO get the ip address from
         * configration(ajax-cross-domain.properties)
         */
        response.setHeader("Access-Control-Allow-Origin", "*");

        response.setDateHeader("Expires", 0); // Proxies.

        PrintWriter writer = getWriter(response);

        writeAjaxJSONResponse(responseObj, writer);
    }
  /**
     *
     * @param response
     * @return
     */
    protected PrintWriter getWriter(HttpServletResponse response) {
        if(null == response){
            return null;
        }

        PrintWriter writer = null;

        try {
            writer = response.getWriter();
        } catch (IOException e) {
            logger.error("unknow exception", e);
        }


        return writer;
    }

    /**
     * description:send the ajax response back to the client side.
     *
     * @param responseObj
     * @param writer
     * @param writer
     */
    protected void writeAjaxJSONResponse(Object responseObj, PrintWriter writer) {
        if (writer == null || responseObj == null) {
            return;
        }
        try {         writer.write(JSON.toJSONString(responseObj,SerializerFeature.DisableCircularReferenceDetect));
        } finally {
            writer.flush();
            writer.close();
        }
    }
}

实现一个子Controller:

@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public void addAccount(HttpSession session,HttpServletRequest request,HttpServletResponse response){
        ViewerResult result = new ViewerResult();
         //实现自己业务逻辑代码
        writeAjaxJSONResponse(result, response);
    }
}

 

赞(4) 打赏
未经允许不得转载:码农志 » JavaWeb解决跨域的两种方式
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏