好的,我知道之前已经问过这个问题了。但这里的区别是我没有保存任何对象。这个想法是让学生只在父母发起会话(登录)时才注册。我有4个实体:
所有老师,学生和家长都有一个user_id。学生必须始终拥有parent_id。当父登录时,会保存父ID,当学生尝试注册时,它根本找不到父,并且在堆栈跟踪中抛出NPE。但是当UserAction由main()运行时,它会完美地显示ID。
代码UserAction.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.data.Roles;
import com.newidea.tottracker.mappings.Parent;
import com.newidea.tottracker.mappings.Student;
import com.newidea.tottracker.mappings.Teacher;
import com.newidea.tottracker.mappings.User;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Restrictions;
/**
*
* @author Mohit
*/
public class UserAction extends BaseAction{
public UserAction(){}
public int addUser(User user){
session = getSessionFactory().openSession();
tx = null;
int id = 0;
try{
tx = session.beginTransaction();
id = (Integer) session.save(user);
tx.commit();
}catch(Exception e){
if(tx != null) tx.rollback();
}finally{
session.close();
}
return id;
}
public User getUser(int id){
User user;
session = getSessionFactory().openSession();
tx = null;
try{
tx = session.beginTransaction();
user = (User) session.get(User.class, id);
if(!tx.wasCommitted())tx.commit();
System.out.println("Returning user ID : " + user.getId());
return user;
}catch(Exception e){
if(tx != null) tx.rollback();
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}finally{
session.close();
}
System.out.println("Returning user ID : null");
return null;
}
public User getUserByDetails(int role, String email){
try{
session = getSessionFactory().openSession();
Criteria c = session.createCriteria(User.class);
c.add(Restrictions.eq("email", email));
c.add(Restrictions.eq("role", getRole(role)));
if(c.list().isEmpty()) return null;
else return (User) c.list().get(0);
}catch(HibernateException e){
System.out.println("Error : " + e.getMessage());
}finally{
if(session.isOpen()) session.close();
}
return null;
}
public User getUserByEmail(String email){
try{
session = getSessionFactory().openSession();
Criteria c = session.createCriteria(User.class);
c.add(Restrictions.eq("email", email));
if(c.list().isEmpty()) return null;
else return (User) c.list().get(0);
}catch(HibernateException e){
System.out.println("Error : " + e.getMessage());
}finally{
if(session.isOpen()) session.close();
}
return null;
}
public int getPersonIdByUserId(int userid, int role){
try{
System.out.println("Starting to fetch Person Type");
session = getSessionFactory().openSession();
// tx = session.beginTransaction();
Criteria c = null;
switch(role){
case Roles.STUDENT:
c = session.createCriteria(Student.class);
break;
case Roles.PARENT:
c = session.createCriteria(Parent.class);
break;
case Roles.TEACHER:
c = session.createCriteria(Teacher.class);
break;
}
System.out.println("Fetch User ID and Set to criteria");
c.add(Restrictions.eq("user", getUser(userid)));
System.out.println("Criteria set successfully!");
switch(role){
case Roles.STUDENT:
System.out.println("Returning Student User ID : " + userid);
Student student = (Student) c.list().get(0);
return student.getId();
case Roles.PARENT:
System.out.println("Returning Parent User ID : " + userid);
Parent parent = (Parent) c.list().get(0);
return parent.getId();
case Roles.TEACHER:
System.out.println("Returning Teacher User ID : " + userid);
Teacher teacher = (Teacher) c.list().get(0);
return teacher.getId();
}
}catch(HibernateException e){
System.out.println("Error : " + e.getMessage());
// if(tx != null) tx.rollback();
}finally{
// tx.commit();
if(session.isOpen()) session.close();
}
return 0;
}
public boolean deleteUser(int id){
User user;
session = getSessionFactory().openSession();
tx = null;
try{
tx = session.beginTransaction();
user = (User) session.get(User.class, id);
session.delete(user);
tx.commit();
return true;
}catch(Exception e){
if(tx != null) tx.rollback();
}finally{
session.close();
}
return false;
}
public boolean updateUser(int id, User newUser){
User user;
session = getSessionFactory().openSession();
tx = null;
try{
tx = session.beginTransaction();
user = (User) session.get(User.class, id);
user.setUsername(newUser.getUsername());
user.setAnswer(newUser.getAnswer());
user.setEmail(newUser.getEmail());
user.setPassword(newUser.getPassword());
user.setRole(newUser.getRole());
user.setSecurityQuestion(newUser.getSecurityQuestion());
session.merge(user);
tx.commit();
return true;
}catch(Exception e){
if(tx != null) tx.rollback();
}finally{
session.close();
}
return false;
}
public static void main(String[] args){
System.out.println("User ID : 4\nRole ID : 1\nPerson Enitity ID : " + new UserAction().getPersonIdByUserId(4,1));
System.out.println("User ID : 4\nRole ID : 1\nPerson Enitity ID : " + new UserAction().getPersonIdByUserId(4,1));
System.out.println("User ID : 4\nRole ID : 1\nPerson Enitity ID : " + new UserAction().getPersonIdByUserId(4,1));
System.out.println("User ID : 4\nRole ID : 1\nPerson Enitity ID : " + new UserAction().getPersonIdByUserId(4,1));
}
}
AddStudent.jsp //导致错误的页面
<%@page import="com.newidea.tottracker.mappings.ParentProfileId"%>
<%@page import="com.newidea.tottracker.mappings.ParentProfile"%>
<%@page import="com.newidea.tottracker.action.Views"%>
<%@page import="com.newidea.tottracker.action.AddressAction"%>
<%@page import="com.newidea.tottracker.mappings.Address"%>
<%@page import="com.newidea.tottracker.action.ParentAction"%>
<%@page import="com.newidea.tottracker.action.UserAction"%>
<%@page import="com.newidea.tottracker.data.Roles"%>
<%@page import="com.newidea.tottracker.mappings.Parent"%>
<%@page import="java.time.LocalDateTime"%>
<%@page import="java.util.Calendar"%>
<%@include file="header.jsp"%>
<% Object roleObj = session.getAttribute("role");
Object idObj = session.getAttribute("uid");
int role, uid;
Views profileDB = new Views();
ParentProfileId profile;
System.out.println(1);
if (roleObj == null || idObj == null || !(Integer.parseInt(roleObj.toString()) == Roles.PARENT)) {
roleObj = 0;
System.out.println("In null value block");
response.sendRedirect("login.jsp?code=1");
return;
} else {
role = Integer.parseInt(roleObj.toString());
uid = Integer.parseInt(idObj.toString());
System.out.println("In not null value block");
// System.out.println("Role : " + role + " UID : " + new UserAction().getPersonIdByUserId(uid, role));
int parent_id = new UserAction().getPersonIdByUserId(uid, role);
System.out.println("Parent ID : " + parent_id);
profile = profileDB.getParentProfile(parent_id);
}
%>
<div class="container-fluid">
<div class="row">
<div class="col-lg-offset-2 col-lg-8 col-lg-offset-2">
<form class="border" action="addStudent" method="post" style="">
<center><h2 style="color: whitesmoke; ">Add your Child</h2><hr style="margin:0px" /></center>
<div style="z-index: 100; background: whitesmoke">
<h3 style="font-size: 23px; padding: 15px;padding-bottom: 5px; margin: 0px">Personal Details</h3><center><hr style="margin:1px; height: 1px; background: lightgray; width: 96%" /></center>
<div class="input-group">
<label for="">First Name</label><req>*</req>
<input class="form-control" type="text" required="true" name="first_name" placeholder="Enter First Name"/>
</div>
<div class="input-group">
<label for="">Last Name</label><req>*</req>
<input class="form-control" type="text" required="true" name="last_name" placeholder="Enter Last Name"/>
</div>
<div class="input-group">
<input type="hidden" name="parent_id" value="<%out.print(profile.getId());%>"/>
<label for="">Parent`s Name</label><req>*</req>
<input class="form-control" type="text" required="true" name="fname" placeholder="Enter Parent`s Name" value="<%out.print(profile.getFirstName() + " " + profile.getLastName());%>" readonly="true"/>
</div>
<div class="input-group">
<label for="">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="">Gender</label><req>*</req><br/>
<select name="gender" class="form-control">
<option value="0">Male</option>
<option value="1">Female</option>
</select>
</div>
<h3 style="font-size: 23px; padding: 15px;padding-bottom: 5px; margin: 0px">Contact Information</h3><center><hr style="margin:1px; height: 1px; background: lightgray; width: 96%" /></center>
<div class="input-group">
<label for="">Phone Number</label><req>*</req>
<input class="form-control" type="number" required="true" name="phone" placeholder="Enter Phone"/>
</div>
<div id="adderss">
<div class="input-group">
<label for="">Address</label><req>*</req>
<span style="position: absolute; right: 0px;" id="sameAddr">
<input type="hidden" name="same_address" value="0"/>
<input type="checkbox" name="same_address" id="sameAddress" value="1"><label for="sameAddress"> I live with my parent.</label>
</span>
<input type="hidden" name="address_id" value="<%out.print(profile.getAddressId());%>"/>
<input class="form-control" type="text" required="true" name="address1" value="<%out.print(profile.getAddress1());%>" placeholder="Address Line 1"/>
</div>
<div class="input-group">
<input class="form-control" type="text" name="address2" value="<%out.print(profile.getAddress2());%>" placeholder="Address Line 2"/>
</div>
<div class="input-group">
<input class="form-control" type="text" required="true" name="city" value="<%out.print(profile.getCity());%>" placeholder="City"/>
</div>
<div class="input-group">
<input class="form-control" type="text" required="true" name="state" value="<%out.print(profile.getState());%>" placeholder="State"/>
</div>
<div class="input-group">
<input type="hidden" name="country_id" value="<%out.print(profile.getCountryId());%>"/>
<%@include file="countrylistselect.jsp" %>
</div>
<div class="input-group">
<input class="form-control" type="number" required="true" name="pincode" value="<%out.print(profile.getPincode());%>" placeholder="Pincode"/>
</div>
</div>
<div class="input-group">
<label for="">Joining Date</label><req>*</req>
<input class="form-control" type="date" required="true" name="doj" value="<%out.print(LocalDateTime.now().toLocalDate());%>" />
</div>
<h3 style="font-size: 23px; padding: 15px;padding-bottom: 5px; margin: 0px">Login and Password Recovery Details</h3><center><hr style="margin:1px; height: 1px; background: lightgray; width: 96%" /></center>
<div class="input-group">
<label for="">Email</label><req>*</req>
<input class="form-control" type="text" required="true" name="email" placeholder="Enter Email"/>
</div>
<div class="input-group">
<label for="">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>
<div class="input-group">
<label for="">Security Question</label><req>*</req> (In case you forget your password, answer this)
<input class="form-control" type="text" required="true" name="security_question" placeholder="Security Question" value="Mother`s Maiden Name"/>
</div>
<div class="input-group">
<label for="">Your Answer</label><req>*</req>
<input class="form-control" type="text" required="true" name="answer" placeholder="Your Answer"/>
</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 TotTracker<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>
<script>
$().ready(function() {
// alert(("#sameAddress").val);
$("#sameAddress").change(function() {
if ($("#sameAddress").is(":checked")) {
// alert("Child has same address!");
$("input[name=address1]").val("<%out.print(profile.getAddress1());%>").change();
$("input[name=address2]").val("<%out.print(profile.getAddress2());%>").change();
$("input[name=city]").val("<%out.print(profile.getCity());%>").change();
$("input[name=state]").val("<%out.print(profile.getState());%>").change();
$("input[name=pincode]").val("<%out.print(profile.getPincode());%>").change();
$("#country").val("<%out.print(profile.getCountryIso());%>").change();
$("input[name=address1]").attr("readonly", true);
$("input[name=address2]").attr("readonly", true);
$("input[name=city]").attr("readonly", true);
$("input[name=state]").attr("readonly", true);
$("input[name=pincode]").attr("readonly", true);
$("#country").attr("readonly", true);
$("input[name=address1]").removeAttr("required");
$("input[name=address2]").removeAttr("required");
$("input[name=city]").removeAttr("required");
$("input[name=state]").removeAttr("required");
$("input[name=pincode]").removeAttr("required");
} else {
// alert("Child dont have same address!");
$("input[name=address1]").removeAttr("readonly");
$("input[name=address2]").removeAttr("readonly");
$("input[name=city]").removeAttr("readonly");
$("input[name=state]").removeAttr("readonly");
$("input[name=pincode]").removeAttr("readonly");
$("#country").removeAttr("readonly");
$("input[name=address1]").attr("required", true);
$("input[name=address2]").attr("required", true);
$("input[name=city]").attr("required", true);
$("input[name=state]").attr("required", true);
$("input[name=pincode]").attr("required", true);
$("#country").attr("required", true);
}
});
});
</script>
<%@include file="footer.jsp" %>
堆栈跟踪:
22-Mar-2016 16:56:05.694 SEVERE [41] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [/TotTrack] threw exception [An exception occurred processing JSP page /AddStudent.jsp at line 52
49: <input class="form-control" type="text" required="true" name="last_name" placeholder="Enter Last Name"/>
50: </div>
51: <div class="input-group">
52: <input type="hidden" name="parent_id" value="<%out.print(profile.getId());%>"/>
53: <label for="">Parent`s Name</label><req>*</req>
54: <input class="form-control" type="text" required="true" name="fname" placeholder="Enter Parent`s Name" value="<%out.print(profile.getFirstName() + " " + profile.getLastName());%>" readonly="true"/>
55: </div>
Stacktrace:] with root cause
java.lang.NullPointerException
at org.apache.jsp.AddStudent_jsp._jspService(AddStudent_jsp.java:297)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
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)
服务器日志:
1
22-Mar-2016 16:56:05.170 INFO [http-nio-8080-exec-15] org.hibernate.cfg.Configuration.configure HHH000043: Configuring from resource: /hibernate.cfg.xml
In not null value block
22-Mar-2016 16:56:05.462 INFO [http-nio-8080-exec-15] org.hibernate.cfg.Configuration.addResource HHH000221: Reading mappings from resource: com/newidea/tottracker/mappings/StudentProfile.hbm.xml
22-Mar-2016 16:56:05.474 INFO [http-nio-8080-exec-15] org.hibernate.cfg.Configuration.addResource HHH000221: Reading mappings from resource: com/newidea/tottracker/mappings/ExamResult.hbm.xml
22-Mar-2016 16:56:05.490 INFO [http-nio-8080-exec-15] org.hibernate.cfg.Configuration.doConfigure HHH000041: Configured SessionFactory: null
22-Mar-2016 16:56:05.494 INFO [http-nio-8080-exec-15] org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH000402: Using Hibernate built-in connection pool (not for production use!)
22-Mar-2016 16:56:05.494 INFO [http-nio-8080-exec-15] org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH000115: Hibernate connection pool size: 20
22-Mar-2016 16:56:05.494 INFO [http-nio-8080-exec-15] org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH000006: Autocommit mode: false
22-Mar-2016 16:56:05.494 INFO [http-nio-8080-exec-15] org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/sms?zeroDateTimeBehavior=convertToNull]
22-Mar-2016 16:56:05.494 INFO [http-nio-8080-exec-15] org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure HHH000046: Connection properties: {user=root, password=****}
22-Mar-2016 16:56:05.550 INFO [http-nio-8080-exec-15] org.hibernate.dialect.Dialect.<init> HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
22-Mar-2016 16:56:05.570 INFO [http-nio-8080-exec-15] org.hibernate.engine.transaction.internal.TransactionFactoryInitiator.initiateService HHH000399: Using default transaction strategy (direct JDBC transactions)
22-Mar-2016 16:56:05.570 INFO [http-nio-8080-exec-15] org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory.<init> HHH000397: Using ASTQueryTranslatorFactory
Starting to fetch Person Type
Fetch User ID and Set to criteria
Error : Transaction not successfully started
Parent ID : 0
答案 0 :(得分:0)
对于此问题,错误在传递的值中。我首先在验证servlet上调用getPersonIdByUserId
,然后再次在导致真正痛苦的页面上调用WirelessNet:sendData
。对于其他任何人来说,它可能会有所帮助。