springboot封装JsonUtil,CookieUtil工具类代码实例

下面开始讲解Spring Boot封装JsonUtil,CookieUtil工具类代码实例的攻略,主要包含以下几步:

下面开始讲解"Spring Boot封装JsonUtil,CookieUtil工具类代码实例"的攻略,主要包含以下几步:

1. 创建工具类文件

在src/main/java目录下创建一个名为utils的包,然后在该包下创建两个工具类文件:JsonUtil和CookieUtil。

1.1 JsonUtil

JsonUtil用于将Java对象与Json数据相互转换,示例代码如下:

package com.example.demo.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JsonUtil {
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String toJsonString(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.error("Object to JSON String error:", e);
            return null;
        }
    }

    public static <T> T toObject(String jsonString, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonString, clazz);
        } catch (IOException e) {
            logger.error("JSON String to Object error:", e);
            return null;
        }
    }
}

1.2 CookieUtil

CookieUtil用于操作Cookie,示例代码如下:

package com.example.demo.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }

    public static void removeCookie(HttpServletResponse response, HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
    }
}

2. 使用工具类

在工程中需要用到工具类的地方,只需要import相应的类即可使用,例如:

2.1 使用JsonUtil转换对象与Json字符串

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.utils.JsonUtil;

public class UserService {
    public void test() {
        User user = new User();
        user.setId(1);
        user.setUsername("Tom");
        user.setPassword("123456");
        String jsonString = JsonUtil.toJsonString(user); // 将对象转换为Json字符串
        System.out.println(jsonString);
        User user1 = JsonUtil.toObject(jsonString, User.class); // 将Json字符串转换为对象
        System.out.println(user1.getUsername());
    }
}

2.2 使用CookieUtil操作Cookie

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.utils.CookieUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserController {
    public void login(HttpServletRequest request, HttpServletResponse response, User user) {
        // 登录成功后将用户信息存入Cookie,时长为30分钟
        CookieUtil.addCookie(response, "user", JsonUtil.toJsonString(user), 30 * 60);
    }

    public User getUser(HttpServletRequest request) {
        // 从Cookie中读取用户信息
        Cookie cookie = CookieUtil.getCookie(request, "user");
        if (cookie != null) {
            String userJson = cookie.getValue();
            return JsonUtil.toObject(userJson, User.class);
        }
        return null;
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 从Cookie中删除用户信息
        CookieUtil.removeCookie(response, request, "user");
    }
}

以上就是使用Spring Boot封装JsonUtil、CookieUtil工具类的完整攻略。

本文标题为:springboot封装JsonUtil,CookieUtil工具类代码实例

基础教程推荐