我试图通过一个简单的jsp表单来持久保存实体,但它不起作用.出现的异常是:
javax.naming.NamingException:’java:global / jee-projet-web’的查找失败.
我正在使用glasfish作为服务器.
这是我的表格代码:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add admin</title>
</head>
<body>
<p id="info">
${info}
</p>
<form action="/jee-projet-web/AddAdmin" method="post">
<fieldset>
<label>Nom:</label>
<input type="text" name="lastName" value="Entrez votre nom">
<label>Prenom</label>
<input type="text" name="name" value="Entrez votre prnom">
</fieldset>
<button type="submit">Ajouter</button>
</form>
</body>
</html>
我的servlet AddAdmin:
package servlet.add;
import java.io.IOException;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
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 model.Admin;
import model.databaseManager.AdminManager;
import model.databaseManager.Database;
@WebServlet(urlPatterns = {"/AdminAdd"})
@SuppressWarnings("serial")
public class AddAdmin extends HttpServlet{
private AdminManager adminManager;
@Override
public void init() {
Context context;
try {
context = new InitialContext();
AdminManager adminManager = (AdminManager)context.lookup("java:global/jee-projet-web");
} catch (NamingException e) {
Logger.getLogger(this.getClass().getName()).warning("Erreur de contexte : Dans le nom");
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=iso-8859-15");
String lName = request.getParameter("lastName");
String name = request.getParameter("name");
if(lName.equals("") || name.equals("")) {
request.setAttribute("info", "Erreur: Un champ n'a pas été rempli");
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/jsp/add/add.jsp");
dispatcher.include(request, response);return;
}
Admin a = new Admin(lName, name);
adminManager.addAdmin(a);
request.setAttribute("info", "Admin ajouté");
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/jsp/add/add.jsp");
dispatcher.include(request, response);return;
}
}
我的实体bean Admin.java:
package model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the admin database table.
*
*/
@SuppressWarnings("serial")
@Entity
@Table(name="admin")
public class Admin implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String lastName;
private String firstName;
public Admin() {
}
public Admin(String lName, String fName) {
this.firstName = fName;
this.lastName = lName;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String name) {
this.firstName = name;
}
}
我的managedBean:AdminManager
package model.databaseManager;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import model.Admin;
public class AdminManager {
private EntityManager entityManager = null;
private EntityTransaction entityTransaction = null;
@SuppressWarnings("static-access")
public AdminManager(Database database) {
entityManager = database.ENTITY_MANAGER;
entityTransaction = database.ENTITY_TRANSACTION;
}
public void addAdmin(Admin admin) {
entityTransaction.begin();
entityManager.persist(admin);
entityTransaction.commit();
}
public List<Admin> findAll() {
Query query =
entityManager.createQuery("select a from Admin a ");
@SuppressWarnings("unchecked")
List<Admin> liste = (List<Admin>)query.getResultList();
return liste;
}
public Admin findAdmin(int id) {
Query query =
entityManager.createQuery("select a from Admin a where a.id = :id");
query.setParameter("id", id);
return (Admin) query.getSingleResult();
}
public boolean updateAdmin(Admin admin) {
entityTransaction.begin();
Query query =
entityManager.createQuery("select a from Admin a where a.id = :id");
query.setParameter("id", admin.getId());
if(query.getSingleResult()!=null) {
entityManager.merge(admin);
entityTransaction.commit();
return true;
}
else return false;
}
public boolean deleteAdmin(int id) {
entityTransaction.begin();
Admin a = entityManager.find(Admin.class, id);
if (a != null) {
entityManager.remove(a);
entityTransaction.commit();
return true;
}
else return false;
}
}
我的文件web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- Configuration jstl -->
<context-param>
<param-name>javax.servlet.jsp.jstl.sql.dataSource</param-name>
<param-value>jdbc/data</param-value>
</context-param>
<!-- AddAdmin mapping -->
<servlet>
<servlet-name>AddAdmin</servlet-name>
<servlet-class>servlet.add.AddAdmin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddAdmin</servlet-name>
<url-pattern>/AddAdmin</url-pattern>
</servlet-mapping>
</web-app>
我的文件glassfish-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app>
<context-root>/jee-projet-web</context-root>
<class-loader delegate="true"/>
<jsp-config>
<property name="keepgenerated" value="true">
<description>Conserve une copie du code des servlets auto-générées.</description>
</property>
</jsp-config>
</glassfish-web-app>
我的文件persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="jee-projet" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>model.Account</class>
<class>model.Action</class>
<class>model.Admin</class>
<class>model.Client</class>
<class>model.Transaction</class>
<class>model.Wallet</class>
<class>model.Company</class>
<class>model.Bourse</class>
<class>model.Participation</class>
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/jee"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="eclipselink.ddl-generation"
value="drop-and-create-tables"/>
<property name="eclipselink.logging.level"
value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
我确信所有3个最后的文件都放在了正确位置.现在在这里运行我的程序是控制台中的错误:
2013-12-27T14:01:02.847+0100|Grave: javax.naming.NamingException: Lookup failed for 'java:global/jee-projet-web' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: jee-projet-web not found]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at servlet.add.AddAdmin.init(AddAdmin.java:33)
at javax.servlet.GenericServlet.init(GenericServlet.java:244)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1583)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:1212)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:237)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Caused by: javax.naming.NameNotFoundException: jee-projet-web not found
at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:237)
at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:204)
at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:208)
at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:66)
at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:114)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:478)
... 33 more
2013-12-27T14:01:02.872+0100|Avertissement: StandardWrapperValve[AddAdmin]: Servlet.service() for servlet AddAdmin threw exception
java.lang.NullPointerException
at servlet.add.AddAdmin.doPost(AddAdmin.java:55)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
感谢您的帮助.
最佳答案 在您已声明的AddAdmin servlet中
private AdminManager adminManager;
作为实例变量.在init()方法中,您再次使用同名创建问题来声明局部变量
更改
AdminManager adminManager = (AdminManager)context.lookup("java:global/jee-projet-web");
至
adminManager = (AdminManager)context.lookup("java:global/jee-projet-web");
现在,此行将值分配给adminManager
根本原因是
java.lang.NullPointerException
at servlet.add.AddAdmin.doPost(AddAdmin.java:55)
我想第55行是
adminManager.addAdmin(a); //variable adminManager is not initialized
adminManager为null所以,调用null上的任何方法都会抛出NPE
更新
Root exception is javax.naming.NameNotFoundException: jee-projet-web not found
当名称的组件由于未绑定而无法解析时,将抛出This exception.
请确保名称jee-projet-web已经绑定.
我猜这是在jee-projet-web中丢失c的错字错误.它应该是jee-project-web.