import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class CORSFilter implements Filter { public void CORSFilter(){ } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,ServletException { HttpServletResponse httpResp = (HttpServletResponse) resp; HttpServletRequest httpReq = (HttpServletRequest) req; httpResp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS"); httpResp.setHeader("Access-Control-Allow-Origin", "*"); httpResp.setHeader("Access-Control-Allow-Credentials","true"); if (httpReq.getMethod().equalsIgnoreCase("OPTIONS")) { httpResp.setHeader("Access-Control-Allow-Headers", httpReq.getHeader("Access-Control-Request-Headers")); } chain.doFilter(req, resp); } @Override public void init(FilterConfig arg0) throws ServletException { } @Override public void destroy() { } }
<filter> <filter-name>corsFilter</filter-name> <filter-class>com.sung.risk.filter.CORSFilter</filter-class> </filter> <filter-mapping> <filter-name>corsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
controller:
@ResponseBody @RequestMapping(value = "/getNewsOfficial") public JSONObject getNewsOfficial(HttpServletRequest request){ JSONObject jsonObject1 = new JSONObject(); String currentPage = request.getParameter("currentPage"); String pageSize = request.getParameter("pageSize"); jsonObject1.put("currentPage",currentPage); jsonObject1.put("pageSize",pageSize); return jsonObject1; }
前端页面:
<!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:8080/newsofficial/getNewsOfficial.do", data:{currentPage:0, pageSize:5}, success: function (data) { console.log(data); }, error: function (data) { } }); $.ajax({ async: false, type: 'POST', data:{currentPage:0, pageSize:5}, dataType: "json", url: "http://localhost:8080/newsofficial/getNewsOfficial.do",//请求的action路径 error: function (msg) {//请求失败处理函数 }, success: function (data) { //请求成功后处理函数。 } }) }) </script> </html>
这个方案,前端发送的是非json格式。
json格式其实差不多,留待下篇