Ajax
package com.xiaoge.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
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.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2020/4/4 11:10
* @author Administrator
*/
@WebServlet("/findUsernameServlet")
public class FindUsernameServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
<---------------------------------------------------------------------->
//1.获取用户名
String username = request.getParameter("username");
<---------------------------------------------------------------------->
//2.调用service层判断用户名是否存在
//期望服务器响应回的数据格式:{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"}
// {"userExsit":false,"msg":"用户名可用"}
//
//("text/html;charset=utf-8");
response.setContentType("application/json;charset=utf-8");
Map<String,Object> map = new HashMap<>();
<---------------------------------------------------------------------->
//2.调用service层判断用户是否存在
if ("tom".equals(username)){
//存在
map.put("userExsit",true);
map.put("msg","此用户太受欢迎,请换一个");
}else {
//不存在
map.put("userExsit",false);
map.put("msg","此用户可以使用");
}
//将map转化为json,并传递给客户端
//将map转化为json
<---------------------------------------------------------------------->
ObjectMapper mapper = new ObjectMapper();
//((),map);
String string = mapper.writeValueAsString(map);
System.out.println(string);
response.getWriter().write(string);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}