警惕HttpServletResponse.getWriter().println(result)换行的坑

     头大连续调试了两天,一直报验签失败,仔细看商户返回的原串和发送的原串是一样的啊,本机调试(服务器tomcat)又不会报验签失败的,测试环境(was)会报,后来仔细查看报文原来返回的报文多了个\n(调试的时候才能看到,日志里面看不到\n)。导致商户拿到的原始报文和我们签名的报文不一致,那哪里导致会多一行呢,仔细看代码,原来是HttpServletResponse.getWriter().println(result),返回同步数据导致的坑,println和print的区别就是多了一行。看源码:

    public void println(String x) {
synchronized (lock) {
    print(x);
    println();
}

    }

  public void println() {
newLine();

    }

   private void newLine() {
try {
    synchronized (lock) {
ensureOpen();
out.write(lineSeparator);
if (autoFlush)
    out.flush();
    }
}
catch (InterruptedIOException x) {
    Thread.currentThread().interrupt();
}
catch (IOException x) {
    trouble = true;
}
    }

所以大家得谨慎,今后尽量使用HttpServletResponse.getWriter().print(result)返回给接口调用者,特别是调用者需要拿到你原串进行验签的情况。


package com.lanou.servlet.role; import java.io.IOException; 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 com.lanou.bean.Admin; import com.lanou.bean.Result; import com.lanou.bean.Role; import com.lanou.service.AdminService; import com.lanou.service.RoleMenuService; import com.lanou.service.impl.AdminServiceImpl; import com.lanou.service.impl.RoleMenuServiceImpl; import com.lanou.util.FastJSONUtil; @WebServlet("/admin/delRole") public class DeleteRole extends HttpServlet{ private static final long serialVersionUID = 1L; RoleMenuService roleMenuService = new RoleMenuServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Role role = (Role) req.getSession().getAttribute("role"); long roleId = Long.parseLong(req.getParameter("roleId")); boolean isDelete = false; // 只有超级管理员 有权限删除 if (role.getRoleId() == 1) { isDelete = roleMenuService.delRMByRoleId(roleId); } Result result = null; if (isDelete) { result = new Result(0, "删除成功", null, null); }else { result = new Result(1, "删除失败", null, null); } System.out.println(result.getCode()); resp.setContentType("type/json;charset=utf-8"); resp.getWriter().write(FastJSONUtil.entityToJson(result)); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
07-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值