I am trying to create a web application using a database and I am getting this error:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Unknown database 'database')
Any ideas?
I can post code if necessary.
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
<Resource auth="Container"
name="jdbc/mysql"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/database"
username="root"
password="********" //I blocked the password
maxIdle="10"
maxActive="200"
maxWait="5"
removeAbandoned="true"
removeAbandonedTimeout="1200"
/>
</Context>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>webApp-01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description>Get Information about Country - jQuery Ajax Request</description>
<display-name>CountryInformation</display-name>
<servlet-name>CountryInformation</servlet-name>
<servlet-class>com.as400samplecode.CountryInformation</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CountryInformation</servlet-name>
<url-pattern>/CountryInformation</url-pattern>
</servlet-mapping>
app.js
$(document).ready(function() {
//Stops the submit request
$("#myAjaxRequestForm").submit(function(e){
e.preventDefault();
});
//checks for the button click event
$("#myButton").click(function(e){
//get the form data and then serialize that
dataString = $("#myAjaxRequestForm").serialize();
//get the form data using another method
var countryCode = $("input#countryCode").val();
dataString = "countryCode=" + countryCode;
//make the AJAX request, dataType is set to json
//meaning we are expecting JSON data in response from the server
$.ajax({
type: "POST",
url: "CountryInformation",
data: dataString,
dataType: "json",
//if received a response from the server
success: function( data, textStatus, jqXHR) {
//our country code was correct so we have some information to display
if(data.success){
$("#ajaxResponse").html("");
$("#ajaxResponse").append("<b>Country Code:</b> " + data.countryInfo.code + "");
$("#ajaxResponse").append("<b>Country Name:</b> " + data.countryInfo.name + "");
$("#ajaxResponse").append("<b>Continent:</b> " + data.countryInfo.continent + "");
$("#ajaxResponse").append("<b>Region:</b> " + data.countryInfo.region + "");
$("#ajaxResponse").append("<b>Life Expectancy:</b> " + data.countryInfo.lifeExpectancy + "");
$("#ajaxResponse").append("<b>GNP:</b> " + data.countryInfo.gnp + "");
}
//display error message
else {
$("#ajaxResponse").html("<div><b>Country code in Invalid!</b></div>");
}
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown){
console.log("Something really bad happened " + textStatus);
$("#ajaxResponse").html(jqXHR.responseText);
},
//capture the request before it was sent to server
beforeSend: function(jqXHR, settings){
//adding some Dummy data to the request
settings.data += "&dummyData=whatever";
//disable the button until we get the response
$('#myButton').attr("disabled", true);
},
//this is called after the response or error functions are finsihed
//so that we can take some action
complete: function(jqXHR, textStatus){
//enable the button
$('#myButton').attr("disabled", false);
}
});
});
});
index.html
<html>
<head>
<title>jQuery Ajax POST data Request and Response Example</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<form id="myAjaxRequestForm">
<fieldset>
<legend>jQuery Ajax Form data Submit Request</legend>
<p>
<label for="countryCode">Country Code:</label>
<input id="countryCode" type="text" name="countryCode" />
</p>
<p>
<input id="myButton" type="button" value="Submit" />
</p>
</fieldset>
</form>
<div id="anotherSection">
<fieldset>
<legend>Response from jQuery Ajax Request</legend>
<div id="ajaxResponse"></div>
</fieldset>
</div>
</body>
</html>
country.java
package com.as400samplecode;
public class Country {
String code = null;
String name = null;
String continent = null;
String region = null;
String lifeExpectancy = null;
String gnp = null;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getLifeExpectancy() {
return lifeExpectancy;
}
public void setLifeExpectancy(String lifeExpectancy) {
this.lifeExpectancy = lifeExpectancy;
}
public String getGnp() {
return gnp;
}
public void setGnp(String gnp) {
this.gnp = gnp;
}
}
CountryInformation.java
package com.as400samplecode;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class CountryInformation extends HttpServlet {
private static final long serialVersionUID = 1L;
public CountryInformation() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String countryCode = request.getParameter("countryCode");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "86400");
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
Country countryInfo = getInfo(countryCode);
JsonElement countryObj = gson.toJsonTree(countryInfo);
if(countryInfo.getName() == null){
myObj.addProperty("success", false);
}
else {
myObj.addProperty("success", true);
}
myObj.add("countryInfo", countryObj);
out.println(myObj.toString());
out.close();
}
//Get Country Information
private Country getInfo(String countryCode) {
Country country = new Country();
Connection conn = null;
PreparedStatement stmt = null;
String sql = null;
try {
Context ctx = (Context) new InitialContext().lookup("java:comp/env");
conn = ((DataSource) ctx.lookup("jdbc/mysql")).getConnection();
sql = "Select * from COUNTRY where code = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, countryCode.trim());
ResultSet rs = stmt.executeQuery();
while(rs.next()){
country.setCode(rs.getString("code").trim());
country.setName(rs.getString("name").trim());
country.setContinent(rs.getString("continent").trim());
country.setRegion(rs.getString("region").trim());
country.setLifeExpectancy(rs.getString("lifeExpectancy").trim());
country.setGnp(rs.getString("region").trim());
// country.setLifeExpectancy(rs.getString("lifeExpectancy") == null ? new Double(0) : Double.parseDouble(rs.getString("lifeExpectancy").trim()));
// country.setGnp(rs.getString("gnp") == null ? new Double(0) : Double.parseDouble(rs.getString("gnp").trim()));
}
rs.close();
stmt.close();
stmt = null;
conn.close();
conn = null;
}
catch(Exception e){System.out.println(e);}
finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlex) {
// ignore -- as we can't do anything about it here
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException sqlex) {
// ignore -- as we can't do anything about it here
}
conn = null;
}
}
return country;
}
}
For my case, I just remove: "useSSL=false" from the url (url="jdbc:mysql://localhost:3306/web_student_tracker?useSSL=false") in the context.xml and then it works.
context.xml
user page of student list
Based on the exception you're receiving
Cannot create PoolableConnectionFactory (Unknown database 'database')
... and comparing it to the URL string you're passing in
url="jdbc:mysql://localhost:3306/database"
The database named 'database' doesn't exist.
Related
i am trying to connect to database and write some records but i get this error
can anyone help me to correct it i would really appreciate i am new in java programming
this is my jsp file : NewFile.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="/Add" method="post" enctype="multipart/form-data">
Enter news ID: <br>
<input type="text" name="id"><br><br>
Enter title :<br>
<input type="text" name="title"><br><br>
Choose an image :
<input type="file" name="image" required="required">
<br><br>
<input type="submit" value="add news">
</form>
</body>
</html>
this my Add.java
package com.example.saeid;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
public class Add extends HttpServlet
{
private static final long serialVersionUID = 1L;
private String db_userName = "root";
private String db_Password = "uyhgbv098";
private String db_Name = "my_demo_database";
private String driver = "com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/";
private Connection getConnection()
{
Connection conn = null;
try
{
Class.forName(driver);
conn = DriverManager.getConnection(
url + db_Name,
db_userName,
db_Password);
}
catch (Exception e)
{
throw new RuntimeException("Failed to obtain database connection.", e);
}
return conn;
}
public void doPost( HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String newsId = request.getParameter("id");
int newsID = Integer.parseInt(newsId);
String newsTitle = request.getParameter("title");
String body = "body";
InputStream inputStream = null;
Part part = request.getPart("image");
inputStream = part.getInputStream();
Connection conn = null;
try
{
conn = getConnection();
String query = "INSERT INTO news (id , title , subm_date , text , image ) values (?, ?, NOW() ,? ,?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, newsID);
ps.setString(2,newsTitle );
ps.setString(3, body);
ps.setBlob(4, inputStream);
int row = ps.executeUpdate();
if (row > 0)
{
RequestDispatcher rd = request.getRequestDispatcher("NewFile.jsp");
rd.include(request,response);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
conn.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
}
and web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>12</display-name>
<welcome-file-list>
<welcome-file>NewFile.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>addServlet</servlet-name>
<servlet-class>com.example.saeid.Add</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addServlet</servlet-name>
<url-pattern>NewFile</url-pattern>
</servlet-mapping>
One of the reasons for 404 is The URL was written incorrectly, linked incorrectly.
If you got the 404 response when you accessed the page localhost:8080/NewFile.jsp or on click of Add, Your form action is pointing to /Add but yout url-pattern is NewFile.
Change url-pattern to
/Add
There is a problem with connectors in my project. I have added MySQL connector to Tomcat's lib and also to project's path in IntellijIDEA but problem still exist. Answers from older versions in stackoverlow didnt work in here.
Here are project classes:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_1.xsd"
version="3.1">
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/library</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/context.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/myApp" docBase="myApp"
crossContext="true" reloadable="true" debug="1">
<Resource name="jdbc/library"
global="jbc/library"
auth="Container"
type="javax.sql.DataSource"
initialSize="10"
maxTotal="100"
maxIdle="30"
maxWaitMillis="10000"
username="root"
password="admin"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/library" />
</Context>
error.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Upss</title>
</head>
<body>
<h1>Something is wrong</h1>
Try again
</body>
</html>
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Library Viewer</title>
</head>
<body>
<h1>Biblioteka viewer</h1>
<form action="BookServlet" method="post">
<input placeHolder="ISBN" type="text" name="isbn">
<br>
<input placeHolder="Tytuł" type="text" name="title">
<br>
<input placeHolder="Opis" type="text" name="description">
<br>
Szukaj: <input type="radio" name="option" value="search"> Dodaj: <input type="radio" name="option" value="add">
Modyfikuj: <input type="radio" name="option" value="update"> Usuń: <input type="radio" name="option" value="delete">
<br>
<input type="submit" value="Wyślij">
</form>
</body>
</html>
result.jsp
<%#page import="pl.javastart.model.Book"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<% Book book = (Book)request.getAttribute("book"); %>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Wynik zapytania <%= request.getAttribute("option") %></h1>
<p>W wyniku Twojego zapytania otrzymano następujacy wynik:</p>
<p>Title: <%= book.getTitle() %><br>
ISBN: <%= book.getIsbn() %><br>
Descrition: <%= book.getDescription() %></p>
</body>
</html>
Book.java
package pl.javastart.model;
public class Book {
private String isbn;
private String title;
private String description;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Book(){}
public Book(String isbn, String title, String desc){
this.isbn = isbn;
this.title = title;
description = desc;
}
}
BookServlet.java
package pl.javastart.servlet;
import java.io.IOException;
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 pl.javastart.dao.BookDAO;
import pl.javastart.model.Book;
#WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String isbn = request.getParameter("isbn");
String title = request.getParameter("title");
String description = request.getParameter("description");
String option = request.getParameter("option");
BookDAO dao = new BookDAO();
Book book = null;
String operation = null;
boolean result = false;
if("search".equals(option)) {
book = dao.read(isbn);
result = book!=null? true:false;
operation = "search";
} else if("add".equals(option)) {
book = new Book(isbn, title, description);
result = dao.create(book);
operation = "add";
} else if("update".equals(option)) {
book = new Book(isbn, title, description);
result = dao.update(book);
operation = "update";
} else if("delete".equals(option)) {
book = new Book(isbn, title, description);
result = dao.delete(book);
operation = "delete";
}
if(book != null && result) {
request.setAttribute("option", operation);
request.setAttribute("book", book);
request.getRequestDispatcher("result.jsp").forward(request, response);
} else {
request.getRequestDispatcher("error.jsp").forward(request, response);
}
}
}
BookDAO.java
package pl.javastart.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import pl.javastart.model.Book;
import pl.javastart.util.ConnectionProvider;
public class BookDAO {
private final static String CREATE = "INSERT INTO book(isbn, title, description) VALUES(?, ?, ?);";
private final static String READ = "SELECT isbn, title, description FROM book WHERE isbn = ?;";
private final static String UPDATE = "UPDATE book SET isbn=?, title=?, description=? WHERE isbn = ?;";
private final static String DELETE = "DELETE FROM book WHERE isbn=?;";
public boolean create(Book book) {
Connection conn = null;
PreparedStatement prepStmt = null;
boolean result = false;
try {
conn = ConnectionProvider.getConnection();
prepStmt = conn.prepareStatement(CREATE);
prepStmt.setString(1, book.getIsbn());
prepStmt.setString(2, book.getTitle());
prepStmt.setString(3, book.getDescription());
int rowsAffected = prepStmt.executeUpdate();
if (rowsAffected > 0) {
result = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
releaseResources(prepStmt, null, conn);
}
return result;
}
public Book read(String isbn) {
Connection conn = null;
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
Book resultBook = null;
try {
conn = ConnectionProvider.getConnection();
prepStmt = conn.prepareStatement(READ);
prepStmt.setString(1, isbn);
resultSet = prepStmt.executeQuery();
if(resultSet.next()) {
resultBook = new Book();
resultBook.setIsbn(resultSet.getString("isbn"));
resultBook.setTitle(resultSet.getString("title"));
resultBook.setDescription(resultSet.getString("description"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
releaseResources(prepStmt, resultSet, conn);
}
return resultBook;
}
public boolean update(Book book) {
Connection conn = null;
PreparedStatement prepStmt = null;
boolean result = false;
try {
conn = ConnectionProvider.getConnection();
prepStmt = conn.prepareStatement(UPDATE);
prepStmt.setString(1, book.getIsbn());
prepStmt.setString(2, book.getTitle());
prepStmt.setString(3, book.getDescription());
prepStmt.setString(4, book.getIsbn());
int rowsAffected = prepStmt.executeUpdate();
if (rowsAffected > 0) {
result = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
releaseResources(prepStmt, null, conn);
}
return result;
}
public boolean delete(Book book) {
Connection conn = null;
PreparedStatement prepStmt = null;
boolean result = false;
try {
conn = ConnectionProvider.getConnection();
prepStmt = conn.prepareStatement(DELETE);
prepStmt.setString(1, book.getIsbn());
int rowsAffected = prepStmt.executeUpdate();
if (rowsAffected > 0) {
result = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
releaseResources(prepStmt, null, conn);
}
return result;
}
private void releaseResources(PreparedStatement prepStmt, ResultSet res,
Connection conn) {
try {
if (prepStmt != null && !prepStmt.isClosed()) {
prepStmt.close();
}
if (res != null && !res.isClosed()) {
res.close();
}
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
ConnectionProvider.java
package pl.javastart.util;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ConnectionProvider {
private static DataSource dataSource;
public static Connection getConnection() throws SQLException {
return getDSInstance().getConnection();
}
private static DataSource getDSInstance() {
if(dataSource == null) {
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/library");
} catch (NamingException e) {
e.printStackTrace();
}
}
return dataSource;
}
}
Dao.iml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="web" name="Web">
<configuration>
<descriptors>
<deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/web/WEB-INF/web.xml" />
</descriptors>
<webroots>
<root url="file://$MODULE_DIR$/web" relative="/" />
</webroots>
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="PROVIDED" name="Tomcat 9.0.0.M9" level="application_server_libraries" />
<orderEntry type="library" name="mysql-connector-java-5.1.39-bin" level="project" />
</component>
</module>
Here is a screen with project structure:
And console:
In context.xml
<Resource name="jdbc/library"
global="jbc/library"
...
it looks like the value for the global key might be missing a letter.
On a different note, all the examples of getConnection() I'm finding online have a String parameter for the url, e.g. this Mkyong article, but no where in your code does it appear to be like that. Is ConnectionProvider.getConnection() actually returning anything when you debug through it?
Problem solved. I had to add META-INF directory and move there context.xml
Screen attatched
I'm trying to create simple unique username check following this tutorial.
http://javaandj2eetutor.blogspot.com/2013/12/check-username-availability-using-java.html
But My ajax call for username is fails. I'm new to ajax and somewhat new for jsp.
Here is my index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Username Availability</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$(".username").change(function () {
var username = $(this).val();
if (username.length >= 3) {
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "CheckAvalability",
data: "uname="+ username,
success: function (msg) {
$(".status").ajaxComplete(function (event, request, settings) {
$(".status").html(msg);
});
}
});
}
else {
$(".status").html("<font color=red>Username should be <b>3</b> character long.</font>");
}
});
});
</script>
<div>
<label class="flable">User Name :</label> <input class="username" type="text" name="username"> <span class="status"></span>
</div>
</body>
</html>
Here is my Servlet
package hsenid;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final Logger logger = LogManager.getLogger(CheckAvailability.class);
private static final long serialVersionUID = -734503860925086969L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
logger.info("Check availability called");
DBConnector dbPool = (DBConnector)getServletContext().getAttribute("DBConnection");
Connection myConn = dbPool.getConn();
String uname = request.getParameter("username");
PreparedStatement ps = myConn.prepareStatement("select username from userdetails where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("<font color=green><b>"+uname+"</b> is avaliable</font>");
logger.info("Username detected!!!");
}
else{
out.println("<font color=red><b>"+uname+"</b> is already in use</font>");
}
out.println();
} catch (Exception ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Here is my servlet mapping in web.xml.
<servlet>
<servlet-name>CheckAvailability</servlet-name>
<servlet-class>hsenid.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckAvailability</servlet-name>
<url-pattern>/CheckAvailability</url-pattern>
</servlet-mapping>
This detects if minimum characters aren't added and also gives the massage check availability when type in there so I think jquery is added. Also I've run the servlet in Eclipse Mars. It do check the if a username is in the table or not. So I believe that the problem calling to the servlet because I can't see the log4j console output then. I'm unable find what wrong with my code.
Thanks in advance
I'm learning to build a web application using jsp and servlets.
My web application contains two text fields : one for the username and the seconde for password and a simple button to login.
I'm using an internal database to store the username and the passwords.
But when i press login i get always sorry username and password are incorrect
You can find here the code :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoginDao {
public static boolean validate(String username, String password) {
boolean status = false;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "info";
String driver = "com.mysql.jdbc.Driver";
String dBuserName = "root";
String dBpasssword = "azerty";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName, dBuserName,dBpasssword);
pst = conn.prepareStatement("select * from users where username=? and password=?");
pst.setString(1, dBusername);
pst.setString(2, dBpassword);
rs = pst.executeQuery();
status = rs.next();}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
System.out.println(e);
}
finally {
if (conn != null) {
try { conn.close(); }
catch (SQLException e) { } }
if (pst != null) { try { pst.close(); } catch (SQLException e) { } }
if (rs != null) { try {
rs.close();
} catch (SQLException e)
{
}
}
}
return status;
}
}
LoginServlet.java :
import java.io.IOException;
import java.io.PrintWriter;
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 javax.servlet.http.HttpSession;
#WebServlet(urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException , IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("password");
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("name", n);
if(LoginDao.validate(n,p)){
RequestDispatcher rd = request.getRequestDispatcher("/welcome.jsp");
rd.forward(request,response);
}
else{
out.print("<p style=\"color:red\">Sorry username or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request,response);
}
out.close();
}
}
weclome.jsp :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Welcome </h3>
<h4>
Hello,
<%=session.getAttribute("name")%></h4>
</body>
</html>
my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
version="2.5">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>loginDao</servlet-name>
<servlet-class>/LoginDao</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Change this code
pst.setString(1, dBusername);
pst.setString(2, dBpassword);
to
pst.setString(1, username);
pst.setString(2, password);
If you are using an IDE and you should debug such issues. If not using IDE then please use them as they help aid development like Eclipse, IntelliJ, etc.
I understand you are writing quick code to make it work. I am sure you will improve the code.
You should extract out the DB connection steps from your DAO so that you can use the same in multiple DAOs instead of repeating the code. Also inject the DB properties from outside instead of coding.
I am trying to check database for username availability. I don't know where it went wrong but it just keep saying "Checking availability" and never returns the answer. Below is my code.
index.jsp;
<html>
<head>
<title>Username Availability</title>
<style type="text/css">
.flable {
color: gray;
}
.status {
font-family: verdana;
font-size: 12px;
}
.uname {
color: blue;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js "></script>
<script type="text/javascript">
$(document).ready(function(){
$(".uname").change(function(){
var uname = $(this).val();
if(uname.length >= 3){
$(".status").html("<img src='images/loading.gif'><font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "check",
data: "uname="+ uname,
success: function(msg){
$(".status").ajaxComplete(function(event, request, settings){
$(".status").html(msg);
});
}
});
}
else{
$(".status").html("<font color=red>Username should be <b>3</b> character long.</font>");
}
});
});
</script>
</head>
<body>
<div>
<label class="flable">User Name :</label> <input type="text" class="uname" /> <span class="status"></span>
</div>
</body>
</html>
CheckAvailibilty.java:
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final long serialVersionUID = -734503860925086969L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String connectionURL = "jdbc:mysql://localhost:3306/quora"; // students is my database name
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
String uname = request.getParameter("uname");
PreparedStatement ps = connection.prepareStatement("select username from users where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("<font color=green><b>"+uname+"</b> is avaliable");
}
else{
out.println("<font color=red><b>"+uname+"</b> is already in use</font>");
}
out.println();
} catch (Exception ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
web.xml:
<servlet>
<servlet-name>check</servlet-name>
<servlet-class>com.amzi.servlets.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>check</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
You don't need ajaxComplete, when you get a msg just feed it to html()
success: function(msg){
$(".status").html(msg);
}