javaweb 之 用Ajax实现用户注册功能

一.客户端

三种方式提交

get   post    json

<%--
  Created by IntelliJ IDEA.
  User: ASUS
  Date: 2018/8/5
  Time: 23:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    regaxios
    
    


用户名: 密码:

 

二.服务器端

<%@ page import="java.io.InputStream" %>
<%@ page import="org.apache.commons.io.IOUtils" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="com.alibaba.fastjson.serializer.SerializerFeature" %><%--
  Created by IntelliJ IDEA.
  User: ASUS
  Date: 2018/8/6
  Time: 0:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String username=request.getParameter("username");
String pwd=request.getParameter("pwd");

if(username==null){
    //JSON以流的方式获取数据
    InputStream in=request.getInputStream();
    //转换为字符串
    String jsonstr= IOUtils.toString(in,"utf-8");
    //将字符串转换为json对象
    JSONObject obj= JSON.parseObject(jsonstr);
    //获取数据
    username=obj.getString("username");
    pwd=obj.getString("pwd");
}

//获取users对象
Map users=(Map)application.getAttribute("users");
//创建jsonObject对象
JSONObject jsonObject=new JSONObject();

//如果users为空
if(users==null){
    //创建一个集合用来存储用户信息
    users=new HashMap();
    //将用户信息存入
    users.put(username,pwd);
    application.setAttribute("users",users);
    //json存入数据,作为反馈信息
    jsonObject.put("msg","用户不存在");
}else {
    if(users.containsKey(username)){
        jsonObject.put("msg","用户名已存在");
    }else{
        jsonObject.put("msg","用户名不存在");
        users.put(username,pwd);
    }
}

    jsonObject.put("users",users);
    out.println(JSON.toJSONString(jsonObject, SerializerFeature.WriteSlashAsSpecial));
%>

 

你可能感兴趣的:(javaweb 之 用Ajax实现用户注册功能)