在某项目中,前端jsp传入的用户id数据通过session域传入后台servlet进行处理的过程中,无意间出现了InvocationTargetException异常
前端部分代码如下:测试代码,非原项目代码
// 登录处理源码
if ("student".equals(role)) {
// 学生登录
// 创建学生服务对象
StudentService ss = new StudentServiceImpl();
// 调用服务中的登录进程
Student student = ss.login(uid, upwd);
// 判断此学生是否存在
if(student != null) {
// 如果存在,则登录成功, 存储学生信息
/* javax.servlet.http.HttpSession源码
* public void setAttribute(String name, Object value);
*/
// 第一种设置域属性方式:sid 在实体类中定义的是int类型,setAttribute中传入值则自动装箱成Integer
// req.getSession().setAttribute("uid", student.getSid());
// 第二种设置属性方式:为了验证,此处给指定字符串数据
req.getSession().setAttribute("uid", "1");
req.getSession().setAttribute("uname", student.getSname());
// 页面跳转
resp.sendRedirect(req.getContextPath() + "/index.jsp");
return;
} else {
// 失败信息
req.setAttribute("error", "用户名或密码错误,请重新登录!");
// 请求转发
req.getRequestDispatcher("login.jsp").forward(req, resp);
return;
}
}
<-- 登录成功后的跳转链接 -->
<div>
<a href="student.action?operation=queryInfo&uid=${uid }" class="left-font03">查看个人信息</a>
</div>
// 获取详细信息的servlet代码
public void queryInfo(HttpServletRequest req, HttpServletResponse resp){
StudentService ss = new StudentServiceImpl();
// 第一种获取uid方式:从url中的参数中获取uid,为String类型数据
//String uid = req.getParameter("uid");
// 第二种获取uid方式:从登录时保存在session中属性获取,此属性为int类型,通过setAttribute方法自动装箱成Integer类型属性传递
// int sid = (Integer) req.getSession().getAttribute("uid");
// 第二种获取uid方式:从登录时保存在session中属性获取,此属性为String类型
String uid = (String) req.getSession().getAttribute("uid");
// 出现InvocationTargetException异常的源头就在此,由于使用getAttribute方法获取保存在对应域内的属性值默认属性为Object,
// 此时强转类型需要使用与原类型匹配的类型,否则在下面语句转换数据为int类型时会出错
int sid = Integer.parseInt(uid);
Student student = ss.queryById(sid);
if(cs.queryById(sid) != null ){
req.setAttribute("student", student);
try {
// 请求转发 req.getRequestDispatcher("student/information.jsp").forward(req, resp);
return;
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 重写service方法,通过反射提取方法
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取当前对象所属类的Class对象
Class<?> c = this.getClass();
// 接收想要被调用的方法的名字
String name = req.getParameter("operation");
try {
// 通过class对象获取要调用的方法
// 如果被调用方法出错,此处就会抓取异常信息,也就是InvocationTargetException异常的来源
Method method = c.getMethod(name, HttpServletRequest.class, HttpServletResponse.class);
// 通过反射调用该方法
method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
个人总结分享,共同学习。