Servlet-Vue-JSON交互

Servlet-Vue-JSON交互

统一结果返回
  • 定义

    package org.example.result;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Result<T> {
        private Integer code;
        private String message;
        private T data;
    
        public static Result success(String message, Object data) {
            Result result = new Result<>();
            result.setCode(200);
            result.setMessage(message);
            result.setData(data);
            return result;
        }
    
        public static Result success(Integer code, String message, Object data) {
            Result result = new Result<>();
            result.setCode(code);
            result.setMessage(message);
            result.setData(data);
            return result;
        }
    
        public static Result error(String message) {
            Result result = new Result<>();
            result.setCode(500);
            result.setMessage(message);
            result.setData(null);
            return result;
        }
    }
    
    
创建控制器
  • controller

    package org.example.controller.user;
    
    import com.google.gson.Gson;
    
    @WebServlet("/user/login")
    public class UserLonginController extends HttpServlet {
        private UserService userService = new UserServiceImpl();
    
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            Gson gson = new Gson();
            User user = userService.getUserByUserName(username, password);
            if (user != null) {
                // 密码脱敏处理
                user.setPassword("********");
                Result result = Result.success("登录成功", user);
                resp.getWriter().println(gson.toJson(result));
            } else {
                Result result = Result.error("登录失败");
                // 输出 json 格式的字符串
                resp.getWriter().println(gson.toJson(result));
            }
        }
    }
    
    
Axios
  • 发送请求

    axios({
    	baseURL: "http://localhost:8080",
        url: "/user/login",
        method: "get",
        params:{
            // es6 语法
            username,
            password
        }
    })
    
  • 测试
    Servlet-Vue-JSON交互_第1张图片

POST
  • post请求

    • controller

      package org.example.controller.user;
      
      import com.google.gson.Gson;
      import com.google.gson.JsonObject;
      
      @WebServlet("/user/update")
      public class UserUpdateController extends HttpServlet {
          private UserService userService = new UserServiceImpl();
      
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              BufferedReader reader = req.getReader();
              StringBuilder sb = new StringBuilder();
              String line;
              while ((line = reader.readLine()) != null) {
                  sb.append(line);
              }
              // 使用 Gson 解析 JSON 数据
              Gson gson = new Gson();
              JsonObject json = gson.fromJson(sb.toString(), JsonObject.class);
              // 获取 JSON 中的参数
              Integer userId = Integer.valueOf(json.get("id").getAsString());
              String userName = json.get("username").getAsString();
              String phone = json.get("phone").getAsString();
              String address = json.get("address").getAsString();
              String nickname = json.get("nickname").getAsString();
              String email = json.get("username").getAsString();
              // 传递到对象中
              User user = new User();
              user.setId(userId);
              user.setUsername(userName);
              user.setPhone(phone);
              user.setAddress(address);
              user.setNickname(nickname);
              user.setEmail(email);
              boolean isUpdate = userService.updateById(user);
              if (isUpdate) {
                  // 更新成功
                  Result result = Result.success("数据更新成功!", null);
                  resp.getWriter().println(gson.toJson(result));
              } else {
                  Result result = Result.error("数据更新失败!");
                  resp.getWriter().println(gson.toJson(result));
              }
          }
      }
      
      
    • axios

      axios({
      	baseURL: "http://localhost:8080",
          url: "/user/update",
          method: "post",
          data:{
              // es6 语法
              userId,
              userName,
              phone,
              address,
              email
          }
      })
      

你可能感兴趣的:(servlet,vue.js,json)