Adding data to mysql with servlet not working - java

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?

Related

Connecting Mysql with IntelliJ ultimate 2016.2.3 using JSP [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
Am new in JSP and the IntelliJ IDE am experiencing an error java.lang.ClassNotFoundException: com.mysql.jdbc.Driver when i try to login inside my Application. Am using IntelliJ as my IDE while developing a JSP project. How can I connect Mysql to a JSP project?
Below is LoginDao.java class
package com.huza.schooldynamic;
/**
* Created by HUZY_KAMZ on 9/8/2016.
*/
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 name, String pass) {
boolean status = false;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306";
String dbName = "form";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "namungoona";
try {
Class.forName(driver).newInstance();
conn = DriverManager
.getConnection(url + dbName, userName, password);
pst = conn
.prepareStatement("select * from login where user=? and password=?");
pst.setString(1, name);
pst.setString(2, pass);
rs = pst.executeQuery();
status = rs.next();
} catch (Exception e) {
System.out.println(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return status;
}
}
and this is my servlet class LoginServlet.java
package com.huza.schooldynamic;
/**
* Created by HUZY_KAMZ on 9/8/2016.
*/
import java.io.IOException;
import java.io.PrintWriter;
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.HttpSession;
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public 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("userpass");
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.jsp");
rd.include(request,response);
}
out.close();
}
}
This is my index.jsp file
<%--
Created by IntelliJ IDEA.
User: HUZY_KAMZ
Date: 9/8/2016
Time: 5:31 PM
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>School Management System</title>
</head>
<body>
<br>
<br>
<br>
<center>
<form action="loginServlet" method="post">
<fieldset style="width: 300px">
<legend> Login here </legend>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="username" required="required" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="userpass" required="required" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</fieldset>
</form>
</center>
</body>
</html>
This is my welcome.jsp file
<%--
Created by IntelliJ IDEA.
User: HUZY_KAMZ
Date: 9/8/2016
Time: 6:00 PM
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Login successful!!!</h3>
<h4>
Hello,
<%=session.getAttribute("name")%></h4>
</body>
</html>
And finally this is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="3.1">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.huza.schooldynamic.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
So currently i have tried to view Mysql in the IntelliJ IDE but it seems i don't know how to connect it to the project , when i run the app and i try ti login this error comes in the IDE java.lang.ClassNotFoundException: com.mysql.jdbc.Driver.
Below is the picture of the IDE
The ClassNotFoundException is telling you that it cannot find the class com.mysql.jdbc.Driver on your classpath. In other words, non of the library JARs you have defined in your project contain that class.
That particular class is a MySQL specific implementations of the java.sql.Driver interface. (If you do not understand what an interface is, you can start wit the Java tutorial's page on it. But you'll want to do more learning about it since interfaces are a core concept of OOP).
Your DAO class says to use this particular diver in the line String driver = "com.mysql.jdbc.Driver";. But when the code is running, it is not finding a class by that name. So you need to add that class to your classpath. By going to Advance Search Page at the Maven Central, you can search for that (or any other) class to determine what libraries have it. In this particular case, it is in the mysql-connector-java JAR; the latest version of which is v6.0.4.
So yo need to add the mysql-connector-java JAR to your classpath , that is add it as a library to your Java project. How you do that depends on how you have set up your project.
If you are using Maven, you can add the required dependency:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.4</version>
</dependency>
If you are using Gradle, add
compile 'mysql:mysql-connector-java:6.0.4'
If you are using Ant with Ivy, add
<dependency org="mysql" name="mysql-connector-java" rev="6.0.4" />
All those declarations I copied from the information page for that JAR file at maven central.
If you are not using one of the above build tools, you will need to add the JAR to your project in another way. For example, if you are just using the Project configuration in IDEA, go to Project Structure (Ctrl+Shift+Shift+S / ⌘;) and add it a new library to the module. See the Library IntelliJ IDEA help page and the pages it references for more information.

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>

insert data into database using servlet and jsp in eclipse

