gpt4 book ai didi

java - 在 Tomcat 中设置属性时出现 NullPointerException

转载 作者:行者123 更新时间:2023-11-29 00:01:26 26 4
gpt4 key购买 nike

您好,我需要 Java EE 方面的帮助。我最近使用 Maven 和 Glassfish 在 Netbeans 上用 Java EE 构建了一个项目,一切正常。我们被要求让它在 Tomcat 和 TomEE 下运行,但我不明白为什么我会从 Tomcat 收到此错误。

我从 NullPointerException when setting attribute? 看到了类似的问题

22-Nov-2019 13:33:13.388 SEVERE [http-nio-8080-exec-11] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [JEEServlet] in context with path [/jee-efrei_v3] threw exception
java.lang.NullPointerException
at com.controller.JEEServlet.listEmployes(JEEServlet.java:88)
at com.controller.JEEServlet.logIn(JEEServlet.java:254)
at com.controller.JEEServlet.doPost(JEEServlet.java:214)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:810)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

我试着搜索了一下,一些建议是添加:

  1. context.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->

<Context>
<Resource
name="jdbc/jeeprj" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
url="jdbc:mysql://localhost:3306/jeeprj?zeroDateTimeBehavior=convertToNull"
driverClassName="com.mysql.jdbc.Driver"
username="jee" password="jeeprj"
/>
</Context>

  1. 将 mysql 连接添加到 Tomcat 的库中
  2. 通过添加 resource-env-ref 编辑我的 web.xml

这是我的web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>/WEB-INF/login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>JEEServlet</servlet-name>
<servlet-class>com.controller.JEEServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JEEServlet</servlet-name>
<url-pattern>/JEEServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<resource-env-ref>
<resource-env-ref-name>jdbc/jeeprj</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
</web-app>

这是我的persistence.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="com.jvprj_jee-efrei_maven_war_1.0-SNAPSHOTPU" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProvider</provider>
<jta-data-source>jdbc/jeeprj</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>

这里是tomcat在控制台指出的各个区域:

/*
* 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.controller;

import com.dao.EmployeDAOLocal;
import com.model.Jeeprj;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
*
* @author EKEUMOU
*/
@WebServlet(name = "JEEServlet", urlPatterns = {"/JEEServlet"})
public class JEEServlet extends HttpServlet {

@EJB
private EmployeDAOLocal employeDao;

boolean selected = true;

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

try {

String theCommand = request.getParameter("action");

if (theCommand == null){
theCommand = "LIST";
}

switch(theCommand){
case "LIST":
case "Voir Liste":
listEmployes(request, response);
break;
case "Ajouter":
showFormAddEmploye(request, response);
break;
case "Modifier":
showFormModifyEmploye(request, response);
break;
case "Valider":
updateEmploye(request, response);
break;
case "Logout":
logOut(request, response);
break;
case "Supprimer":
deleteEmploye(request, response);
break;
case "Details":
loadEmploye(request,response);
break;
case "UPDATE_EMPLOYE":
updateEmploye(request,response);
break;
default:
listEmployes(request, response);
}

}
catch (IOException | ServletException exc) {
throw new ServletException(exc);
}
}

private void listEmployes(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
String userName = (String) session.getAttribute("userName");
if (userName.equals("empl"))
listEmployesEmpl(request, response);
else {
request.setAttribute("allEmployes", employeDao.getAllEmployes());
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/list-employe.jsp");
dispatcher.forward(request, response);
}
}

private void listEmployesEmpl(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("allEmployes", employeDao.getAllEmployes());
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("WEB-INF/list-employe_empl.jsp");
dispatcher.forward(request, response);
}

private void showFormAddEmploye(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/add-employe-form.jsp");
dispatcher.forward(request, response);
}

private void addEmploye(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String nom = request.getParameter("nom");
String prenom = request.getParameter("prenom");
String telDom = request.getParameter("telDom");
String telPor = request.getParameter("telPor");
String telPro = request.getParameter("telPro");
String adresse = request.getParameter("adresse");
String codePostal = request.getParameter("codePostal");
String ville = request.getParameter("ville");
String email = request.getParameter("email");

Jeeprj theEmploye = new Jeeprj(nom, prenom, telDom, telPor, telPro, adresse, codePostal, ville, email);
employeDao.addEmploye(theEmploye);

listEmployes(request, response);
}

private void deleteEmploye(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String theEmployeStrId = request.getParameter("selectedEmploye");
int theEmployeId = 0;

//if(theEmployeStrId!=null && !theEmployeStrId.equals("")){
try{
theEmployeId=Integer.parseInt(theEmployeStrId);
request.getSession().setAttribute("result", true);
employeDao.deleteEmploye(theEmployeId);
}catch (NumberFormatException ex) {
request.getSession().setAttribute("result", false);
}

listEmployes(request, response);

}

