Fastjson
tomcat
1.创建实体类:
public class Employee {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Employee{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
2.创建状态码类
public class ApiRest<T> {
private Integer status;
private T data;
private String msg;
public Integer getStatus() {
return status;
}
public ApiRest(Integer status, T data, String msg) {
this.status = status;
this.data = data;
this.msg = msg;
}
public void setStatus(Integer status) {
this.status = status;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "ApiRest{" +
"status=" + status +
", data=" + data +
", msg='" + msg + '\'' +
'}';
}
}
3.创建Servlet:
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
ApiRest apiRest = null;
if (("admin".equals(username) )&& "12345".equals(password)){
apiRest = new ApiRest(200,"登录成功","higugyhdu");
}else {
apiRest = new ApiRest(404,"登录失败","hdugdye");
}
String json = JSON.toJSONString(apiRest);
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(json);
}
}
运行结果:
注意点:
1.乱码解决办法:
response.setContentType("text/html;charset=utf-8");