1
votes

I am writing a simple servlet program in which I am trying to save web form data(jsp) to mySQL database. I am getting a http status 404. Here is my code

My FirstServlet.java file is

package first;

import java.io.IOException;
import java.io.PrintWriter;

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 java.sql.*;

public class FirstServlet extends HttpServlet { private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public FirstServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse      response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse     response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Employee Management form";
 String docType =
 "<!doctype html public \"-//w3c//dtd html 4.0 " +
 "transitional//en\">\n";
 out.println(docType +
           "<html>\n" +
           "<head><title>" + title + "</title></head>\n" +
           "<body bgcolor=\"#f0f0c0\">\n" +
           "<h1 align=\"center\">" + title + "</h1>\n" +
           "<ul>\n" +
           "  <li><b>First Name</b>: "
           + request.getParameter("first_name") + "\n" +
           "  <li><b>Last Name</b>: "
           + request.getParameter("last_name") + "\n" +
           "</ul>\n" +
           "</body></html>");

 try {

 Connection myConn =     DriverManager.getConnection("jdbc:mysql://localhost:3306/world", "root" , "password");
 System.out.println("Loading driver...");
 Class.forName("com.mysql.jdbc.Driver");
 System.out.println("Driver loaded!");

Statement myStmt = myConn.createStatement();
//ResultSet myRs = myStmt.executeQuery("select * from countrylanguage");
String sql = "insert into countrylanguage"
+ " (CountryCode, Language, IsOfficial, Percentage)"
+ " VALUES ('dvi', 'engli', 'T', '9.3')";

myStmt.executeUpdate(sql);

}
catch (Exception exc) {
exc.printStackTrace();
 }
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
                HttpServletResponse response)
 throws ServletException, IOException {
doGet(request, response);
 }
}

The index.jsp file is

<%@ 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<H1>Welcome to Employee Management Project</H1>
<form action="FirstServlet" method="GET">
    First Name: <input type="text" name="first_name"> <br /> 
    Last Name: <input type="text" name="last_name" /> <br /> <br />
    <input type="checkbox" name="add" /> Add <input type="checkbox"    name="search" /> Search <input
        type="checkbox" name="delete" /> Delete  <input type="checkbox"
        name="update" /> Update <br /> <br />
        <input type="submit" value="Submit" />
 </form>
</body>
</html>

The web.xml file is

<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>HelloServlet2</display-name>

<servlet>
    <servlet-name>FirstServlet</servlet-name>
    <servlet-class>first.FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
    <url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>

</web-app>

Following is the hierarchy of the folder

HelloSevrvlet2
 Java Resources
  src
   first
    FirstServlet.java
 Libraries
  Apache Tomcat v7.0
  EAR Libraries
  JRE System Library
  Web App Libraries
 WebContent
  WEB-INF
   Lib
   web.xml
 index.jsp
3
try action="/FirstServlet" - singhakash
Tried it. Still getting the error. - sainid
What does the console show? - cнŝdk
Try action="FirstServlet". From /FirstServlet, the browser will construct an absolute URL like http://localhost/FirstServlet, which might or might not work depending on the mapping of the root of your application. On the other hand, action set to FirstServlet will result in an URL relative to the location of index.jsp (e.g. http://localhost/yourapproot/FirstServlet, which is what you actually want. - david a.
//@WebServlet("/FirstServlet") try to uncomment this line - hece

3 Answers

1
votes

You have a typo in the form statement in the jsp file. You have: The "HelloServlet2" has been mistakenly spelt as HelloSevrvlet2. Once you correct this problem, your code should work fine. I have personally tested your code with Glassfish server.

0
votes

In web.xml, following line must be like this:

<servlet-class>first.FirstServlet</servlet-class>

and in jsp file your action must be :

action="/FirstServlet"
0
votes

Here's how you get the values from JSP and store in a database table:
1. Create the table in the database

   create table emp(
      emp_id Integer primary key,
      first_name varchar(25),
      last_name varchar(25)
   )

The above mentioned 'create table' statment is for JavaDB database which comes bundled with Glassfish server. But you can tweak the create statement so that it can be run on the database of your choice.

  1. The Java Servlet code ( I have just included the try/catch block for database interaction. Other parts of servlet code remain the same as you posted earlier.)

    // You do not need to load the driver class as JDBC now  
    // loads the required driver class automatically based on the   
    // connect string you specify in the getConnection() method.  
    Connection myConn = null;  
    try {  
        int emp_id = Integer.parseInt(request.getParameter("emp_id"));  
        String first_name = (String) request.getParameter("first_name");  
        String last_name = (String) request.getParameter("last_name");  
        myConn = DriverManager.getConnection
        ("jdbc:derby://localhost:1527/sun-appserv-samples", "app", "app");  
        String sql = "INSERT INTO emp"  
                   + " (emp_id, first_name, last_name)"  
                   + " VALUES (?,?,?)";  
        PreparedStatement myStmt = myConn.prepareStatement(sql);  
        myStmt.setInt(1, emp_id);  
        myStmt.setString(2, first_name);  
        myStmt.setString(3, last_name);  
        int status = myStmt.executeUpdate();  
        out.println(status + " rows inserted");  
        myConn.commit();  
        myConn.close();  
    } catch (Exception exc) {  
        exc.printStackTrace();  
        out.println(exc.getMessage());  
    }
    
  2. Once you learn about technologies like Hibernate/JPA/JTA/JPQL, you will find that these APIs provide very powerful functionality for interacting with databases. Using these technologies, you will not have to interact with JDBC directly. For now, the solution I have given above should suffice.