网络编程 
首页 > 网络编程 > 浏览文章

Ajax实现登录案例

(编辑:jimmy 日期: 2024/11/15 浏览:3 次 )

Ajax登录案例,供大家参考,具体内容如下

Ajax实现登录案例

Msg

package com.lbl.msg;

public class Msg {
  String msg;
  int code;

  public Msg() {
  }

  public Msg(String msg, int code) {
    this.msg = msg;
    this.code = code;
  }

  public String getMsg() {
    return msg;
  }

  public void setMsg(String msg) {
    this.msg = msg;
  }

  public int getCode() {
    return code;
  }

  public void setCode(int code) {
    this.code = code;
  }
}

RegisterServlet

package com.lbl.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lbl.msg.Msg;

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("/register")
public class RegisterServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1:获取请求发送的数据
    String username = request.getParameter("username");
    response.setContentType("text/html;charset=UTF-8");
    //2:判断用户名是否注册
    if("abc123".equals(username)){
      Msg msg = new Msg("用户名已经注册",0);
      //用户名已经注册 {"flag":false,"info":"用户名已经注册"};
//      String jsonStr = "{\"flag\":false,\"info\":\"用户名已经注册\"}";
      //响应回浏览器
      response.getWriter().write(new ObjectMapper().writeValueAsString(msg));
    }else{
      Msg msg = new Msg("可以注册",1);
      //用户名没有注册
//      String jsonStr = "{\"flag\":true,\"info\":\"可以注册\"}";
      //响应回浏览器
      response.getWriter().write(new ObjectMapper().writeValueAsString(msg));
    }

  }
}

json_register.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="/UploadFiles/2021-04-02/jquery-3.3.1.js">

运行效果:

Ajax实现登录案例

Ajax实现登录案例

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:ajax异步实现文件分片上传实例代码
下一篇:Ajax工作原理及优缺点实例解析