I am trying to add or insert values into table of database using servlet and jsp and MySQL Workbench as database. These are the following details:
1.> Register.java
package register.com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
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.*;
import javax.servlet.*;
/**
* Servlet implementation class Register
*/
#WebServlet("/register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
//String connectionURL = "jdbc:mysql://127.0.0.1:3306/newData";// newData is the database
//Connection connection;
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="userlogindb";
String driver="com.mysql.jdbc.Driver";
//String dbUserName="root";
//String dbPassword="root";
try{
String Fname = request.getParameter("fname");
String Mname = request.getParameter("mname");
String Lname = request.getParameter("lname");
String Uname = request.getParameter("username");
String Emailid = request.getParameter("emailid");
String Mobno = request.getParameter("mobno");
String Address = request.getParameter("address");
String Password1 = request.getParameter("password1");
String Password2 = request.getParameter("password2");
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,"root", "root");
PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into 'userlogindb'.'registerutable'(fname,mname,lname,username,emailid,mobno,address,password1,password2) values(?,?,?,?,?,?,?,?,?)");//try2 is the name of the table
pst.setString(1,Fname);
pst.setString(2,Mname);
pst.setString(3,Lname);
pst.setString(4,Uname);
pst.setString(5,Emailid);
pst.setString(6,Mobno);
pst.setString(7,Address);
pst.setString(8,Password1);
pst.setString(9,Password2);
int i = pst.executeUpdate();
conn.commit();
String msg=" ";
if(i!=0){
msg="Record has been inserted";
pw.println("<font size='6' color=blue>" + msg + "</font>");
}
else{
msg="failed to insert the data";
pw.println("<font size='6' color=blue>" + msg + "</font>");
}
pst.close();
}
catch (Exception e){
pw.println(e);
}
}
}
2.> index.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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="registrationform" action="register" method="post">
<p>
Enter your first name: <input type="text" name="fname"><br>
Enter your middle name: <input type="text" name="mname"><br>
Enter your last name: <input type="text" name="lname"><br>
</p><br>
<p>
Enter username: <input type="text" name="username"><br>
</p><br>
<p>
Enter email id: <input type="text" name="emailid"><br>
Enter mobile number: <input type="text" name="mobno"><br>
Enter address: <textarea rows="5" cols="5" name="address"></textarea><br>
</p><br>
<p>
Enter the password: <input type="password" name="password1"><br>
Reenter the password: <input type="password" name="password2"><br>
</p><br>
<p>
<input type="submit">
</p><br>
</form>
</body>
</html>
3.> 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" 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>RegisterExample</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>Register Servlet</description>
<display-name>Register</display-name>
<servlet-name>Register</servlet-name>
<servlet-class>register.com.Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
4.> I have added mysql-connector-java-5.0.8-bin.jar and servlet-api-3.0.jar is anything else needed to add it. I have created a connection to database in Data Source Explorer.
When I m compiling or debuging it shows no error. During runtime also there is no error.
When I fill in the form and submit it shows only blank screen :(
No output is displayed. :(
Also in the database values are not updated.
Please help me. I m getting hangover with this snippet.
Check that doPost() method of servlet is called from the jsp form and remove conn.commit.
Can you check value of i by putting logger or println(). and check with closing db conn at the end. Rest your code looks fine and it should work.
Same problem fetch main problem in PreparedStatement use simple statement then you successfully insert record same use below.
String st2="insert into
user(gender,name,address,telephone,fax,email,
destination,sdate,edate,Participant,hcategory,
Culture,Nature,People,Cities,Beaches,Festivals,username,password)
values('"+gender+"','"+name+"','"+address+"','"+phone+"','"+fax+"',
'"+email+"','"+desti+"','"+sdate+"','"+edate+"','"+parti+"',
'"+hotel+"','"+chk1+"','"+chk2+"','"+chk3+"','"+chk4+"',
'"+chk5+"','"+chk6+"','"+user+"','"+password+"')";
int i=stm.executeUpdate(st2);
In your JSP at line <form> tag,
try this code
<form name="registrationform" action="Register" method="post">
String user = request.getParameter("uname");
out.println(user);
String pass = request.getParameter("pass");
out.println(pass);
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
out.println("hello");
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";
st.executeUpdate(sql);
Remove conn.commit from Register.java
In your jsp change action to :<form name="registrationform" action="Register" method="post">
I had a similar issue and was able to resolve it by identifying which JDBC driver I intended to use. In my case, I was connecting to an Oracle database. I placed the following statement, prior to creating the connection variable.
DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());

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