I'm studing javaee and Im executing the project in ubuntu server with tomcat and postgres.
When I try to execute the servlet , I have this error:
java.lang.ClassNotFoundException: javax.persistence.EntityTransaction
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1718)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569)
ejemploLoginMVC.Modelo.Conexion.crearla(Conexion.java:50)
ejemploLoginMVC.Controller.nuevoUsuario.doPost(nuevoUsuario.java:47)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
usuario.java
#Entity
public class Usuario {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id_Usuario;
#Column(nullable=false)
private String nick;
#Column(nullable=false)
private String password;
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Conexion.java
public class Conexion {
private static EntityManagerFactory emf;
private static EntityManager em;
private static EntityTransaction tx;
String nick;
String pass;
public Conexion(String nick,String pass){
this.nick=nick;
this.pass=pass;
}
#BeforeClass
public static void initEntityManager() throws Exception {
emf = Persistence.createEntityManagerFactory("usuarios-unit");
em = emf.createEntityManager();
}
#AfterClass
public static void closeEntityManager() throws SQLException {
if (em != null) em.close();
if (emf != null) emf.close();
}
#Before
public void initTransaction() {
tx = em.getTransaction();
}
public void crearla() throws Exception{
Usuario usuario=new Usuario();
usuario.setNick(nick);
usuario.setPassword(pass);
tx.begin();
em.persist(usuario);
tx.commit();
em.close();
emf.close();
}
}
nuevoUsuario.java (servlet)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
String nick = request.getParameter("nick");
String pass = request.getParameter("pass");
Conexion conexion= new Conexion(nick,pass);
try {
conexion.crearla();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try(PrintWriter out =response.getWriter()){
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("<p>USUARIO:"+nick+"</p>");
out.println("<p>PASSWORD:"+pass+"</p>");
out.println("</body>");
out.println("</html>");
}
I cant find the error, i added to the project: postgresql-jdbc4.jar , javaee-api-6.0 , tomcat jars , tomee jars ,etc
Thanks :D
To summarize the comments to the question:
The ClassNotFoundException is thrown because the JPA related classes cannot be found. Tomcat does not come with JPA support out of the box. Either use TomEE, or add the JPA related (and probably further) JARs to the tomcat's lib folder (/usr/share/tomcat7/lib in your case), or add them to the web applications lib folder when deploying the WAR file.
Remember that if you add the JARs to tomcat's lib folder, they will be shared by all applications that you deploy.
For an overview of how web/enterprise applications are made up, see http://docs.oracle.com/javaee/7/tutorial/packaging.htm for example.
You have to add Hibernate or other JPA implementation to classPath or... use Spring.
Related
This question already has answers here:
How should I connect to JDBC database / datasource in a servlet based application?
(2 answers)
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed last month.
today i have a problem with servlet in java and mySql, btw i'm using eclipse to write this code. The problem is that when i use the servlet to call my DAO class in tomcat, my connection to the database fails, but when i use a normal class to make a try with java compiler, the connection is good, this error is only when i use Tomcat.
this is my Servlet controller (in this the connection fails and i run this with tomcat)
public class ProductController extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ProductDAO productDAO = new ProductDAO();
RequestDispatcher dispatcher = null;
String accion = request.getParameter("accion");
if(accion == null || accion.isEmpty()) {
dispatcher = request.getRequestDispatcher("products/index.jsp");
List<Product> list = productDAO.getList();
request.setAttribute("list", list);
}
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
This is my DAO class
public class ProductDAO {
public ProductDAO() {
}
public List<Product> getList() {
Connection_ jdbc = new Connection();
PreparedStatement ps;
ResultSet rs;
List<Product> list = new ArrayList<>();
try {
ps = jdbc.getConecction().prepareStatement("SELECT * FROM products");;
rs = ps.executeQuery();
while(rs.next()) {
list.add(new Product(rs.getInt("id"), rs.getInt("stock"), rs.getDouble("price"), rs.getString("name"), rs.getString("code")));
}
return list;
}catch (Exception e) {
System.out.println("Fallo en la conexion");
return null;
}
}
}
This is the error message
enter image description here
This is my Try controller
public class Controller{
public static void main(String[] args) {
Connection_ jdbc = new Connection();
Statement statement;
ResultSet rows;
try {
statement = jdbc.getConecction().createStatement();
rows = statement.executeQuery("SELECT * FROM products");
System.out.println("Registers");
while(rows.next()) {
System.out.println("Id "+rows.getInt("stock"));
}
} catch (Exception e) {
System.out.println("Fallo en la conexion");
}
}
And this is when i use the try controller
enter image description here
like i said before, in this try i am using java compiler of eclipse and i don't have the problem but, when i use tomcat again in this controller my system failes, i dont know how can i resolve it
https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-tomcat.html
You should look at this page to install mysql driver properly in Tomcat
I have created an application which reads & writes into a remote file. I have different files (A.properties, B.properties, C.properties) in different directories (folder-1, folder-2, folder-3). Each directory has the same filename with different data.
I have implemented concurrency in my application by using the LockRegistry provided by this other answer. The issue is that if a thread is accessing A.properties while another thread accesses B.properties, the propertyMap displayed to the end user will contain both data from property files. How can I resolve this issue?
My code:
public class UDEManager
{
private Map<String, String> propertyMap = new TreeMap<>();
HttpSession session = null;
public UDEPropertyManager()
{
super();
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Code for calling thread for read/write operations into remote
// file and fill the propertyMap
}
}
class WebAppProperty implements Runnable
{
private WebApp webapp; // folder-1
private String propertyFile; // A.properties
private String keyValue; //messages-title=Messages
private LockType mode;
public String getPropertyFile()
{
return propertyFile;
}
public void setPropertyFile(String propertyFile)
{
this.propertyFile = propertyFile;
}
#Override
public void run()
{
try {
LockRegistry.INSTANCE.acquire(propertyFile, mode);
if (this.mode == LockType.WRITE) {
writeToPropertyFile();
} else if (this.mode == LockType.READ) {
getProperty(this.webapp, this.propertyFile);
}
} catch (Exception ie) {
sysoutAndLog("Thread is Interrupted");
ie.printStackTrace();
} finally {
LockRegistry.INSTANCE.release(propertyFile, mode);
}
}
private boolean getProperty(WebApp webapp, String property)
{
try {
// read from file and put it into Map instance variable
// of calling class (UDEManager)
propertyMap.put(key, value);
} catch(Exception e) {
sysoutAndLog("Error while reading property ");
e.printStackTrace();
}
return false;
}
private void writeToPropertyFile()
{
try {
// Write data into remote file
} catch (Exception e) {
sysoutAndLog("exception while writing to file.");
e.printStackTrace();
}
}
}
You should associate the properties map with the user session or request
I have developed a project using Hibernate. I am trying to test it using Junit with H2 in memory db but the test case is creating fields in the db that I am using it for development.
Here is my code :
UserDAO.java
public interface UserDAO {
public void addUser(String username, String password);
public List<String> getUsers();
}
UserDAOImpl.java
public class UserDAOImpl implements UserDAO {
public static final Logger LOG = LoggerFactory.getLogger(UserDAOImpl.class);
private static Session session;
private static void beginSession() {
session = DbUtils.getSessionFactory().openSession();
session.beginTransaction();
}
#Override
public void addUser(String username, String password) {
String encryptedPassword = Utils.encrypt(password);
User user = new User(username, encryptedPassword);
beginSession();
try {
session.save(user);
System.out.println(user.getPassword());
session.getTransaction().commit();
} catch (SQLGrammarException e) {
session.getTransaction().rollback();
LOG.error("Cannot save user", e);
} finally {
session.close();
}
}
#Override
public List<String> getUsers() {
beginSession();
List<String> results = new ArrayList<String>();
String hql = "select username from User";
Query query = null;
try {
query = session.createQuery(hql);
results = query.list();
} catch (HibernateException e) {
LOG.error("Cannot execute query", e);
}
return results;
}
}
Files for test cases
SessionFactoryRule.java
public class SessionFactoryRule implements MethodRule {
private SessionFactory sessionFactory;
private Transaction transaction;
private Session session;
#Override
public Statement apply(final Statement statement, FrameworkMethod method, Object test) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
sessionFactory = createSessionFactory();
createSession();
beginTransaction();
try {
statement.evaluate();
} finally {
shutdown();
}
}
};
}
private void shutdown() {
try {
try {
try {
transaction.rollback();
} catch (Exception ex) {
ex.printStackTrace();
}
session.close();
} catch (Exception ex) {
ex.printStackTrace();
}
sessionFactory.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private SessionFactory createSessionFactory() {
Configuration configuration = new Configuration().configure();
configuration.addAnnotatedClass(User.class)
.addAnnotatedClass(Message.class);
configuration.setProperty("hibernate.dialect",
"org.hibernate.dialect.H2Dialect");
configuration.setProperty("hibernate.connection.driver_class",
"org.h2.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:h2:./data/db");
configuration.setProperty("hibernate.hbm2ddl.auto", "create");
SessionFactory sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
public Session createSession() {
session = sessionFactory.openSession();
return session;
}
public void commit() {
transaction.commit();
}
public void beginTransaction() {
transaction = session.beginTransaction();
}
public Session getSession() {
return session;
}`
Here is my test case
UserDAOTest.java
public class UserDAOTest {
#Rule
public final SessionFactoryRule sf = new SessionFactoryRule();
#Test
public void testAddUser() {
Session session = sf.getSession();
UserDAOImpl userDAOImpl = new UserDAOImpl();
String username = "stackoverflow";
String password = "testing";
userDAOImpl.addUser(username, password);
}
}
This test case is updating the fields username and password in the db that I am using while development. How can I stop it and use h2 in-memory db for testing.
You have session = DbUtils.getSessionFactory().openSession() in the UserDAOImpl. This is the reason of using a development database. Your SessionFactoryRule is not used at all.
So what you can to do.
The best choice is use to Spring for Hibernate configuration and unit testing.
Other option is to set sessionFactory to the UserDAOImpl using constructor.
Also, using static here is a really very very bad idea
private static Session session;
I am calling a Servlet using its URL address. This is the URL I am typing
http://localhost:7001/ryan/olympics?action=selectCatalog&id=1
This is the Servlet's URL for sure; if I change the address I get
page not found
This is the code for the Servlet.
public class Servlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;
public Servlet() {
super();
}
public void init(ServletConfig config) throws ServletException {
System.out.println("*** initializing controller servlet.");
super.init(config);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equals("selectCatalog")) {
String categoryId = request.getParameter("id");
ProductModelDAO dao4 = new ProductModelDAOImpl("jpac");
if (categoryId != null && !categoryId.trim().equals("")) {
CategoryDAO dao1 = new CategoryDAOImpl("jpac");
try {
Category category = dao1.getCategoryName(categoryId);
request.setAttribute("category", category);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
#SuppressWarnings("unchecked")
List<Product> products = dao4
.getProductsByCategory(categoryId);
request.setAttribute("products", products);
} catch (Exception e) {
e.printStackTrace();
}
url = "SelectCatalog.jsp";
RequestDispatcher requestDispatcher =
getServletContext().getRequestDispatcher(url);
requestDispatcher.forward(request, response);
I get the NullPointerException pointing to the RequestDispatcher's line. Any help?
Try changing "SelectCatalog.jsp" to "/SelectCatalog.jsp", because, as I understand, You want to use an absolute path.
If you want to use a relative path you have to use:
request.getRequestDispatcher(url);
in place of:
getServletContext().getRequestDispatcher(url);
request.getParameter("action");
code is written in doPost method. Are you invoking this servlet from doPost method of calling servlet? URL parameters will not be used by doPost method.
I am working on a simple EJB module using sample code. I am trying to implement CURD operations through a SOAP web service. I have a persistence unit defined in persistence.xml.
Here is the code for my implementation. The problem is that I cannot create an instance of PersistenceService because the persistence unit name is not present in the JNDI listings.
If, instead of using code injection, I use
EntityManagerFactory emf = Persistence.createEntityManagerFactory(PU_NAME);
em = emf.createEntityManager();
the code runs, but then the transaction is managed by the container. I was reading through some tutorials and they mentioned that, in this scenario, if the user wants to roll the transaction back later, he cannot do so.
What can I do instead?
users class
#WebService()
#Stateless()
public class users {
public users()
{
}
/**
* Web service operation
*/
#WebMethod(operationName = "addUser")
public Integer addUser(
#WebParam(name = "UserName") final String UserName,
#WebParam(name = "LastName") final String LastName) {
DatabaseEntityManager dem = new DatabaseEntityManager();
Integer result = null;
try
{
result = dem.addUser(UserName, LastName, false);
dem.commitTx();
return result;
} catch(Exception E)
{
}
return new Integer(-1);
}
DatabaseEntityManager class
public class DatabaseEntityManager {
PersistenceService ps_bck = null;
public DatabaseEntityManager()
{
}
public SiteUsers addUser(
String Username,
String LastName, boolean commit) throws Exception
{
AppUser appUser = new appUser(UserName, LastName);
//AppUser is an entity class
PersistenceService ps = PersistenceService.getInstance();
try
{
ps.beginTx();
EntityManager em = ps.getEntityManager();
em.persist(appUser);
if (commit)
ps.commitTx();
else
ps_bck = ps;
}
catch (Exception E)
{
ps.rollbackTx();
}
finally
{
ps.close();
}
return appUser.getId();
}
void commitTx() throws Exception
{
try
{
ps_bck.commitTx();
}
catch(Exception E)
{
throw E;
}
finally
{
ps_bck =null;
}
}
}
PersistenceService class — borrowed from sample code generated by NetBeans
public class PersistenceService {
private static String DEFAULT_PU = "pers-ejbPU";
private static ThreadLocal<PersistenceService> instance = new ThreadLocal<PersistenceService>() {
#Override
protected PersistenceService initialValue() {
return new PersistenceService();
}
};
private EntityManager em;
private UserTransaction utx;
private PersistenceService() {
try {
//This code runs
// EntityManagerFactory emf = ersistence.createEntityManagerFactory(DEFAULT_PU);
// em = emf.createEntityManager();
//This code throws an exception
this.em = (EntityManager) new InitialContext().lookup("java:comp/env/persistence/"+ DEFAULT_PU);
this.utx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
} catch (NamingException ex) {
throw new RuntimeException(ex);
}
}
/**
* Returns an instance of PersistenceService.
*
* #return an instance of PersistenceService
*/
public static PersistenceService getInstance() {
return instance.get();
}
private static void removeInstance() {
instance.remove();
}
/**
* Returns an instance of EntityManager.
*
* #return an instance of EntityManager
*/
public EntityManager getEntityManager() {
return em;
}
/**
* Begins a resource transaction.
*/
public void beginTx() {
try {
utx.begin();
em.joinTransaction();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Commits a resource transaction.
*/
public void commitTx() {
try {
utx.commit();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Rolls back a resource transaction.
*/
public void rollbackTx() {
try {
utx.rollback();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Closes this instance.
*/
public void close() {
removeInstance();
}
}
If your persistence.xml has an entry
<persistence-unit name="PU_NAME" transaction-type="JTA">
In your PersistenceService class, add the annotation:
#PersistenceContext (name = "PU_NAME") private EntityManager em;