Requested Resource not available? - java

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>

Related

Error with Java Servlet & DB connection [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.
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>

Adding data to mysql with servlet not working

This is my database
CREATE TABLE `Animal` ( `name` varchar(128) NOT NULL, `breed` varchar(128) NOT NULL, `age` varchar(128) NOT NULL )
register.html to fill in the data
<html>
<body>
<form action="servlet/Register" method="post">
name <input type="text" name="name"/><br/><br/>
breed <input type="password" name="breed"/><br/><br/>
age <input type="password" name="age"/><br/><br/>
<br/><br/>
<input type="submit" value="register"/>
</form>
</body>
</html>
My servlet
package animals;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Register extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String breed = request.getParameter("breed");
String age = request.getParameter("age");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
PreparedStatement ps = con.prepareStatement(
"INSERT INTO Animal (name,breed,age) VALUES(?,?,?)");
ps.setString(1, name);
ps.setString(2, breed);
ps.setString(3, age);
int i = ps.executeUpdate();
if (i > 0) {
out.print("Data successfully registered...");
}
} catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>animals.Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
</welcome-file-list>
</web-app>
When I fill in the form and submit, it send me to /register but it's blank and it doesn't add data in my database.
I'm 100% sure that my connection to the java database is working, because I have another project with a login with the same connection to the database and that one is working.
Any tips / comments are welcome
Few things you can check :
1. Debug the code & check if values are captured by the servlet.
2. Use commit() after the executeUpdate(). Maybe your config is set to auto-commit off due to some reasons.
3. Is this string printed? "Data successfully registered..."
4. Lastly, Any exceptions?

Jsp servlet - login page is not redirecting properly

I am trying to create a login service but my pages are not redirecting properly. I have following:
login.jsp
<form action="login" method="post">
User Name
<br>
<input type="text" name="userId"/>
<br><br>
Password
<br>
<input type="password" name="password"/>
<br><br>
<input type="submit"/>
</form>
LoginServlet.java
package org.sohail.javabrains;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userId, password;
userId=request.getParameter("userId");
password=request.getParameter("password");
LoginService loginService = new LoginService();
boolean result = loginService.authenticate(userId, password);
if (result) {
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/success.jsp");
dispatcher.forward(request, response);
return;
}
else {
response.sendRedirect("login.jsp");
return;
}
}
}
LoginService.java - has a authenticate(userId, password) method which connects to database, verifies userId and pass and returns a boolean value.
web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>org.sohail.javabrains.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
from login.jsp page, doesn't matter what I put I get following error:
HTTP Status 404 - /LoginApp/login
It should redirect the page to success.jsp if authenticate() reutrns true.
I am pretty new to this so please feel free to provide any other suggestions.
Thank you Birgit Martinelle for following answer:
change your web.xml servlet mapping to
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
and remove the WEB-INF part from your redirect url:
RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp");
– Birgit Martinelle 50 mins ago

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

Calling servlet from HTML form, but servlet is never invoked [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.
Iam calling servlet from html form,servlet takes the form data and it will insert that form data into database.But when i click the submit button error page is coming.please help whats wrong in my servlet code.
my servlet code:
import javax.servlet.http.HttpServlet;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Loginservlet extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
System.out.println("login servlet");
String connectionURL = "jdbc:mysql://localhost:3306/mysql";
Connection connection=null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String username= req.getParameter("username");
String password = req.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "root");
String sql = "insert into signup values (?,?)";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, username);
pst.setString(2, password);
int numRowsChanged = pst.executeUpdate();
out.println(" Data has been submitted ");
pst.close();
}
catch(ClassNotFoundException e){
out.println("Couldn't load database driver: "+ e.getMessage());
}
catch(SQLException e){
out.println("SQLException caught: " + e.getMessage());
}
catch (Exception e){
out.println(e);
}
finally {
try {
if (connection != null)
connection.close();
}
catch (SQLException ignored){
out.println(ignored);
}
}
}
}
my html code:
Sign Up
<form action="servlet/Loginservlet" method="post" >
<font size='5'>Create your Account:</font><br/><br>
<label for="username" accesskey="u" style="padding-left:3px;">User Name: </label>
<input type="text" style="background-color:#ffffff;margin-left:14px;padding-top:7px;border-width:0px;margin-top:6px;padding-right:85px;" id="username" name="username" tabindex="1"><br/><br>
<label for="password" accesskey="p" style="padding-left:4px;">Password: </label>
<input type="password" style="background-color:#ffffff;margin-left:14px;padding-top:7px;border-width:0px;padding-right:85px;" id="password" name="pasword" tabindex="2"><br/><br>
<input type="submit" value="Submit" style="margin-left:164px;"/>
<input type="reset" value="Reset" style="margin-left:17px;"/>
</form>
web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<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">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>Loginservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
please help
check web.xml file of your project, you have to registrate your servlet there.check this also
use <form action="/login" method="post" > in html
and
in web.xml
<servlet-class>your.class.package.Loginservlet</servlet-class>
</servlet>
As you look into your servlet class, there is no package defined, which is required. And map that class with package(mean fully qualified name) in <servlet-class/> tag.
Another thing is you are setting action to url servlet/LogininServlet, but given different url in <url-pattern/> tag, which is wrong. you can simply set the form action to login
everything is fine....in the html page use action="./login".........it will work i have done the same

Categories

Resources