vue 访问后端接口(后端接口框架:ssm)报错 403 No ‘Access-Control-Allow-Origin‘ header解决方案

1.错误如图(跨域问题):

2.解决方案:

(1).先添加拦截器:

具体代码:

package com.ldkj.smms.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ldkj.smms.entity.system.TMenu;
import com.ldkj.smms.entity.system.TPubStaff;
import com.ldkj.smms.util.Const;
import com.ldkj.smms.util.RequestUtil;
//import com.ldkj.smms.util.shop.MenuUtil;

/**
 * 登录拦截器
 *
 * @modificationHistory. 
    *
  • syf 2015年4月18日上午12:21:21 TODO
  • *
*/ public class LoginHandlerInterceptor extends HandlerInterceptorAdapter { //@Resource(name = "menuUtil") //private MenuUtil menuUtil; @SuppressWarnings("unchecked") @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // TODO Auto-generated method stub String path = request.getServletPath(); if (!path.toLowerCase().matches(Const.IGNORE_REQUEST_TYPE)) { System.out.println("path--------->" + path); } if (!path.matches(Const.INTERCEPTOR_PATH) || path.matches(Const.NO_INTERCEPTOR_PATH)) { return true; } else { HttpSession httpSession = request.getSession(); String loginType = (String) httpSession.getAttribute(Const.SESSION_LOGINTYPE); //shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); if (loginType != null && loginType.equals("system")) { TPubStaff staff = (TPubStaff) session.getAttribute(Const.SESSION_STAFF); if (staff != null) { //判断是否拥有当前点击菜单的权限(内部过滤,防止通过url进入跳过菜单权限) /** * 根据点击的菜单的xxx.do去菜单中的URL去匹配,当匹配到了此菜单,判断是否有此菜单的权限,没有的话跳转到登录页面 * 根据按钮权限,授权按钮(当前点的菜单和角色中各按钮的权限匹对) */ List menuList = (List) session.getAttribute(Const.SESSION_allmenuList); //获取菜单列表 Boolean hasRights = this.checkRights(menuList, path); if (!hasRights) { this.noPermRedirect(request, response); } return hasRights; } else { //登陆过滤 this.notLogin(request, response); return false; } } else { // shopStaff = (TShopStaff) session.getAttribute(Const.SESSION_SHOP_STAFF); // if (shopStaff != null) { // Integer adminType = (Integer) session.getAttribute(Const.SESSION_ADMINTYPE); // // //同一session只能登录一个相同账号,除非系统管理员 // if (!SessionListener.isOnline(httpSession) && (adminType == null || adminType != 1)) { // this.kickOut(request, response); // } // // // //判断是否拥有当前点击菜单的权限(内部过滤,防止通过url进入跳过菜单权限) // /** // * 根据点击的菜单的xxx.do去菜单中的URL去匹配,当匹配到了此菜单,判断是否有此菜单的权限,没有的话跳转到登录页面 // * 根据按钮权限,授权按钮(当前点的菜单和角色中各按钮的权限匹对) // */ // List menuList = menuUtil.getRoleMenus(shopStaff.getRole(),PermissionScope.PC.getId()); //获取菜单列表 // // Boolean hasRights = this.checkRights(menuList, path); // // if (hasRights) { // System.out.println("请求通过"); // } else { // System.out.println("请求不通过"); // } // // if (!hasRights) { // this.noPermRedirect(request, response); // } // return hasRights; // } else { //登陆过滤 this.notLogin(request, response); return false; // } } } } /** * 递归校验各菜单 * * @param menuList * @param path * @return * @throws Exception * @author syf * @creationDate. 2015年5月29日 下午10:02:38 */ private boolean checkRights(List menuList, String path) throws Exception { path = path.replaceFirst("^/+", ""); path = path.split(".htm")[0].split(".json")[0]; if (menuList != null && menuList.size() > 0) { for (TMenu menu : menuList) { if (menu.getSubMenu() != null && menu.getSubMenu().size() > 0) { if (!checkRights(menu.getSubMenu(), path)) return false; } String menuPath = menu.getMenuUrl().split(".htm")[0].split(".json")[0]; menuPath = menuPath.replaceFirst("^/+", ""); if (menuPath.equals(path)) { if (!menu.isHasMenu()) { //判断有无此菜单权限 return false; } else { //按钮判断 //setBtnRights(menu.getMenuId()); return true; } } } } return true; } /** * 未登录 * * @param request * @param response * @throws Exception * @author syf * @creationDate. 2015年5月29日 下午9:57:35 */ private void notLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { if (RequestUtil.isAjaxRequest(request)) { RequestUtil.write(response, "{'_http_status_code_':'405'}", Const.SYSTEM_DEFAULT_ENCODING); } else { response.sendRedirect(request.getContextPath() + Const.NOTLOGIN); } } /** * 无权限 * * @param request * @param response * @throws Exception * @author syf * @creationDate. 2015年5月29日 下午9:57:42 */ private void noPermRedirect(HttpServletRequest request, HttpServletResponse response) throws Exception { if (RequestUtil.isAjaxRequest(request)) { RequestUtil.write(response, "{'_http_status_code_':'406'}", Const.SYSTEM_DEFAULT_ENCODING); } else { response.sendRedirect(request.getContextPath() + Const.NOPERMISSION); } } @SuppressWarnings("unused") private void kickOut(HttpServletRequest request, HttpServletResponse response) throws Exception { if (RequestUtil.isAjaxRequest(request)) { RequestUtil.write(response, "{'_http_status_code_':'407'}", Const.SYSTEM_DEFAULT_ENCODING); } else { response.sendRedirect(request.getContextPath() + Const.KICKOUT); } } }

springmvc配置文件加:

  
      
        
            
            
           
    

(2)如果还是报错的话,应添加跨域过滤,增加:

package com.ldkj.smms.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import com.ldkj.smms.controller.base.BaseController;

public class CorsFilter extends BaseController implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.addHeader("Access-Control-Allow-Origin", "*");
		//httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
		httpResponse.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,access_token,refresh_token");
		httpResponse.setHeader("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST");
		httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
		httpResponse.setHeader("Access-Control-Max-Age", "0");
		httpResponse.setContentType("text/html;charset=UTF-8");
		httpResponse.setHeader("XDomainRequestAllowed","1");
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}

项目下的web.xml下增加:


     
          CorsFilter
          com.ldkj.smms.filter.CorsFilter
     
     
          CorsFilter
          /*
     

3.通过上述两种方法即可解决vue跨域问题

你可能感兴趣的:(vue,Java,spring,vue.js,servlet,java)