@RequestMapping(value = "/login.do",method = RequestMethod.POST) public Message login(HttpServletRequest request,HttpServletResponse response) throws BusinessException { // CORSUtil.addHeaders(response); // 获取请求参数 JSONObject json = WebUtils.getRequest(request); String userName = (String) json.get("userName"); String password = (String) json.get("password"); // String userName = request.getParameter("userName"); // String password = request.getParameter("password"); UsersLoginInfoVO usersLoginInfo = iLoginService.login(userName, password); return response(SUCCESS.getCode(),usersLoginInfo); }
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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HeadersCORSFilter 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 httpResp = (HttpServletResponse) response; HttpServletRequest httpServletRequest = (HttpServletRequest) request; httpResp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS"); httpResp.setHeader("Access-Control-Allow-Origin", "*"); httpResp.setHeader("Access-Control-Allow-Credentials","true"); httpResp.setHeader("Access-Control-Max-Age", "3600"); if (httpServletRequest.getMethod().equalsIgnoreCase("OPTIONS")) { httpResp.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin," + "Access-Control-Request-Method,Access-Control-Request-Headers,userID,Authentication"); } chain.doFilter(request, response); } @Override public void destroy() { // TODO Auto-generated method stub } }
<!--<!–cors过滤器–>--> <filter> <filter-name>cors</filter-name> <filter-class>com.backstage.filter.HeadersCORSFilter</filter-class> <async-supported>true</async-supported> </filter> <filter-mapping> <filter-name>cors</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>新闻动态</title> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"> </head> <body class="body-blackBg"> </body> <script src="jquery.min.js"></script> <script> $(document).ready(function () { $.ajax({ type: "POST", dataType: "json", url: "http://localhost:8081/api/pas/web/user/login.do", contentType: "application/json; charset=utf-8", data:JSON.stringify({userName:"admin", password:"admin123"}), success: function (data) { console.log(data); }, error: function (data) { } }); }) </script> </html>