why i get this error? HTTP Status 404 – Not Found - java

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

Related

Why am I getting a blank page in my servlet program

I am using netbeans 8.2 and using Apache Tomcat server. Whenever I run the program I get to the registration page. But when I submit the information I am supposed to get an output. But I always get a blank page.I am using the database present in JAVA. Please Help I have to submit my java project;_;. I still need to create a login page.
Thanks in Advance.
Jsp Program
<%--
Document : registeration
Created on : Mar 12, 2019, 10:24:50 AM
Author : Pranav Sharma
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div align="center">
<form action="Registeration" method="POST">
User Name:<input type="text" name="user" required="required"><br>
Password : <input type="password" name="password"
required="required"><br>
Age : <input type="text" name="age" required="required" /><br>
Gender : <select name="gender">
<option>Male</option>
<option>Female</option>
<option>Transgender</option>
</select><br>
Event : <select name="event" multiple="multiple">
<option>Mr.Tanwar Body Building</option>
<option>Fashion Show</option>
<option>Dance</option>
<option>Singing</option>
<option>Coding</option>
</select><br>
<input type="submit" value="REGISTER" />
<input type="reset" value="RESET" />
</form>
</div>
</body>
Servlet Program
package jdbc;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name="Registeration", urlPatterns={"/Registeration"})
public class Registeration extends HttpServlet
{
private static final long serialVersionUID = 1L;
public Registeration(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
try {
String name = request.getParameter("user");
String password = request.getParameter("password");
String age = request.getParameter("age");
String gender = request.getParameter("gender");
String event = request.getParameter("event");
String sql = "insert into
registeration(name,password,age,gender,event) values(?,?,?,?,?)";
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/RegForm","pranav","sharma");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,name);
ps.setString(2,password);
ps.setString(3,age);
ps.setString(4,gender);
ps.setString(5,event);
ps.executeUpdate();
PrintWriter out = response.getWriter();
out.println("You have successfully registered!");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Web-xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
<servlet>
<servlet-name>Registeration</servlet-name>
<servlet-class>jdbc.Registeration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registeration</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I have create a java-servlet project which uses sql server as a database. Underline project takes input from the ui and persist into database.
After inserting data into database, it will show up is records inserted successfully or not.
Change the DBConnectionUtils according to your database
String url = "jdbc:mysql://localhost:3306/";
String dbName = "root";
String driver = "com.mysql.jdbc.Driver";
This is the link for the project on github https://github.com/rosmahajan/java-servlet
Otherwise please post more information like any exception or error you are getting to investigate what is wrong with your code.
Hope this helps you !!

How to insert and retrieve image database using jsp/Servlet?

I have got a Form Page index.jsp :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style>
fieldset
{
width: 70px;
}
</style>
</head>
<body>
<form action="Upload" method="post" enctype="multipart/form-data">
<fieldset>
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Select Photo</td>
<td><input type="file" name="photo"></td>
</tr>
<td><input type="submit" value="Upload"></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
MyServlet Page Upload.java:
import java.sql.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.DriverManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet(name = "Upload", urlPatterns = {"/Upload"})
#MultipartConfig(maxFileSize = 169999999) // upload file's size up to 16MB
public class Upload extends HttpServlet
{
private static final long serialVersionUID = 1L;
PrintWriter out;
InputStream inputStream = null;
int allField = 0;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try
{
out = response.getWriter();
String name=request.getParameter("name");
Part filePart = request.getPart("photo");
if (filePart != null)
{
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","root")
PreparedStatement ps = con.prepareStatement("insert into PhotoDetails(Name,Images)values(?,?)");
ps.setString(1,name);
ps.setBlob(2,inputStream);
ps.executeUpdate();
out.println("Image Inserted");
}
catch(Exception e)
{
out.println(e);
}
}
}
I am using mysql database and here is my table:
create table PhotoDetails
(
Name varchar(100),
Images blob
)
After filling all the form and when I click on the Update button then I get this error :
HTTP Status 500 - Servlet execution threw an exception
How could I resolve this problem?
This is the best way to show image in jsp file.
Just create showLogo.jsp
and include where ever you want it.
<%# page trimDirectiveWhitespaces="true" %>
<%# page import="java.sql.*,java.io.*,org.apache.struts2.ServletActionContext"%>
<%# page language="java" import="java.util.*, com.abc.util.dbutil.*,javax.servlet.http.HttpServletRequest" %>
<%
try{
InputStream sImage;
ResultSet resultSet = null;
PreparedStatement pstmt = null;
DBConnection dbConnection= null;
dbConnection= new DBConnection();
Connection con = null;
con= dbConnection.getConnection();
ServletInputStream sInIm = null;
Statement st=con.createStatement();
String company_id = request.getParameter("company_id");
resultSet=st.executeQuery("select logo from company where company_id='" + company_id + "'");
if(resultSet.next()){
byte[] bytearray = new byte[1048576];
int size=0;
sImage = resultSet.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1){
response.getOutputStream().write(bytearray,0,size);
}
response.getOutputStream().flush();
response.getOutputStream().close();
}
con.close();
}
catch(Exception ex){
}
%>
I am getting it like this.
/company/showLogo.jsp?company_id=" id="blah_s" class="logo-small">
Get image from file to FileInputStream
FileInputStream fs = null;
try {
fs = new FileInputStream(getUserImage());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
.................
ps.setBinaryStream(8, fs, fs.available());
insert into table(logo) values (?)
This is for mysql with blob column.

I always get Sorry username and password are incorrect when i press login (java web application)

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.

Basics of this web application development [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am creating a payroll system. I have a database which contains employee_id and password. My index.html is the login page, where you enter an employee_id and password and the database checks to see if the details are correct and if it is, then the Welcome.java servlet takes you to a page which prints "Welcome user".
What I want is, when an employee logs in, it takes them to a page with the following buttons instead of a screen which simply says "Welcome user":
View personal information, View payslip information, change password
I do not know how to do this.
Below are my files.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="login" method="post">
<h3>
Employee Login
</h3>
<b>Employee ID:</b> <br>
<input type="text"name="employee_id" size="20"><br><br>
<b>Password:</b><br>
<input type="password" name="password" size="20"><br><br>
<input type="submit" value="Login"><br><br>
</form>
</body>
</html>
Login.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String employee_id = request.getParameter("employee_id");
String password = request.getParameter("password");
if(Validate.checkUser(employee_id, password)) {
RequestDispatcher rs = request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else
{
out.println("Employee ID or Password is incorrect. Please try again.");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
Validate.java (class file)
import java.sql.*;
public class Validate
{
public static boolean checkUser(String employee_id, String password)
{
boolean st = false;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps = con.prepareStatement("select * from employee_login where employeeID = ? and pwd = ?");
ps.setString(1, employee_id);
ps.setString(2, password);
ResultSet rs =ps.executeQuery();
st = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Welcome.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Welcome extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Welcome user");
}
}
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" >
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>
You have to change one line of code of login servlet RequestDispatcher rs = request.getRequestDispatcher("Welcome"); as RequestDispatcher rs = request.getRequestDispatcher("Options");
and create a html file of creating 3 buttons.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Options</title>
</head>
<body>
<form action="Mainservlet" method="post">
<h3>
Options
</h3>
<input type="submit" value="Personalinformation" name="pi">
<br>
<br>
<input type="submit" value="PayslipInformation" name="psi">
<br>
<br>
<input type="submit" value="ChangePassword" name="cp">
<br>
<br>
</form>
</body>
</html>
In mainservlet
if(request.getParameter("pi") != null) {
// Invoke PersonalInformation's job here.
} else if (request.getParameter("psi") != null) {
// Invoke PayslipInformation's job here.
}else if (request.getParameter("cp") != null) {
// Invoke ChangePassword's job here.
}
Create an html or jsp page with your buttons and other content, then redirect from login servlet to your page instead of welcome servlet through request dispatcher or just by response.sendRedirect() method.

Cannot create PoolableConnectionFactory (Unknown database 'database')

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.

Categories