ERROR org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler - Exception occurred during processing request: null
java.lang.NullPointerException
at service.impl.StudentsDAOImpl.addStudents(StudentsDAOImpl.java:64) ~[StudentsDAOImpl.class:?]
at action.StudentsAction.add(StudentsAction.java:51) ~[StudentsAction.class:?]
感谢分享
你可以参考一下:把下面的代码内容,跟你写的做一下对比
一、在StudentsDAOImpl.java中实现添加学生的方法即可
//添加学生 public boolean addStudents(Students s) { //因为添加的学生是没有学号的,所以我们需要添加一个学号 s.setSid(getNewSid()); Transaction tx = null; try{ Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession(); tx = session.beginTransaction(); session.save(s); tx.commit(); return true; }catch(Exception ex){ ex.printStackTrace(); tx.commit(); return false; }finally{ if(tx != null){ tx = null; } } }
二、StudentsAction类中add()方法:
//添加学生 public String add() throws Exception{ Students s = new Students(); s.setSname(request.getParameter("sname")); s.setGender(request.getParameter("gender")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); s.setBirthday(sdf.parse(request.getParameter("birthday"))); s.setAddress(request.getParameter("address")); StudentsDAO sdao = new StudentsDAOImpl(); sdao.addStudents(s); return "add_success"; }
三、struts.xml
<package name="students" namespace="/students" extends="default"> <action name="*_*" class="action.{1}Action" method="{2}"> <result name="query_success">/students/Students_query_success.jsp</result> <result name="add_success">/students/Students_add_success.jsp</result> <result name="modify_success">/students/Students_modify.jsp</result> <result name="delete_success" type="chain">Students_query</result><!-- chain表示后面链接一个动作,也就是服务器内部转发,它转发的只能是action,而不是一个jsp页面 --> </action> </package>
四、Students_add.jsp中的form表单
<form name="addForm" action="<%=path%>/students/Students_add.action" method="post"> <table width="400" > <tr> <td width="30%">姓名:</td> <td><input type="text" name="sname" /></td> </tr> <tr> <td>性别:</td> <td><input type="radio" name="gender" value="男" checked="checked"/>男<input type="radio" name="gender" value="女"/>女</td> </tr> <tr> <td>出生日期:</td> <td><input name="birthday" type="text" id="control_date" size="20" maxlength="10" onclick="new Calendar().show(this);" readonly="readonly" /> </td> </tr> <tr> <td>地址:</td> <td><input type="text" name="address" /></td> </tr> <tr> <td colspan="2" align="center"><input class="button" type="submit" value="添加"></td> </tr> </table> </form>