Error with Java Servlet & DB connection [duplicate] - java

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
Having issues getting the program to display anything when running in eclipse.
Goal is:
In this application you will also create a virtual directory so that you do not have to use the word servlet as part of your form post URL. You will then be able to run your Web application servlet by using a URL similar to the following: http://localhost:7070/Week5/FormPost2. To create your virtual directory you may start by modifying the web.xml attached to this assignment. Next, create a Servlet that displays a form when the doGet method is invoked. The form will contain a post action that directs the form post back to the same servlet, which in the doPost method will save the form data to a database. Use your Oracle account to make the DB connection. After the form data has been saved to the database, respond back with a query from the database displaying all the current records contained in the database, in an appealing format. The form must contain a minimum of three input fields.
Below error was received:
HTTP Status 404 - /Week5/servlet/Week5.Week5
type Status report
message /Week5/servlet/Week5.Week5
description The requested resource is not available.
Apache Tomcat/7.0.72
I'm sure it is a simple error, but please pinpoint it so I can get it to display properly. Thank you.
package Week5;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Week5 extends HttpServlet{
private static final long serialVersionUID = 1L;
Connection con = null;
Statement stmt = null;
public Week5(){
init();
}
public void init(){
try{
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "student2", "pass");
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("");
out.println("");
out.println("First Name:");
out.println("");
out.println("");
out.println("Last Name:");
out.println("");
out.println("");
out.println("Phone:");
out.println("");
out.println("SUBMIT");
out.println("");
out.println("");
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("");
ResultSet rset = stmt.executeQuery("SELECT * FROM MYTABLE");
while (rset.next()){
out.print("");
out.print("First Name: " + rset.getString(1));
out.print("");
out.println();
out.print("");
out.print("Last Name: " + rset.getString(2));
out.print("");
out.println();
out.print("");
out.print("Phone: " + rset.getString(3));
out.print("");
out.println();
out.println();
}
out.println("");
out.close();
stmt.close();
}
catch (Exception e){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println(e.getMessage());
out.println("");
out.close();
}
}
}
XML
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<servlet>
<servlet-name>
Week5 <!-- Alias I gave the servlet // -->
</servlet-name>
<servlet-class>
HelloWorld <!-- Class name // -->
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
Week5 <!-- Alias I gave the servlet // -->
</servlet-name>
<url-pattern>
/VirtualName <!-- What I want the user to type in // -->
<!-- Example: http://localhost:7070/Week5/FormPost2 // -->
</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>
FormPost2
</servlet-name>
<servlet-class>
HelloWorld2
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
FormPost2
</servlet-name>
<url-pattern>
/VirtualName2
</url-pattern>
</servlet-mapping>
</web-app>

your servlet class should be fully qualified class name such as
<servlet-class>
week5.week5
</servlet-class>
<servlet-class> tag should contain the servlet(class)
<servlet-name> will be the name of the servlet that is mapped with the <servlet-mapping>
example
<servlet>
<servlet-name>
anyServletName
</servlet-name>
<servlet-class>
com.example.customServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
anyServletName
</servlet-name>
<url-pattern>
/VirtualName2
</url-pattern>
</servlet-mapping>

Related

Error HTTP Status 404. The requested resource is not available. [Netbeans]

I do a project Fahrenheit to Celsius conversion using netbeans with Tomcat 8.0.37
when i try to run project, i get a issue HTTP Satus 404.
My index.html
<html>
<head>
</head>
<body>
<h3>Please enter Fahrenheit temperature:</h3><p>
<form action="/conv/test">
Temperature(F) : <input type="text" name="temperature"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
My web.xml
<web-app>
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>doGetMethod.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
My TestServlet.java
public class TestServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException
{
String temperature = req.getParameter("temperature");
DecimalFormat twoDigits = new DecimalFormat("0.00");
try
{
double tempF = Double.parseDouble(temperature);
String tempC = twoDigits.format((tempF -32)*5.0/9.0);
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("<h3>" + temperature + " Fahrenheit is
converted to " + tempC + " Celsius</h3><p>");
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"There was an input error");
}
}
}
Please help me to solve this issue !
I apologize for not being word-perfect in English.
You should access the index.html at localhost:8080/contextRoot/index.html. The action associated to the form should map to the servlet, so it should be action="/test". The servlet-class tag in the web.xml should specify your servlet class full name such as mypackage.TestServlet. You could avoid using a web.xml and save you some time by using annotation on the Servlet class as well explained here https://docs.oracle.com/javaee/7/tutorial/servlets004.htm#BNAFU. Also look here for a similar example https://stackoverflow.com/a/2395262/6848537

Uploading Java to a website doesn't works

