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. Get user name
String username = request.getParameter("username");
<---------------------------------------------------------------------->
//2. Call the service layer to determine if the username exists.
// Expect the server to respond with data in the following format: {"userExsit":true, "msg": "This username is too popular, please change it"}
// {"userExsit":false, "msg": "Username available"}
//
//("text/html;charset=utf-8");
response.setContentType("application/json;charset=utf-8");
Map<String,Object> map = new HashMap<>();
<---------------------------------------------------------------------->
//2. Call the service layer to determine if the user exists.
if ("tom".equals(username)){
// Existence
map.put("userExsit",true);
map.put("msg","This user is too popular. Please change.");
}else {
// Does not exist
map.put("userExsit",false);
map.put("msg","This user can use");
}
//convert the map to json and pass it to the client.
//convert map to 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);
}
}