Ajax not working with JSP in username availability - java

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);
}

Related

Servlet returning blank page not redirecting to jsp page

I am working on a Login and registration form. I have successfully created the Login and Registration form and linked them together. Now I created a separate page for admin where I want to display my database. But I am not able to move to the admin page. Whenever i input my admin credentials it always shows a blank page. I am a newbie both to Java and stackoverflow so I dont know how to ask proper questions. I pasted all my code here. My main problem is in Login.java . I am using eclipse and tomcat 8.5.
Things I have tried till now:-
1) RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/admin.jsp");
rd.forward(request, response);
2)HttpServletResponse.sendRedirect("/WEB-INF/admin.jsp")
3)response.sendRedirect("WEB_INF/admin.jsp");
Registeration.java
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 usernam = request.getParameter("usernam");
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(usernam,password,age,gender,event) values(?,?,?,?,?)";
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
"root", "");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernam);
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!");
out.flush();
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
rd.include(request, response);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Registeration.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<img src="unilogo.PNG" style="width:40%">
<body>
<div align="center">
<form action="Registeration" method="POST">
User Name:<input type="text" name="usernam" 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" /><br>
<a href="${pageContext.request.contextPath}/login.jsp">Click
here
to go to the login page</a>
</form>
</div>
</body>
</html>
Login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<div align="center">
<form action="Login" method="POST">
User Name:<input type="text" name="usernam" required="required">
<br>
Password : <input type="password" name="password"
required="required"><br>
<input type="submit" value="Login" />
<input type="reset" value="RESET" /><br>
<a
href="${pageContext.request.contextPath}/registeration.jsp">Click here
to
go to the Registration page</a>
</form>
</div>
</body>
</html>
Login.java
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
try {
String usernam = request.getParameter("usernam");
String password = request.getParameter("password");
String dbName = null;
String dbPassword = null;
String sql = "select * from registeration where usernam =
? and password = ?";
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
"root",
"");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernam);
ps.setString(2,password);
ResultSet rs = ps.executeQuery();
PrintWriter out = response.getWriter();
while(rs.next()){
dbName = rs.getString(2);
dbPassword = rs.getString("password");
if(usernam.equals("admin") &&
password.equals("password")){
RequestDispatcher rd =
request.getRequestDispatcher("/WEB-INF/admin.jsp");
rd.forward(request, response);
}
if(usernam.equals(dbName) &&
password.equals(dbPassword)) {
out.println("You have successfully logged
in!");
out.println("Age:"+rs.getString(4)+"
Gender:"+rs.getString(5)+" Event:"+rs.getString(6));
}
else {
RequestDispatcher rd =
request.getRequestDispatcher("/WEB-INF/registeration.jsp");
rd.forward(request, response);
}
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
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>Registeration</display-name>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>jdbc.registeration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/regServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>jdbc.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
My login page is supposed to redirect me to admin.jsp when i enter my admin details. But all i get is a blank page. My url after entering admin details"http://localhost:8080/Registeration/Login". I am getting the required output when enter the login id which are stored in DB.

JSP not showing results [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I'm having issues with my Java servlet and application. I'm pulling my hair out trying to understand how to make these servlets work correctly and output in the browser. I have attached my code below, please point me in the direction to get this program to work correctly. I understand sample code vs being told what to do. I'm not looking for you to do my work, just need help visually. All help is greatly appreciated.
Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class FormPost3 extends HttpServlet{
private static final long serialVersionUID = 1L;
Connection con = null;
public void Form3(){
init();
}
public void init(){
try{
Class.forName ("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:7070:XE", "student2", "pass");
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE MYTABLE (FNAME VARCHAR2(20),LNAME VARCHAR2(40), PHONE VARCHAR2(20))");
stmt.close();
}
catch (Exception e){
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<form action='" + request.getRequestURL() + "' method='post' >");
out.println("First Name:");
out.println("<input type='text' name='FNAME' />");
out.println("<br>");
out.println("Last Name:");
out.println("<input type='text' name='LNAME' />");
out.println("<br>");
out.println("Phone:");
out.println("<input type='text' name='PHONE' />");
out.println("<input type='submit' value='Submit' />");
out.println("</form>");
out.println("</body></html>");
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
try{
if (con != null)
init();
String fname = request.getParameter("FNAME");
String lname = request.getParameter("LNAME");
String phone = request.getParameter("PHONE");
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO MYTABLE VALUES('" + fname + "', '" + lname + "', '" + phone + "')");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
ResultSet rset = stmt.executeQuery("SELECT * FROM MYTABLE");
while (rset.next()){
out.print("<pre>");
out.print("First Name: " + rset.getString(1));
out.print("</pre>");
out.println();
out.print("<pre>");
out.print("Last Name: " + rset.getString(2));
out.print("</pre>");
out.println();
out.print("<pre>");
out.print("Phone: " + rset.getString(3));
out.print("</pre><br>");
out.println();
out.println();
}
out.println("</body></html>");
out.close();
stmt.close();
}
catch (Exception e){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println(e.getMessage());
out.println("</body></html>");
out.close();
}
}
}
Web.xml
<web-app version="2.5" 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_2_5.xsd">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FormPost3</servlet-name>
<servlet-class>FormPost3</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormPost3</servlet-name>
<url-pattern>/FormPost3</url-pattern>
</servlet-mapping>
</web-app>
index.html
<html>
<head>
</head>
<body>
<h3 align="center">Storing Employee Details</h3>
<form action="/WFormPost3" method="post">
<div align="center">
Empno: <input type="text" size="20" name="empno"/>
<br><br>
Ename <input type="text" size="20" name="ename"/>
<br><br>
Salary <input type="text" size="20" name="sal"/>
<br><br>
<input type="submit" value="insert" />
<div>
</form>
</body>
</html>
Change your form action in index.html to
<form action="WFormPost3" method="post">
Make sure by debugging that there does not exists any exception in your doPost method of WFormPost3.java servlet.

Ajax Unique user name search fails JSP

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

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