I have uploaded on a... let's say www.mywebsite.com a /helloservlet/ and into /helloservlet/ I have an index.html that shows a simple Hello World! This works fine but if I want to put an Java app, I uploaded a /WEB-INF/web.xml with:
<?xml version="1.0" encoding="ISO-8859-1"?>
<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>HelloWorldServlet</servlet-name>
<servlet-class>mypkg.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>
and in /helloservlet/WEB-INF/src/mypkg/HelloServlet.java with
package mypkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Set the response message's MIME type
response.setContentType("text/html;charset=UTF-8");
// Allocate a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
// Write the response message, in an HTML page
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
// Echo client's request information
out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
out.println("<p>Protocol: " + request.getProtocol() + "</p>");
out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
// Generate a random number upon each request
out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close(); // Always close the output writer
}
}
}
but when I try
http://www.mywebsite.com/helloservlet/sayhello
It gives me an error.
What is the problem?
Thanks!
Use a Java application server on the machine that should host your code, like Tomcat. Then upload the .war to this Tomcat instance (or glassfish or whatever) this should fix your issue.

Requested Resource not available?

I am new to servlets and jdbc.I just created a Registration page and a HTML registration form. I don't know why I am getting error like : HTTP Status 404 and description for this as The requested page is not available. Here is my servlet, html and .xml files. Please help me with this problem. I am using tomcat 7 and jdk8, in eclipse kepler.
public class Register extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String Name = request.getParameter("Name");
String Email = request.getParameter("Email");
String Password = request.getParameter("Pass");
try {
Class.forName("oracle.jdbc.driver.DriverManager");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl", "scott", "tiger");
PreparedStatement ps = conn
.prepareStatement("Insert into student values(?,?,?)");
ps.setString(1, Name);
ps.setString(2, Email);
ps.setString(3, Password);
int i = ps.executeUpdate();
if (i > 0) {
pw.println("Registered Successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
My Html code.
<body>
<form method="post" action="register">
Name : <input type="text" name="Name"><br/>
Email :<input type="text" name="Email"><br/>
Password :<input type="password" name="Pass"><br/>
<input type="submit" value="register"/>
</form>
and my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app >
<display-name>SimpleServlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
I am able to hit servlet code using http://localhost:8080/MyWebapp/register.
In my case,Register servlet is in default package.
If your Register servlet is in a package,then in your web.xml,specify class name with package like this.
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>your.package.Register</servlet-class>
</servlet>

Why "response.sendRedirect" doesn't work?

This is my login part which I need to compare user input with data in the database.
So If a lecturer tries to enter the system, he or she will get into lecturer interface(lecturer.html) and same goes to the student.
But right now, when I try to enter the system using either lecturer or student ID, the system will direct me to the log in interface.
I hope someone can help me to solve this :)
This is the query for Java DB (LogIn.java)
public class LogIn extends HttpServlet {
static final String dbURI = "jdbc:derby://localhost:1527/webdb";
String str = SELECT DEMO.REGISTRATION.*, \n" +
DEMO.STUDENT.STUD_PASSWORD,DEMO.LECTURER.LECT_PASSWORD
FROM DEMO.REGISTRATION
LEFT OUTER JOIN DEMO.STUDENT
ON REGISTRATION.STUDENT_ID = STUDENT.STUDENT_ID
LEFT OUTER JOIN DEMO.LECTURER
ON REGISTRATION.LECTURER_ID = LECTURER.LECTURER_ID;";
Connection theConnection = null;
And this is the rest of codes (LogIn.java)
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String matricI = request.getParameter("matricin");
String passwordI = request.getParameter("passwordin");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>\n" +
" <head>\n" +
" <title>SPEDT | UKM</title>\n" +
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n" +
" <link rel=\"stylesheet\" href=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css\">\n" +
" <link rel=\"stylesheet\" href=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css\">\n" +
" <script src=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js\"></script>\n" +
" </head>\n" +
" \n" +
" <body>\n" +
" \n" +
" <div class=\"navbar navbar-inverse \" role=\"navigation\">\n" +
" <div class=\"container\">\n" +
" <div class=\"navbar-header\">\n" +
" <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".navbar-collapse\">\n" +
" <span class=\"sr-only\">Toggle navigation</span>\n" +
" <span class=\"icon-bar\"></span>\n" +
" <span class=\"icon-bar\"></span>\n" +
" <span class=\"icon-bar\"></span>\n" +
" </button>\n" +
" <a class=\"navbar-brand\" href=\"#\">Sistem Penilaian Esei Dalam Talian</a>\n" +
" </div>\n" +
" <div class=\"navbar-collapse collapse\">\n" +
" <form class=\"navbar-form navbar-right\" role=\"form\" method=\"get\" action=\"http://localhost:8080/Spedt/LogIn\">\n" +
" <a class=\"btn btn-danger\" role=\"button\" href=\"http://localhost:8080/Spedt/start.html\">Keluar</a>\n" +
" </form>\n" +
" </div><!--/.navbar-collapse -->\n" +
" </div>\n" +
" </div>\n" +
"</html>");
// Load database driver
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch (ClassNotFoundException cnfe){
System.out.println(cnfe);
}
// Create a Connection to contacts db Data source
try {
theConnection = DriverManager.getConnection(dbURI,"demo","demo");
} catch (SQLException sqle) {
System.out.println(sqle);
}
// prepare statement for inserting data into table
try {
PreparedStatement theStatement=theConnection.prepareStatement(str);
request.setAttribute("matricin",matricI);
request.setAttribute("passwordin",passwordI);
Statement st = theConnection.createStatement();
ResultSet rs = st.executeQuery(str);
String m = matricI;
String p = passwordI;
while (rs.next()) {
String matricS = rs.getString("STUDENT_ID");
String passwordS = rs.getString("STUD_PASSWORD");
String matricL = rs.getString("LECTURER_ID");
String passwordL = rs.getString("LECT_PASSWORD");
if(m.equals(matricS) && p.equals(passwordS)){
response.sendRedirect("http://localhost:8080/Spedt/StudentInput");
return;}
else if(m.equals(matricL) && p.equals(passwordL)){
response.sendRedirect("http://localhost:8080/Spedt/Lecturer.html");
return;}
else {
out.println("<p class=\"bg-danger container\">Sila masukkan No. Matrik dan Kata Laluan yang betul !</p>");
}
}
}
catch (SQLException sqle) {
System.out.println(sqle);
}
theConnection.close(); //Close database Connection
}catch(Exception e) {
out.println(e.getMessage());//Print trapped error.
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
and this is the html
<form class="navbar-form navbar-right" role="form" method="get" action="http://localhost:8080/Spedt/LogIn">
<div class="form-group">
<input type="text" name="matricin" placeholder="No. Matrik" class="form-control">
</div>
<div class="form-group">
<input type="password" name="passwordin" placeholder="Kata Laluan" class="form-control">
</div>
<button type="submit" class="btn btn-success">Masuk</button>
</form>
This is my 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>InputData</servlet-name>
<servlet-class>mypkg.InputData</servlet-class>
</servlet>
<servlet>
<servlet-name>GetData</servlet-name>
<servlet-class>mypkg.GetData</servlet-class>
</servlet>
<servlet>
<servlet-name>LogIn</servlet-name>
<servlet-class>mypkg.LogIn</servlet-class>
</servlet>
<servlet>
<servlet-name>Lecturer</servlet-name>
<servlet-class>mypkg.Lecturer</servlet-class>
</servlet>
<servlet>
<servlet-name>Student</servlet-name>
<servlet-class>mypkg.Student</servlet-class>
</servlet>
<servlet>
<servlet-name>LogOut</servlet-name>
<servlet-class>mypkg.LogOut</servlet-class>
</servlet>
<servlet>
<servlet-name>LecturerInput</servlet-name>
<servlet-class>mypkg.LecturerInput</servlet-class>
</servlet>
<servlet>
<servlet-name>GetDataLecturer</servlet-name>
<servlet-class>mypkg.GetDataLecturer</servlet-class>
</servlet>
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>mypkg.NewServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>InputLecturer</servlet-name>
<servlet-class>mypkg.InputLecturer</servlet-class>
</servlet>
<servlet>
<servlet-name>GetDataLect</servlet-name>
<servlet-class>mypkg.GetDataLect</servlet-class>
</servlet>
<servlet>
<servlet-name>StudentInput</servlet-name>
<servlet-class>mypkg.StudentInput</servlet-class>
</servlet>
<servlet>
<servlet-name>InputStudent</servlet-name>
<servlet-class>mypkg.InputStudent</servlet-class>
</servlet>
<servlet>
<servlet-name>GetDataStud</servlet-name>
<servlet-class>mypkg.GetDataStud</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InputData</servlet-name>
<url-pattern>/InputData</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetData</servlet-name>
<url-pattern>/GetData</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogIn</servlet-name>
<url-pattern>/LogIn</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Lecturer</servlet-name>
<url-pattern>/Lecturer</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Student</servlet-name>
<url-pattern>/Student</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogOut</servlet-name>
<url-pattern>/LogOut</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LecturerInput</servlet-name>
<url-pattern>/LecturerInput</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetDataLecturer</servlet-name>
<url-pattern>/GetDataLecturer</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InputLecturer</servlet-name>
<url-pattern>/InputLecturer</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetDataLect</servlet-name>
<url-pattern>/GetDataLect</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>StudentInput</servlet-name>
<url-pattern>/StudentInput</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InputStudent</servlet-name>
<url-pattern>/InputStudent</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetDataStud</servlet-name>
<url-pattern>/GetDataStud</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
I hope someone can help me to solve this problem.thanks :)
In your code you don't need to specify full URL in action you can just Specify abc.jsp or ServletName which is there in web.xml.
<form class="navbar-form navbar-right" role="form" method="get" action="LogIn">
Secondly you need to specify onClick in Submit button of your form.
<button type="submit" class="btn btn-success" onclick="action">Masuk</button>
EDIT
I'm getting this, every time I try to log in.
localhost:8080/Spedt/LogIn?matricin=A138&passwordin=92
So it's working and you need to do some stuff in your LogIn Servlet as your doGet method is Empty and better to Use POST for LogIn!!!
ohhh..
In this case control is not reaching to servlet so how would you expect to run redirect!!
In action part of your html you have written action="http://localhost:8080/Spedt/LogIn"
you should use action for your servlet which you have define in web.xml file
see your xml file is
<servlet>
<servlet-name>LogIn</servlet-name>
<servlet-class>mypkg.LogIn</servlet-class>
</servlet>
if your write action=LogIn then you will go to mypkg.LogIn servlet

Executing MySQL Commands from a Java Servlet

I'm trying to get my servlet to output the results of SQL commands entered by the user. Right now, the servlet correctly detects when a command does not include "SELECT", "INSERT", or "DELETE", and outputs an error message. When the command is valid, nothing is outputted. I know this means my problem is likely occurring either where I am trying to connect to the database, or where I am trying to print output to "out".
databaseServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
#SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
private Connection conn;
private Statement statement;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName(config.getInitParameter("databaseDriver"));
conn = DriverManager.getConnection(
config.getInitParameter("databaseName"),
config.getInitParameter("username"),
config.getInitParameter("password"));
statement = conn.createStatement();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<xml version = \"1.0\"?>");
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
out.println("<html xmlns = \"http://www.w3.org/1999/xhtml\">");
out.println("<head>");
out.println("<title>MySQL Servlet</title>");
out.println("<style type='text/css'>");
out.println("body{background-color: blue}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
String query = request.getParameter("query");
if (query.toLowerCase().contains("select")) {
//SELECT Queries
try {
ResultSet resultSet = statement.executeQuery(query);
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
out.printf("%20s\t", metaData.getColumnName(i));
}
out.println();
while (resultSet.next()){
for (int i = 1; i <= numberOfColumns; i++){
out.printf("%20s\t", resultSet.getObject(i));
}
out.println();
}
}
catch (Exception f) {
f.printStackTrace();
}
}
else if (query.toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
//DELETE and INSERT commands
try {
conn.prepareStatement(query).executeUpdate(query);
out.println("\t\t Database has been updated!");
}
catch (Exception l){
l.printStackTrace();
}
}
else {
//Not a valid response
out.println("\t\t Not a valid command or query!");
}
out.println("</body>");
out.println("</html>");
out.close();
}
}
dbServlet.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>MySQL Servlet</title>
<style type="text/css">
body{background-color: green;}
</style>
</head>
<body>
<h1>Hello World!</h1>
<h2>This is the MySQL Servlet</h2>
<form action = "/database/database" method = "get">
<p>
<label>Enter your query and click the button to invoke a MySQL Servlet
<input type = "text" name = "query" />
<input type = "submit" value = "Run MySQL Servlet" />
</label>
</p>
</form>
</body>
</html>
I thought another potential failure point could be my path to the database file, which is initialized in my web.xml file. An example I found online included the port, but I'm wondering if I should remove the port number. Does anyone know the default port to use for MySQL?
This is the specific line I'm talking about from the xml file below:
jdbc:mysql://localhost:3309/project4
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<!-- General description of the web application -->
<display-name>
MySQL Servlet
</display-name>
<description>
This web application allows the user to connect to a database, sumbit queries, and make changes.
</description>
<!-- Servlet definitions -->
<servlet>
<servlet-name>database</servlet-name>
<description>
A servlet that handles SQL commands submitted by the user.
</description>
<servlet-class>
databaseServlet
</servlet-class>
<init-param>
<param-name>databaseDriver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>databaseName</param-name>
<param-value>jdbc:mysql://localhost:3309/project4</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>pass</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>database</servlet-name>
<url-pattern>/database</url-pattern>
</servlet-mapping>
</web-app>
I was using port 3309, and needed to use port 3306.
PROBLEM
jdbc:mysql://localhost:3309/project4
SOLUTION
jdbc:mysql://localhost:3306/project4

Categories

Resources