通讯录查询项目--通过id以及通过邮箱查询

本文介绍了通过HTTP Servlet实现的两种联系人查询方法:一种是通过ID查询指定联系人,并将其转发到更新页面;另一种是通过邮箱查询联系人是否存在,返回JSON格式的查询结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过id查询:

public class QueryByIdServlet extends HttpServlet {
    ContactServiceImpl contactService = new ContactServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");


        //通过id查询指定对象
        String id = request.getParameter("id");
        //通过传过来的id参数获得要查找的对象
        Contact contact = contactService.query(id);
        //将contact放入请求域中
        request.setAttribute("contact",contact);
        //因为要发送查找后的资源,用重定向技术发送
        request.getRequestDispatcher("update.jsp").forward(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

通过邮箱查询

public class QueryEmailServlet extends HttpServlet {
    ContactServiceImpl contactService = new ContactServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String email = request.getParameter("email");
        boolean exist = contactService.queryByEmail(email);
        PrintWriter out = response.getWriter();
        Map<String,Object> responseObj = new HashMap<>();

        if(exist){
            //存在
            responseObj.put("code",1);
            responseObj.put("error","此邮箱已经存在!");
        }else {
            //不存在
            responseObj.put("code",0);
            responseObj.put("error","此邮箱不存在,可以注册");
        }

        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(responseObj);
        out.write(s);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值