You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
chat-room/util/ControllerUtils.java

61 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.hyc.wechat.util;
import com.alibaba.fastjson.JSON;
import com.hyc.wechat.controller.constant.RequestMethod;
import com.hyc.wechat.model.dto.ServiceResult;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 控制层工具类,提供了一些静态方法用于控制层操作
*
* @author <a href="mailto:kobe524348@gmail.com">黄钰朝</a>
* @program wechat
* @description 这个类包含了一些静态方法用于在控制层处理请求和响应例如将请求方法转换为枚举类型以及将服务结果转换为JSON格式并返回给客户端
* @date 2019-05-02 17:35
*/
public class ControllerUtils {
/**
* 将请求中的method参数值转换为对应的RequestMethod枚举项
*
* @param name 请求中的method参数值通常是GET、POST等HTTP方法
* @return 返回对应的RequestMethod枚举项如果未找到匹配项则返回RequestMethod.INVALID_REQUEST
* @name valueOf
* @notice 此方法不处理null值如果传入的name为null将会抛出NullPointerException
* @author <a href="mailto:kobe524348@gmail.com">黄钰朝</a>
* @date 2019/4/20
* @see RequestMethod
*/
public static RequestMethod valueOf(String name) {
try {
name = name.toUpperCase().replaceAll("\\.", "_");
return RequestMethod.valueOf(name);
} catch (IllegalArgumentException | NullPointerException e) {
// 如果捕获到异常,说明请求参数没有匹配到任何服务,为无效请求
e.printStackTrace();
return RequestMethod.INVALID_REQUEST;
}
}
/**
* 将服务结果转换为JSON格式并将其写入HTTP响应中返回给客户端
*
* @param resp HTTP响应对象用于向客户端发送数据
* @param result 服务结果对象,包含状态码、消息和数据
* @throws IOException 如果在写入响应时发生I/O错误
* @name returnJsonObject
* @notice 此方法会关闭响应的输出流,调用后不应再对响应对象进行写操作
* @author <a href="mailto:kobe524348@gmail.com">黄钰朝</a>
* @date 2019/5/6
*/
public static void returnJsonObject(HttpServletResponse resp, ServiceResult result) throws IOException {
JSON json = (JSON) JSON.toJSON(result);
resp.getWriter().write(json.toJSONString());
Logger logger = Logger.getLogger(ControllerUtils.class);
logger.info(json.toJSONString());
}
}