private void loadEmploye(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

HttpSession session = request.getSession(true);
String theEmployeStrId = request.getParameter("selectedEmploye");
int theEmployeId = 0;
String userName = (String) session.getAttribute("userName");

if(theEmployeStrId != null && !theEmployeStrId.equals("")){
theEmployeId=Integer.parseInt(theEmployeStrId);


Jeeprj theEmploye = employeDao.getEmploye(theEmployeId);
session.setAttribute("THE_EMPLOYE", theEmploye);

if (userName.equals("admin")) {
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/details-employe-form.jsp");
dispatcher.forward(request, response);
}
else {
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/details-employe-form_empl.jsp");
dispatcher.forward(request, response);
}

}else{
if (userName.equals("admin"))
listEmployes(request, response);
else
listEmployesEmpl(request, response);
}


}

private void updateEmploye(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

int employeId = Integer.parseInt(request.getParameter("employeId"));
String nom = request.getParameter("nom");
String prenom = request.getParameter("prenom");
String telDom = request.getParameter("telDom");
String telPor = request.getParameter("telPor");
String telPro = request.getParameter("telPro");
String adresse = request.getParameter("adresse");
String codePostal = request.getParameter("codePostal");
String ville = request.getParameter("ville");
String email = request.getParameter("email");

Jeeprj theEmploye = new Jeeprj(employeId, nom, prenom, telDom, telPor, telPro, adresse, codePostal, ville, email);
employeDao.editEmploye(theEmploye);

listEmployes(request, response);
}

private void showFormModifyEmploye(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*HttpSession session = request.getSession(true);
Jeeprj ub = (Jeeprj) session.getAttribute("THE_EMPLOYE");
session.setAttribute("THE_EMPLOYE", ub);*/
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/modify-employe-form.jsp");
dispatcher.forward(request, response);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

try {

String theCommand = req.getParameter("action");

if (theCommand == null){
theCommand = "Login";
}

switch(theCommand){
case "Login":
logIn(req, resp);
break;
default:
logIn(req, resp);
}

}
catch (IOException | ServletException exc) {
throw new ServletException(exc);
}
}



protected void logIn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

String userName = req.getParameter("username");
String password = req.getParameter("password");
if (userName != null && userName.trim().length() > 0 &&
password != null && password.trim().length() > 0) {
System.out.println(userName + " : " + password);
if (userName != null && userName.length() != 0 && (userName.equals("admin") || userName.equals("empl")) &&
password != null && password.length() != 0 && (password.equals("admin") || password.equals("empl"))) {
if (req.getParameter("remember") != null) {
String remember = req.getParameter("remember");
System.out.println("remember : " + remember);
Cookie cookUserName = new Cookie("cookUserName", userName.trim());
Cookie cookPassword = new Cookie("cookPassword", password.trim());
Cookie cookRemember = new Cookie("cookRemember", remember.trim());
cookUserName.setMaxAge(60*60*24*3); // 3days
cookPassword.setMaxAge(60*60*24*3);
cookRemember.setMaxAge(60*60*24*3);
resp.addCookie(cookUserName);
resp.addCookie(cookPassword);
resp.addCookie(cookRemember);
}
HttpSession httpSession = req.getSession();
httpSession.setAttribute("sessionUser", userName.trim());
httpSession.setAttribute("userName", userName);
if (userName.equals("admin"))
listEmployes(req, resp);
else
listEmployesEmpl(req, resp);

} else {
System.out.println("Erreur d'Authentification");
req.setAttribute("message", "Erreur d'Authentification");
RequestDispatcher requestDispatcher = req.getRequestDispatcher("WEB-INF/login.jsp");
requestDispatcher.forward(req, resp);
}
} else {
System.out.println("Nom d'Utilisateur et Mot de Passe Requis !");
req.setAttribute("message", "Nom d'Utilisateur et Mot de Passe Requis !");
RequestDispatcher requestDispatcher = req.getRequestDispatcher("WEB-INF/login.jsp");
requestDispatcher.forward(req, resp);
}
}

private void logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Cookie cookUserName = new Cookie("cookUserName", null);
Cookie cookPassword = new Cookie("cookPassword", null);
Cookie cookRemember = new Cookie("cookRemember", null);
cookUserName.setMaxAge(0);
cookPassword.setMaxAge(0);
cookRemember.setMaxAge(0);
response.addCookie(cookUserName);
response.addCookie(cookPassword);
response.addCookie(cookRemember);

HttpSession httpSession = request.getSession();
httpSession.invalidate();
request.setAttribute("message", "Deconnexion réussie !");
RequestDispatcher requestDispatcher = request.getRequestDispatcher("WEB-INF/login.jsp");
requestDispatcher.forward(request, response);
}



}


提前感谢您的各种回答。

最佳答案

这里创建 employedAo bean 似乎有问题:

@EJB
private EmployeDAOLocal employeDao;

由于某种原因,它的实例没有被创建。检查该类是否所有不可替代的注解等。

关于java - 在 Tomcat 中设置属性时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58997183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com