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
Related
I'm trying to create database connection using Listener and get the connection to Servlet and do some database Query and show output on the browser but output not come to brower.it don't show error just blank page.is my code Wrong(my english pretty bad sorry)
this is Listener
public class Mylistener implements ServletContextListener {
public Mylistener() {
}
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("closed");
ServletContext context = sce.getServletContext();
Connection connection = (Connection) context.getAttribute("conn");
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void contextInitialized(ServletContextEvent sce) {
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","system","manager");
ServletContext context = sce.getServletContext();
context.setAttribute("conn", connection);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
//this is Servlet
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response .getWriter();
String tname = request.getParameter("tname");
ServletContext context = request.getServletContext();
Connection connection=(Connection) context.getAttribute("conn");
try
{
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery("select * from " + tname);//tname pass by html form
while(set.next())
{
writer.println(set.getInt(1)+"...."+set.getString(2)+"...."+set.getDouble(3));
//System.out.println(set.getInt(1)+"...."+set.getString(2)+"...."+set.getDouble(3));
writer.println("<br><br>");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
Pool doesn't in servlet but works in standalone appication.
Pool class is common in two cases:
public class Pool {
private static DataSource ds;
static {
DriverAdapterCPDS cpds = new DriverAdapterCPDS();
try {
cpds.setDriver("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
cpds.setUrl("jdbc:mysql://localhost:3306/collage");
cpds.setUser("root");
cpds.setPassword("r00t");
SharedPoolDataSource tds = new SharedPoolDataSource();
tds.setConnectionPoolDataSource(cpds);
tds.setMaxTotal(10);
/*tds.setMaxWait(50);
tds.setMaxTotal();*/
tds.setMaxTotal(50);
ds = tds;
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
for standalone class it works as following
public class MainClass {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = Pool.getConnection();
// Do work with connection
statement = connection.createStatement();
String selectEmployeesSQL = "select * from students";
resultSet = statement.executeQuery(selectEmployeesSQL);
while (resultSet.next()) {
printTestTable(resultSet);
}
} catch (Exception e) {
e.printStackTrace();
} finnaly {
...
}
}
And from part from servlet is following:
#WebServlet("/Demo.do")
public class DemoController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ResultSet rsObj = null;
Connection connObj = null;
PreparedStatement pstmtObj = null;
try {
connObj = Pool.getConnection();
...
And exception is here"
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Servlet execution threw an exception
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.NoClassDefFoundError: Could not initialize class am.ak.dao.jdbc.connections.Pool
test.DemoController.doGet(DemoController.java:27)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
Thanks.
ADDED:
Artifacts in Project settings:
RESOLVED:
So this two lib were missed )
Interesting:
In POM I added only one dependency bot it shoes two :
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.5.0</version>
</dependency>
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.
Getting frustrated with DBUnit :( Anyone know why I would get dbAssertionFailedError driverClass is null for the below please? dbunitData.xml contains the test data with one row. I know that the connection to the database is fine but the error seems to be triggered by the assertequals.
public class ExtendDBTestCaseTest extends DBTestCase
{
public static final String TABLE_LOGIN = "salarydetails";
private FlatXmlDataSet loadedDataSet;
private SalaryCalculation salaryCalculation;
#SuppressWarnings("deprecation")
protected IDataSet getDataSet() throws Exception
{
loadedDataSet = new FlatXmlDataSet(this.getClass().getClassLoader()
.getResourceAsStream("dbunitData.xml"));
return loadedDataSet;
}
protected void setUp() throws Exception
{
setUpDatabase();
}
#SuppressWarnings("deprecation")
private void setUpDatabase() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection jdbcConnection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/salary", "someUser", "somePass");
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
IDataSet dataSet = getDataSet();
try
{
getSetUpOperation().execute(connection, dataSet);
}
finally
{
connection.close();
}
}
protected DatabaseOperation getSetUpOperation() throws Exception{
return DatabaseOperation.REFRESH;
}
public void testCalculatorNeg() throws Exception
{
salaryCalculation = new SalaryCalculation();
int salary = salaryCalculation.calculator("12345");
assertEquals(0, salary);
}
}
Frustratingly I answered my own question after more trial and error. Just needed to add a teardown method with loadedDataSet.endDataSet(); and now works fine!
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.