调用toString()方法的注意事项

时间:2021-07-28 21:26:27

【1】荔枝:Object转为 String;

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

request.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
//设置session超时间隔为120秒,以便测试超时的情况
session.setMaxInactiveInterval(120);
String sessionName = (String)session.getAttribute("name");
如果 不用 String类型强制转换,而使用  session.getAttribute("name").toString() 方法的话,首先得要保证 session.getAttribute("name") 返回的Object对象不为空, 如果为null的话,会抛出空指针异常的。。但如何使用强制类型转换的话,无论返回的对象是否为空,都不会报空指针异常。