我正在开发一个Hibernate项目,需要教师通过表单注册。
Teacheradd.jsp
<%@page import="java.time.LocalDateTime"%>
<%@page import="java.util.Calendar"%>
<%@include file="header.jsp"%>
<div class="row">
<div class="col-lg-offset-2 col-lg-8 col-lg-offset-2">
<form class="border" action="addTeacher" method="post" style="">
<center><h2 style="color: whitesmoke">Sign Up</h2><hr style="margin:0px" /></center>
<div style="z-index: 100; background: whitesmoke">
<div class="input-group">
<label for="">Enter Name</label><req>*</req>
<input class="form-control" type="text" required="true" name="name" placeholder="Enter Name"/>
</div>
<div class="input-group">
<label for="">Enter Father`s Name</label><req>*</req>
<input class="form-control" type="text" required="true" name="fname" placeholder="Enter Father`s Name"/>
</div>
<div class="input-group">
<label for="">Enter DOB</label><req>*</req>
<input class="form-control" type="date" required="true" name="dob" max="<%out.print((LocalDateTime.now().getYear()-18) + "-01-01");%>"/>
</div>
<div class="input-group">
<label for="">Enter Gender</label><req>*</req><br/>
<select name="gender" class="form-control">
<option value="0">Male</option>
<option value="1">Female</option>
</select>
</div>
<div class="input-group">
<label for="">Enter Phone Number</label><req>*</req>
<input class="form-control" type="number" required="true" name="phone" placeholder="Enter Phone"/>
</div>
<div class="input-group">
<label for="">Enter Email</label><req>*</req>
<input class="form-control" type="text" required="true" name="email" placeholder="Enter Email"/>
</div>
<div class="input-group">
<label for="">Enter Address</label><req>*</req>
<input class="form-control" type="text" required="true" name="address1" placeholder="Address Line 1"/>
</div>
<div class="input-group">
<input class="form-control" type="text" name="address2" placeholder="Address Line 2"/>
</div>
<div class="input-group">
<input class="form-control" type="text" required="true" name="city" placeholder="City"/>
</div>
<div class="input-group">
<input class="form-control" type="number" required="true" name="pincode" placeholder="Pincode"/>
</div>
<div class="input-group">
<input class="form-control" type="text" required="true" name="state" placeholder="State"/>
</div>
<div class="input-group">
<%@include file="countrylistselect.jsp" %>
</div>
<div class="input-group">
<label for="">Joining Date</label><req>*</req>
<input class="form-control" type="date" required="true" name="joindate" value="<%out.print(LocalDateTime.now().toLocalDate());%>" />
</div>
<div class="input-group">
<label for="">Enter Password</label><req>*</req>
<input class="form-control" type="password" required="true" name="pass" placeholder="Password"/>
</div>
<div class="input-group">
<label for="">Confirm Password</label><req>*</req>
<input class="form-control" type="password" required="true" name="pass2" placeholder="Re-type Password"/>
</div>
<center>
<input type="checkbox" name="accept-eula" id="eula"/> <label for="eula">By checking this box, I agree to <a href="#">all terms</a> to use Teacher<sup>TM</sup></label><br/>
<input type="submit" value="Sign Up" class="btn btn-info" style="margin-bottom: 10px"/>
</center>
</div>
</form>
</div>
</div>
<div class="clearfix"></div>
<%@include file="footer.jsp" %>
值转到此servlet
addTeacher
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.newidea.tottracker.servlets;
import com.newidea.tottracker.action.TeacherAction;
import com.newidea.tottracker.mappings.Teacher;
import java.io.IOException;
import java.io.PrintWriter;
//import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Mohit
*/
public class addTeacher extends HttpServlet {
String name, fname, phno, email, address1, address2, city, state, country, pass1, pass2;
int gender, pincode, tid;
LocalDate dob, doj;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet addTeacher</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet addTeacher at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
initializeParams(request);
showValues(response);
if(pass1.equals(pass2)){
addNewTeacher();
response.getWriter().println("Teacher ID : " + tid);
response.getWriter().println("Added successfully");
}
else{
response.getWriter().println("Passwords do not match! Try again");
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
private void initializeParams(HttpServletRequest request) {
name = request.getParameter("name");
fname = request.getParameter("fname");
dob = LocalDate.parse(request.getParameter("dob"));
gender = Integer.parseInt(request.getParameter("gender"));
phno = request.getParameter("phone");
email = request.getParameter("email");
address1 = request.getParameter("address1");
address2 = request.getParameter("address2");
city = request.getParameter("city");
pincode = Integer.parseInt(request.getParameter("pincode"));
state = request.getParameter("state");
country = request.getParameter("country");
doj = LocalDate.parse(request.getParameter("joindate"));
pass1 = request.getParameter("pass");
pass2 = request.getParameter("pass2");
}
private void addNewTeacher() {
Teacher teacher = new Teacher();
teacher.setTeacherName(name);
teacher.setTeacherFname(fname);
teacher.setTeacherDob(dob);
teacher.setTeacherGender(gender);
teacher.setTeacherPhone(phno);
teacher.setTeacherEmail(email);
teacher.setAddress1(address1);
teacher.setAddress2(address2);
teacher.setCity(city);
teacher.setPincode(pincode);
teacher.setState(state);
teacher.setCountry(country);
teacher.setTeacherDoj(doj);
teacher.setTeacherStatus("true");
teacher.setTeacherLastLogin(LocalDateTime.now());
TeacherAction action = new TeacherAction();
tid = action.addTeacher(teacher);
}
private void showValues(HttpServletResponse response) {
try {
PrintWriter out = response.getWriter();
System.out.println(name);
System.out.println(fname);
System.out.println(dob);
System.out.println(gender);
System.out.println(phno);
System.out.println(email);
System.out.println(address1);
System.out.println(address2);
System.out.println(city);
System.out.println(pincode);
System.out.println(state);
System.out.println(country);
System.out.println(doj);
System.out.println(pass1);
System.out.println(pass2);
} catch (IOException ex) {
Logger.getLogger(addTeacher.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
和
Teacher.java
package com.newidea.tottracker.mappings;
// Generated 17 Feb, 2016 11:21:31 PM by Hibernate Tools 3.6.0
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
/**
* Teacher generated by hbm2java
*/
public class Teacher implements java.io.Serializable {
private Integer teacherId;
private String teacherName;
private String teacherFname;
private LocalDate teacherDob;
private int teacherGender;
private String teacherPhone;
private String address1;
private String address2;
private String city;
private int pincode;
private String state;
private String country;
private String teacherEmail;
private String teacherStatus;
private LocalDate teacherDoj;
private LocalDateTime teacherLastLogin;
private String teacherLastLoginIp;
private String teacherLevel;
private Set classrooms = new HashSet(0);
public Teacher() {
}
public Teacher(String teacherName, String teacherFname, LocalDate teacherDob, int teacherGender, String teacherPhone, String address1, String city, int pincode, String state, String country, String teacherEmail, String teacherStatus, LocalDate teacherDoj, LocalDateTime teacherLastLogin, String teacherLastLoginIp, String teacherLevel) {
this.teacherName = teacherName;
this.teacherFname = teacherFname;
this.teacherDob = teacherDob;
this.teacherGender = teacherGender;
this.teacherPhone = teacherPhone;
this.address1 = address1;
this.city = city;
this.pincode = pincode;
this.state = state;
this.country = country;
this.teacherEmail = teacherEmail;
this.teacherStatus = teacherStatus;
this.teacherDoj = teacherDoj;
this.teacherLastLogin = teacherLastLogin;
this.teacherLastLoginIp = teacherLastLoginIp;
this.teacherLevel = teacherLevel;
}
public Teacher(String teacherName, String teacherFname, LocalDate teacherDob, int teacherGender, String teacherPhone, String address1, String address2, String city, int pincode, String state, String country, String teacherEmail, String teacherStatus, LocalDate teacherDoj, LocalDateTime teacherLastLogin, String teacherLastLoginIp, String teacherLevel, Set classrooms) {
this.teacherName = teacherName;
this.teacherFname = teacherFname;
this.teacherDob = teacherDob;
this.teacherGender = teacherGender;
this.teacherPhone = teacherPhone;
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.pincode = pincode;
this.state = state;
this.country = country;
this.teacherEmail = teacherEmail;
this.teacherStatus = teacherStatus;
this.teacherDoj = teacherDoj;
this.teacherLastLogin = teacherLastLogin;
this.teacherLastLoginIp = teacherLastLoginIp;
this.teacherLevel = teacherLevel;
this.classrooms = classrooms;
}
public Integer getTeacherId() {
return this.teacherId;
}
public void setTeacherId(Integer teacherId) {
this.teacherId = teacherId;
}
public String getTeacherName() {
return this.teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public String getTeacherFname() {
return this.teacherFname;
}
public void setTeacherFname(String teacherFname) {
this.teacherFname = teacherFname;
}
public LocalDate getTeacherDob() {
return this.teacherDob;
}
public void setTeacherDob(LocalDate teacherDob) {
this.teacherDob = teacherDob;
}
public int getTeacherGender() {
return this.teacherGender;
}
public void setTeacherGender(int teacherGender) {
this.teacherGender = teacherGender;
}
public String getTeacherPhone() {
return this.teacherPhone;
}
public void setTeacherPhone(String teacherPhone) {
this.teacherPhone = teacherPhone;
}
public String getAddress1() {
return this.address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return this.address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public int getPincode() {
return this.pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public String getTeacherEmail() {
return this.teacherEmail;
}
public void setTeacherEmail(String teacherEmail) {
this.teacherEmail = teacherEmail;
}
public String getTeacherStatus() {
return this.teacherStatus;
}
public void setTeacherStatus(String teacherStatus) {
this.teacherStatus = teacherStatus;
}
public LocalDate getTeacherDoj() {
return this.teacherDoj;
}
public void setTeacherDoj(LocalDate teacherDoj) {
this.teacherDoj = teacherDoj;
}
public LocalDateTime getTeacherLastLogin() {
return this.teacherLastLogin;
}
public void setTeacherLastLogin(LocalDateTime teacherLastLogin) {
this.teacherLastLogin = teacherLastLogin;
}
public String getTeacherLastLoginIp() {
return this.teacherLastLoginIp;
}
public void setTeacherLastLoginIp(String teacherLastLoginIp) {
this.teacherLastLoginIp = teacherLastLoginIp;
}
public String getTeacherLevel() {
return this.teacherLevel;
}
public void setTeacherLevel(String teacherLevel) {
this.teacherLevel = teacherLevel;
}
public Set getClassrooms() {
return this.classrooms;
}
public void setClassrooms(Set classrooms) {
this.classrooms = classrooms;
}
}
TeacherAction.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.newidea.tottracker.action;
import com.newidea.tottracker.mappings.Teacher;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* @author Mohit
*/
public class TeacherAction extends BaseAction {
Session session;
Transaction tx = null;
Integer tid = null;
public TeacherAction() {
super();
}
public Integer addTeacher(Teacher teacher) {
session = getSessionFactory().openSession();
try {
tx = session.beginTransaction();
tid = (Integer) session.save(teacher);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
System.out.println("Exception : " + e.getMessage());
} finally {
session.close();
}
return tid;
}
public void deleteTeacher(Integer tid) {
session = getSessionFactory().openSession();
try{
tx = session.beginTransaction();
Teacher teacher = (Teacher) session.get(Teacher.class, tid);
session.delete(teacher);
tx.commit();
}catch(Exception e){
if(tx != null) tx.rollback();
System.out.println("Exception : " + e.getMessage());
}
finally{
session.close();
}
}
public void updateTeacher(Integer tid, Teacher newTeacher){
session = getSessionFactory().openSession();
try{
tx = session.beginTransaction();
Teacher oldTeacher = (Teacher) session.get(Teacher.class, tid);
oldTeacher.setTeacherName(newTeacher.getTeacherName());
oldTeacher.setTeacherFname(newTeacher.getTeacherFname());
oldTeacher.setTeacherDob(newTeacher.getTeacherDob());
oldTeacher.setTeacherGender(newTeacher.getTeacherGender());
oldTeacher.setTeacherPhone(newTeacher.getTeacherPhone());
oldTeacher.setAddress1(newTeacher.getAddress1());
oldTeacher.setAddress2(newTeacher.getAddress2());
oldTeacher.setCity(newTeacher.getCity());
oldTeacher.setPincode(newTeacher.getPincode());
oldTeacher.setState(newTeacher.getState());
oldTeacher.setCountry(newTeacher.getCountry());
oldTeacher.setTeacherEmail(newTeacher.getTeacherEmail());
oldTeacher.setTeacherStatus(newTeacher.getTeacherStatus());
oldTeacher.setTeacherDoj(newTeacher.getTeacherDoj());
oldTeacher.setTeacherLastLoginIp(newTeacher.getTeacherLastLoginIp());
// oldTeacher.setTeacherLevel(newTeacher.getTeacherLevel());
session.merge(oldTeacher);
tx.commit();
}catch(Exception e){
if(tx != null) tx.rollback();
System.out.println("Exception : " + e.getMessage());
}
finally{
session.close();
}
}
}
以下是stacktrace:
18-Feb-2016 17:04:54.313 SEVERE [http-nio-8080-exec-83] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [addTeacher] in context with path [/Hibernate] threw exception
java.lang.NullPointerException
at com.newidea.tottracker.servlets.addTeacher.addNewTeacher(addTeacher.java:146)
at com.newidea.tottracker.servlets.addTeacher.doPost(addTeacher.java:89)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
服务器日志:
18-Feb-2016 17:04:53.049 INFO [http-nio-8080-exec-83] org.hibernate.cfg.Configuration.addResource HHH000221: Reading mappings from resource: com/newidea/tottracker/mappings/ExamType.hbm.xml
18-Feb-2016 17:04:53.057 INFO [http-nio-8080-exec-83] org.hibernate.cfg.Configuration.addResource HHH000221: Reading mappings from resource: com/newidea/tottracker/mappings/Role.hbm.xml
18-Feb-2016 17:04:53.125 INFO [http-nio-8080-exec-83] org.hibernate.cfg.Configuration.addResource HHH000221: Reading mappings from resource: com/newidea/tottracker/mappings/Teacher.hbm.xml
18-Feb-2016 17:04:53.141 INFO [http-nio-8080-exec-83] org.hibernate.cfg.Configuration.addResource HHH000221: Reading mappings from resource: com/newidea/tottracker/mappings/Course.hbm.xml
18-Feb-2016 17:04:53.149 INFO [http-nio-8080-exec-83] org.hibernate.cfg.Configuration.doConfigure HHH000041: Configured SessionFactory: null
18-Feb-2016 17:04:53.269 INFO [http-nio-8080-exec-83] org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH000402: Using Hibernate built-in connection pool (not for production use!)
18-Feb-2016 17:04:53.277 INFO [http-nio-8080-exec-83] org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH000115: Hibernate connection pool size: 20
18-Feb-2016 17:04:53.277 INFO [http-nio-8080-exec-83] org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH000006: Autocommit mode: false
18-Feb-2016 17:04:53.277 INFO [http-nio-8080-exec-83] org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/sms?zeroDateTimeBehavior=convertToNull]
18-Feb-2016 17:04:53.277 INFO [http-nio-8080-exec-83] org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH000046: Connection properties: {user=root}
18-Feb-2016 17:04:53.625 INFO [http-nio-8080-exec-83] org.hibernate.dialect.Dialect.<init> HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
18-Feb-2016 17:04:53.801 INFO [http-nio-8080-exec-83] org.hibernate.engine.transaction.internal.TransactionFactoryInitiator.initiateService HHH000399: Using default transaction strategy (direct JDBC transactions)
18-Feb-2016 17:04:53.809 INFO [http-nio-8080-exec-83] org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory.<init> HHH000397: Using ASTQueryTranslatorFactory
Exception : java.time.LocalDate cannot be cast to java.util.Date
任何人都可以帮忙,因为它让我发疯!提前谢谢。
答案 0 :(得分:0)
似乎存在两种不同的错误,其中一种可能会产生误导,而另一种则是某种错误造成的。正如您在服务器日志中看到的那样:
Exception : java.time.LocalDate cannot be cast to java.util.Date
没有直接转换为旧版日期类型。有一种解决方法,但如果您只是要使用旧的日期类型,您也可以更改以下行:
teacher.setTeacherLastLogin(LocalDateTime.now());
为:
teacher.setTeacherLastLogin(new java.util.Date());
如果您坚持使用新的日期API,则可以将hibernate-java8
包添加到依赖项中以直接支持它们。但是,Instant
类型更适合时间戳,而不是LocalDateTime。
EDIT1:
NullPointerException是由action.addTeacher(teacher)
函数返回null
并尝试将其转换为原始值引起的。我相信日期问题是导致服务器日志中异常的原因(无论如何最后一个日志列表),因此当函数返回时TeacherAction.tid
仍为null
。