У меня есть веб-сайт на Java, который использует сервлет и JSP, а сервер - мой локальный хост.Большинство частей веб-сайта работают хорошо, но что-то не так, когда я нажимаю кнопку «Обновить пациента», отображается «500 внутренних» и появляется сообщение об ошибке:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message java.lang.NullPointerException
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:565)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:481)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
java.lang.NullPointerException
org.focus.DAO.PatientDAO.getAllPat(PatientDAO.java:220)
org.focus.servlets.PatientUServlet.doGet(PatientUServlet.java:65)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:742)
org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:712)
org.apache.jsp.common.lp_jsp._jspService(lp_jsp.java:177)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
А вот и моя «лу».jsp ":
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%
String context = (String) request.getContextPath();
String role = (String) session.getAttribute("role");
String id = (String) session.getAttribute("id");
String userName = (String) session.getAttribute("name");
String errMsg = (String) request.getAttribute("error");
if (errMsg == null) {
errMsg = "";
}
String status = (String) request.getAttribute("status");
if (status == null){
status = "";
}
%>
<html>
<head>
<script>
var context = '<%=context%>';
var role = '<%=role%>';
var id= '<%=id%>';
</script>
<!--import DHTMLX library component javascripts and css files-->
<link rel="stylesheet" type="text/css"
href="<%=context%>/js/dhtmlx/dhtmlx.css" />
<link rel="stylesheet" type="text/css" href="<%=context%>/css/style.css">
</head>
<body>
<jsp:forward page="/PatientUServlet?action=listPatient"/>
</body>
<!--Footer-->
<footer class="page-footer font-small blue pt-4 mt-4">
<!--Copyright-->
<div class="footer-copyright py-3 text-center">
<div class="container-fluid">
<script>
var theDate=new Date();
document.write("© "+ theDate.getFullYear());</script>
</div>
</div>
<!--/.Copyright-->
</footer>
<!--/.Footer-->
</html>
Вот мой" listPatient.jsp ":
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%
String context = (String) request.getContextPath();
String userName = (String) session.getAttribute("id");
String role = (String) session.getAttribute("role");
//out.println("CALLING main.jsp values: "+ userName +" "+role);
%>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>List Patient Template</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="jumbotron.css" rel="stylesheet">
<script>
var context = '<%=context%>';
</script>
<script>
function ConfirmDelete()
{
var Delet_Confirm= confirm("Do you really want to delete this record ?");
if (Delet_Confirm== true && <%=role%>=="ADMIN")
{
return true;
}
else
{
return false;
}
}
</script>
</head>
<body>
<% if (role.equals("ADMIN")) {%>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="<%=context%>/main.jsp">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%=context%>/common/myaccount.jsp">My Account</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%=context%>/common/analysis.jsp?">Patient Analytics</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Administrator Tasks
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="<%=context%>/common/register.jsp">Register BHCO</a>
<a class="dropdown-item" href="<%=context%>/common/addpatient.jsp">Add Patient</a>
<a class="dropdown-item" href="<%=context%>/common/assignpatient.jsp">Assign Patient</a>
<a class="dropdown-item" href="<%=context%>/common/lu.jsp">Update User</a>
<a class="dropdown-item" href="<%=context%>/common/lp.jsp">Update Patient</a>
</div>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" action="<%=context%>/LogoutServlet" method="post">
<a class="form-control mr-sm-2" href="#">Your role: <%=role%> </a>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Logout</button>
</form>
</div>
</nav>
<%}else{ %>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="<%=context%>/main.jsp">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%=context%>/common/myaccount.jsp">My Account</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%=context%>/common/analysis.jsp?">Patient Analytics</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" action="<%=context%>/LogoutServlet" method="post">
<a class="form-control mr-sm-2" href="#">Your role: <%=role%> </a>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Logout</button>
</form>
</div>
</nav>
<%} %>
<div class="box-centerside">
<br />
<br />
</div>
<table class="table">
<thead>
<tr>
<th>Patient Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Email</th>
<th>Last Updated On</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${pats}" var="pat">
<tr>
<td><c:out value="${pat.patid}" /></td>
<td><c:out value="${pat.pfname}" /></td>
<td><c:out value="${pat.plname}" /></td>
<td><fmt:formatDate pattern="yyyy-MM-dd" value="${pat.dob}" /></td>
<td><c:out value="${pat.email}" /></td>
<td><c:out value="${pat.updatedate}" /></td>
<td><a href="<%=context%>/PatientUServlet?action=edit&patid=<c:out value="${pat.patid}"/>">Update</a></td>
<td><a onclick="return ConfirmDelete();" href="<%=context%>/PatientUServlet?action=delete&patid=<c:out value="${pat.patid}" />">Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
</body>
<!--Footer-->
<footer class="page-footer font-small blue pt-4 mt-4">
<!--Copyright-->
<div class="footer-copyright py-3 text-center">
<div class="container-fluid">
<script>
var theDate=new Date();
document.write("© "+ theDate.getFullYear() + " University of Pittsburgh");</script>
</div>
</div>
<!--/.Copyright-->
</footer>
<!--/.Footer-->
Вот мой" PatientUServlet.java ":
package org.focus.servlets;
import java.io.IOException;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.focus.DAO.PatientDAO;
import org.focus.data.Patient;
/**
* Servlet implementation class UserServlet
*/
@WebServlet("/PatientUServlet")
public class PatientUServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String INSERT_OR_EDIT = "/common/patient.jsp";
private static String LIST_PAT = "/common/listPatient.jsp";
private PatientDAO dao;
/**
* @throws Exception
* @see HttpServlet#HttpServlet()
*/
public PatientUServlet() throws Exception {
super();
dao = new PatientDAO();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward="";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("delete")){
int patid = Integer.parseInt(request.getParameter("patid"));
dao.deletePat(patid);
forward = LIST_PAT;
request.setAttribute("pats", dao.getAllPat());
} else if (action.equalsIgnoreCase("edit")){
forward = INSERT_OR_EDIT;
int patid = Integer.parseInt(request.getParameter("patid"));
Patient pat = dao.getPatById(patid);
request.setAttribute("pat", pat);
} else if (action.equalsIgnoreCase("listPatient")){
forward = LIST_PAT;
request.setAttribute("pats", dao.getAllPat());
} else {
forward = INSERT_OR_EDIT;
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Patient pat = new Patient();
pat.setPatid(Integer.parseInt(request.getParameter("patid")));
pat.setMed_no(Integer.parseInt(request.getParameter("medNo")));
pat.setFamily_id(Integer.parseInt(request.getParameter("familyId")));
pat.setBlock_id(Integer.parseInt(request.getParameter("blockId")));
pat.setCommunity_id(Integer.parseInt(request.getParameter("communityId")));
pat.setEmail(request.getParameter("email"));
pat.setPfname(request.getParameter("firstName"));
pat.setPmname(request.getParameter("midName"));
pat.setPlname(request.getParameter("lastName"));
pat.setPhone(request.getParameter("phone"));
pat.setGender(request.getParameter("gender"));
pat.setRace(request.getParameter("race"));
pat.setMaritalstatus(request.getParameter("maritalstatus"));
pat.setStreetnum(request.getParameter("streetNumber"));
pat.setStreetname(request.getParameter("streetName"));
pat.setAptno(request.getParameter("aptNo"));
pat.setCity(request.getParameter("city"));
pat.setState(request.getParameter("state"));
pat.setZip(Integer.parseInt(request.getParameter("zip")));
pat.setLatitude(Double.parseDouble(request.getParameter("latitude")));
pat.setLongitude(Double.parseDouble(request.getParameter("longitude")));
Date dob;
try {
dob = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("dob"));
pat.setDob(dob);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dao.updatePat(pat);
RequestDispatcher view = request.getRequestDispatcher(LIST_PAT);
request.setAttribute("pats", dao.getAllPat());
view.forward(request, response);
}
}
А вотмой "PatientDAO":
package org.focus.DAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import org.apache.log4j.Logger;
import org.focus.data.PatientAssignDataBean;
import org.focus.data.PatientDataBean;
import org.focus.data.Patient;
import org.focus.db.JdbcUtil;
import org.focus.util.DbUtil;
public class PatientDAO {
private static Logger log = Logger.getLogger(PatientDAO.class);
private Connection connection1;
public PatientDAO() throws Exception {
connection1 = DbUtil.getConnection();
}
private static java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
public static ArrayList<PatientDataBean> getAllPatients(){
ArrayList<PatientDataBean> result = new ArrayList<>();
try ( Connection con = JdbcUtil.getConnection()) {
String sql= "select patientid,patient_first_name,patient_last_name from patients";
try (Statement st = con.createStatement()) {
System.out.println(sql);
ResultSet rs = st.executeQuery(sql);
while (rs.next()){
result.add(new PatientDataBean(rs.getInt(1),rs.getString(2),rs.getString(3)));
}
} catch (Exception e) {
log.error("Statement in patients search error", e);
e.printStackTrace();
result = null;
}
}
catch (Exception e) {
log.error("patients search error", e);
e.printStackTrace();
result = null;
}
return result;
}
public static ArrayList<PatientDataBean> getAllUnassignedPatients(){
ArrayList<PatientDataBean> result = new ArrayList<>();
try ( Connection con = JdbcUtil.getConnection()) {
String sql= "select patientid,patient_first_name,patient_last_name "
+ "from patients where patientid not in (select patientid from patientsassigns)";
try (Statement st = con.createStatement()) {
System.out.println(sql);
ResultSet rs = st.executeQuery(sql);
while (rs.next()){
result.add(new PatientDataBean(rs.getInt(1),rs.getString(2),rs.getString(3)));
}
} catch (Exception e) {
log.error("Statement in patients search error", e);
e.printStackTrace();
result = null;
}
}
catch (Exception e) {
log.error("patients search error", e);
e.printStackTrace();
result = null;
}
return result;
}
public static ArrayList<PatientAssignDataBean> getAllAssignedPatientsAndUsers(){
ArrayList<PatientAssignDataBean> result = new ArrayList<>();
try ( Connection con = JdbcUtil.getConnection()) {
String sql= "SELECT pa.uid,pa.patientid "
+ "from patientsassigns pa";
try (Statement st = con.createStatement()) {
System.out.println(sql);
ResultSet rs = st.executeQuery(sql);
while (rs.next()){
result.add(new PatientAssignDataBean(rs.getString(1),rs. getInt(2)));
}
} catch (Exception e) {
log.error("Statement in patientassign search error", e);
e.printStackTrace();
result = null;
}
}
catch (Exception e) {
log.error("patientassign search error", e);
e.printStackTrace();
result = null;
}
return result;
}
public static int getNameById(int pid){
PatientDataBean result = new PatientDataBean();
try ( Connection con = JdbcUtil.getConnection()) {
String sql= "select patientid from patient where patientid = " + pid;
try (Statement st = con.createStatement()) {
System.out.println(sql);
ResultSet rs = st.executeQuery(sql);
while (rs.next()){
result = new PatientDataBean(rs.getInt(1));
}
} catch (Exception e) {
log.error("Statement in users search error", e);
e.printStackTrace();
result = null;
}
}
catch (Exception e) {
log.error("patients search error", e);
e.printStackTrace();
result = null;
}
return result.getPatientId();
}
/*New CRUD OPERATIONS START FOR USERS - SM*/
//Join to patient assigns to get BHCO info to check if the BHCO is admin in order to delete
public void deletePat(int pat) {
try {
PreparedStatement preparedStatement = connection1
.prepareStatement("delete from patients p where patientid=?");
// Parameters start with 1
preparedStatement.setInt(1, pat);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
//Join to patient assigns to get BHCO info to check if the BHCO is admin in order to update
public void updatePat(Patient pat) {
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd");
String dob = sdf.format(pat.getDob());
try {
PreparedStatement preparedStatement = connection1
.prepareStatement("update patients p set med_no=?, family_id=?,block_id=?,community_id=?,email=?, "
+"patient_first_name=?,patient_mid_name=?, patient_last_name=?,patient_phone_number=?, "
+"gender=?,dob=?,race=?,maritalstatus=?,streetnumber=?,aptno=?,city=?,state=?,zip=?, "
+"latitude=?,longitude=?,update_date=? "
+"where patientid=?");
// Parameters start with 1
preparedStatement.setInt(1, pat.getMed_no());
preparedStatement.setInt(2, pat.getFamily_id());
preparedStatement.setInt(3, pat.getBlock_id());
preparedStatement.setInt(4, pat.getCommunity_id());
preparedStatement.setString(5, pat.getEmail());
preparedStatement.setString(6, pat.getPfname());
preparedStatement.setString(7, pat.getPmname());
preparedStatement.setString(8, pat.getPlname());
preparedStatement.setString(9, pat.getPhone());
preparedStatement.setString(10, pat.getGender());
//preparedStatement.setDate(11, new java.sql.Date(pat.getDob().getTime()));
preparedStatement.setString(11, dob);
preparedStatement.setString(12, pat.getRace());
preparedStatement.setString(13, pat.getMaritalstatus());
preparedStatement.setString(14, pat.getStreetnum());
preparedStatement.setString(15, pat.getAptno());
preparedStatement.setString(16, pat.getCity());
preparedStatement.setString(17, pat.getState());
preparedStatement.setInt(18, pat.getZip());
preparedStatement.setDouble(19, pat.getLatitude());
preparedStatement.setDouble(20, pat.getLongitude());
preparedStatement.setTimestamp(21,getCurrentTimeStamp());
preparedStatement.setInt(22, pat.getPatid());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Patient> getAllPat() {
List<Patient> pats = new ArrayList<Patient>();
try {
Statement statement = connection1.createStatement();
ResultSet rs = statement.executeQuery("select patientid,patient_first_name,patient_last_name,dob,email,update_date from patients");
while (rs.next()) {
Patient pat = new Patient();
pat.setPatid(rs.getInt("patientid"));
pat.setPfname(rs.getString("patient_first_name"));
pat.setPlname(rs.getString("patient_last_name"));
pat.setDob(rs.getDate("dob"));
pat.setEmail(rs.getString("email"));
pat.setUpdatedate(rs.getString("update_date"));
pats.add(pat);
}
} catch (SQLException e) {
e.printStackTrace();
}
return pats;
}
public Patient getPatById(int patid) {
Patient pat = new Patient();
try {
PreparedStatement preparedStatement = connection1.
prepareStatement("select patientid,patient_first_name,patient_last_name,dob,email from patients where patientid=?");
preparedStatement.setInt(1, patid);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
pat.setPatid(rs.getInt("patientid"));
pat.setPfname(rs.getString("patient_first_name"));
pat.setPlname(rs.getString("patient_last_name"));
pat.setDob(rs.getDate("dob"));
pat.setEmail(rs.getString("email"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return pat;
}
}
Я ожидаю, что я могу получить всех пациентов из базы данных, используя DAO, а затем, когда я нажимаю кнопку "Обновить пациента", он переходит к "lu.jsp"и в «lu.jsp» вы можете увидеть «listPatient.jsp», а затем распечатать информацию о каждом пациенте.Однако это не работает.А затем я набрал «lu.jsp» в своем браузере, он также показывает ту же «500 внутренняя ошибка».Затем я набрал "listPatient.jsp" в браузере, он не показывает ошибки, но на веб-странице нет информации о пациенте.Поэтому я думаю, что я не правильно оцениваю информацию о пациенте?что случилось?спасибо!