servlet处理跨域请求
前言
我们要做的是让在一个不在当前项目文件夹的前端页面发送Ajax请求,由一个远程servlet处理
代码
-
创建一个web工程
-
导入所需的jar-> servlet-api.jar fastjson.jar
-
编写前端页面
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="button" value="get" id='get'>
<input type="button" value="POST" id='post'>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
let data = {
name: '狗剩',
age: 20
}
$("#get").on('click', function() {
$.ajax({
type: 'get',
contentType:'application/json', //data发送方式
url: 'http://localhost/TestServlet', //发送跨域请求
data: data,
success: (res) => {
console.log("res:", res)
}
})
})
$("#post").on('click', function() {
$.ajax({
type: 'post',
contentType:'application/json',
url: 'http://localhost/TestServlet',
data: JSON.stringify(data),
success: (res) => {
console.log("res:", res)
}
})
})
</script>
</body>
</html>
- 配置一个Filter处理跨域请求
import javax.servlet.*;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Filter extends HttpFilter {
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//设置跨域请求
System.out.println("Filter 过滤器 执行 了");
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
//允许跨域主机地址
response.setHeader("Access-Control-Allow-Origin", "*");
//允许跨域方法
response.setHeader("Access-Control-Allow-Methods", "POST, DELETE,PUT,GET,OPTIONS");
//缓存时间
response.setHeader("Access-Control-Max-Age", "3600");
//允许跨域的请求头
response.setHeader("Access-Control-Allow-Headers", "*");
//是否携带cookie
response.setHeader("Access-Control-Allow-Credentials", "true");
//允许放行
chain.doFilter(request, response);
}
}
- 编写servlet处理请求
import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
public class TestServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("请求已到达-> post");
request.setCharacterEncoding("utf-8");
ServletInputStream inputStream = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String str = null;
while((str = br.readLine()) != null) {
sb.append(str);
}
System.out.println(sb.toString());
//转为map集合
Map parseObject = JSON.parseObject(sb.toString(), Map.class);
System.out.println("parseObject:" + parseObject);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("请求已到达-> get");
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
System.out.println("name:" + name + ", age:" + age);
}
}
- 配置web.xml
<filter>
<filter-name>Filter</filter-name>
<filter-class>Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter</filter-name>
<!-- 配置需要进行跨域的接口 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<!--servlet名 -->
<servlet-name>Test</servlet-name>
<!-- servlet路径,包名.类名 -->
<servlet-class>TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<!--servlet映射,必须与servlet-name同名 -->
<servlet-name>Test</servlet-name>
<!--浏览器中输入的访问该servlet的url-->
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
- 部署项目,启动服务器,测试跨域请求
结语
//需要注意的是前端Ajax请求的url
url: 'http://localhost/TestServlet'
//servlet的web.xml配置
<url-pattern>/TestServlet</url-pattern>
//localhost后面的地址和xml配置的地址一致即可