项目搭建
pom文件引入依赖与打包配置。
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.16.2</version>
</dependency>
</dependencies>
<packaging>war</packaging>
<build>
<finalName>hello</finalName>
</build>
目录结构创建。
web.xml写入配置。
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app></web-app>
idea配置tomcat。
接口使用
import com.fasterxml.jackson.databind.json.JsonMapper;
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;
@WebServlet("/test")
public class HelloServlet extends HttpServlet {
long count = 0;
@Override
public void init() throws ServletException {
new Thread(() -> {
while (true) {
count++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("username = " + username + ", password = " + password);
resp.setContentType("text/html; charset=utf8");
resp.setStatus(200);
resp.setHeader("refresh", "1");
resp.getWriter().write("success " + count);
}
static class Customer {
public String username;
public String password;
}
static class ResponseMessage {
public Integer status;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
JsonMapper jsonMapper = new JsonMapper();
// 入参映射转换
// Customer customer = jsonMapper.readValue(req.getInputStream(), Customer.class);
// 读取入参报文
StringBuilder request = new StringBuilder();
// 读取方式一
// String line;
// while ((line = req.getReader().readLine()) != null) {
// request.append(line);
// }
// 读取方式二
byte[] requestBuffer = new byte[1024];
int length;
while ((length = req.getInputStream().read(requestBuffer, 0, requestBuffer.length)) > 0) {
request.append(new String(requestBuffer, 0, length));
}
// 组织出参报文
resp.setContentType("application/json; charset=utf8");
resp.setStatus(200);
ResponseMessage responseMessage = new ResponseMessage();
responseMessage.status = 200;
String response = jsonMapper.writeValueAsString(responseMessage);
resp.getWriter().write(response);
System.out.println("request: " + request + "\n" + "response: " + response);
}
}