依赖:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
Java 后端代码:
package com.mr;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author kate
*/
@WebServlet(urlPatterns = "/deptController")
public class TestController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
/*设置响应头允许ajax跨域访问**/
resp.setHeader("Access-Control-Allow-Origin", "*");
/*星号表示所有的异域请求都可以接受,*/
resp.setHeader("Access-Control-Allow-Methods", "GET,POST");
//设置输出编码
resp.setContentType("application/json;charset=utf-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
writer.println("哈哈哈不错哟");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
req.setCharacterEncoding("UTF-8");
/*设置响应头允许ajax跨域访问**/
resp.setHeader("Access-Control-Allow-Origin", "*");
/*星号表示所有的异域请求都可以接受,*/
resp.setHeader("Access-Control-Allow-Methods", "GET,POST");
//设置输出编码
resp.setContentType("application/json;charset=utf-8");
resp.setCharacterEncoding("UTF-8");
配置信息可以做一个全局配置,防止代码冗余