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.
Related
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.
I am using netbeans 8.2 and using Apache Tomcat server. Whenever I run the program I get to the registration page. But when I submit the information I am supposed to get an output. But I always get a blank page.I am using the database present in JAVA. Please Help I have to submit my java project;_;. I still need to create a login page.
Thanks in Advance.
Jsp Program
<%--
Document : registeration
Created on : Mar 12, 2019, 10:24:50 AM
Author : Pranav Sharma
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div align="center">
<form action="Registeration" method="POST">
User Name:<input type="text" name="user" 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" />
</form>
</div>
</body>
Servlet Program
package jdbc;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name="Registeration", urlPatterns={"/Registeration"})
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 name = request.getParameter("user");
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(name,password,age,gender,event) values(?,?,?,?,?)";
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/RegForm","pranav","sharma");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,name);
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!");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
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>Registeration</servlet-name>
<servlet-class>jdbc.Registeration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registeration</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I have create a java-servlet project which uses sql server as a database. Underline project takes input from the ui and persist into database.
After inserting data into database, it will show up is records inserted successfully or not.
Change the DBConnectionUtils according to your database
String url = "jdbc:mysql://localhost:3306/";
String dbName = "root";
String driver = "com.mysql.jdbc.Driver";
This is the link for the project on github https://github.com/rosmahajan/java-servlet
Otherwise please post more information like any exception or error you are getting to investigate what is wrong with your code.
Hope this helps you !!
I'm newbie to servlet programming. I have checked various other links about the Http 404 error but nothing helped me. So I'm posting my code here.
I have three html forms in WebContent/ folder form1.html, form2.html,form3.html, all these forms have same url pattern because accessing three different forms in the same Http session.
form1.html
<html>
<head>
<title>Adhar Registration Form</title>
</head>
<body style="background-color:orange">
<h1>FORM 1</h1>
<form action="./reg" method="get">
<table>
<tr><td>NAME:</td><td><input type="text" name="id"/></td></tr>
<tr><td>F_NAME:</td><td><input type="text" name="name"/></td></tr>
<tr><td>M_NAME:</td><td><input type="text" name="email"/></td></tr>
<tr><td><input type="submit" name= "NEXT"> </td></tr>
</table>
<input type="hidden" name="fno" value="1">
</form>
</body>
</html>
form2.html
<html>
<head>
<title>Adhar Registration Form</title>
</head>
<body style="background-color:orange">
<h1>FORM 2</h1>
<form action="./reg" method="get">
<table>
<tr><td>CONTACT:</td><td><input type="text" name="id"/></td></tr>
<tr><td>EMAIL:</td><td><input type="text" name="name"/></td></tr>
<tr><td>ADDRESS:</td><td><textarea rows ="10" cols="5" name="address"></textarea></td></tr>
<tr><td><input type="submit" name= "NEXT"> </td></tr>
</table>
<input type="hidden" name="fno" value="2">
</form>
</body>
</html>
<html>
<head>
<title>Adhar Registration Form</title>
</head>
<body style="background-color:orange">
<h1>FORM 3</h1>
<form action="./reg" method="get">
<table>
<tr><td>QUALIFICATION:</td><td><input type="text" name="id"/></td></tr>
<tr><td>PAN NO:</td><td><input type="text" name="name"/></td></tr>
<tr><td><input type="submit" name= "Register"> </td></tr>
</table>
<input type="hidden" name="fno" value="3">
</form>
</body>
</html>
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>Adhar</display-name>
<welcome-file-list>
<welcome-file>form1.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>container.RegistrationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>
</web-app>
RegistrationServlet.java
package container;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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 javax.servlet.http.HttpSession;
/**
* Servlet implementation class RegistrationServlet
*/
#WebServlet("/reg")
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String URL = "jdbc:mysql://localhost/db";
public static final String USER = "root";
public static final String PASSWORD = "12345";
public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
/**
* #see HttpServlet#HttpServlet()
*/
public RegistrationServlet() {
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
PrintWriter out = response.getWriter();
HttpSession hs = request.getSession();
String fno = request.getParameter("fno");
if(fno.equals("1")){
String name = request.getParameter("name");
String f_name = request.getParameter("f_name");
String m_name = request.getParameter("m_name");
hs.setAttribute("name", name);
hs.setAttribute("f_name", f_name);
hs.setAttribute("m_name", m_name);
response.sendRedirect("./Form2.html");
}
if(fno.equals("2")){
String contact = request.getParameter("contact");
String email = request.getParameter("email");
String address = request.getParameter("address");
hs.setAttribute("contact", contact);
hs.setAttribute("email", email);
hs.setAttribute("address", address);
response.sendRedirect("./Form3.html");
}
if(fno.equals("3")){
String qual = request.getParameter("qual");
String pan = request.getParameter("pan");
String name = (String)hs.getAttribute("name");
String f_name = (String)hs.getAttribute("f_name");
String m_name = (String)hs.getAttribute("m_name");
String contact = (String)hs.getAttribute("contact");
String email = (String)hs.getAttribute("email");
String address = (String)hs.getAttribute("address");
try {
Class.forName(DRIVER_CLASS);
System.out.println("Loaded the driver");
Connection con = DriverManager.getConnection(URL,USER,PASSWORD);
PreparedStatement ps = con.prepareStatement("INSERT into adharReg values(?,?,?,?,?,?,?,?)");
ps.setString(1, name);
ps.setString(2, f_name);
ps.setString(3, m_name);
ps.setString(4, contact);
ps.setString(5, email);
ps.setString(6, address);
ps.setString(7, qual);
ps.setString(8, pan);
int i = ps.executeUpdate();
if(i!=0){
out.println("<h1>REGISTRATION SUCCESS</h1>");
}
else{
out.println("<h1>REGISTRATION FAILED</h1>");
}
} catch (Exception e) {
// TODO: handle exception
out.println("<h1>REGISTRATION FAILED" + e.getMessage() + " </h1>");
}
}
}
}
I'm using tomcat server 8.0. I checked this Link and my tomcat server has exact same settings. And followed this link for any possible mistakes but, I don't know the exact reason why i'm getting Http 404 error. Help me out why i'm getting this error.
Thanks.
The issue is caused by a conflict between web.xml configuration and the WebServlet annotation. The web.xml is delcaring a servlet called login that target to the /reg url, but also in the RegistrationServlet there is a declaration throught #WebServlet annotation that reference to the same url /reg.
One possible solution is to remove the servlet declaration from the web.xml, that means that the web.xml content should be like this.
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>Adhar</display-name>
<welcome-file-list>
<welcome-file>form1.html</welcome-file>
</welcome-file-list>
</web-app>
Just let the Servlet declared by annotation only. Hope this helps.
check web.xml is exist into WEB-INF folder.
and use servlet mapping into web.xml
And register the servlet instead in web.xml like this:
<servlet>
<servlet-name>yourServlet</servlet-name>
<servlet-class>com.example.YourServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>yourServlet</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
for more refer bellow link :-
http://www.beingjavaguys.com/2013/08/jsp-servlet-hello-world-example.html
https://www.javatpoint.com/servlet-with-annotation
I'm having a little issue connecting with my servlet so that I can pass some data to a mysql database. I've read a bunch of the threads here, but have had no luck with suggestions to other members.
I have a jsp page named "insertData.jsp" On that page there is a form where the action points to a servlet named "UpdateData". When I click submit on the web page, I get a 404 error stating that the requested resource is not available. I have also updated my web xml file to try to point to the right direction.
So here's my folder setup:
The UpdateData.java is in the controller package of the source packages folder. The name of the project is "RukertContainerTracker".
Here's my jsp page:
<%#taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert Data</title>
</head>
<body>
<h1>Insert Data Into Container Records</h1>
<H1>The Rukert Terminals Container Tracker </H1>
<form name="Insert Record" action="/UpdateData" method="Post">
Container Number: <input type="text" name="containerNumber"> <br />
Full Out: <input type="date" name="fullOut" /> <br/>
Empty In: <input type="date" name="emptyIn" /> <br/>
Empty Out <input type="date" name="emptyOut" /> <br/>
Full In: <input type="date" name="fullIn" /> <br/>
Comments: <input type="text" name="comments" /> <br/>
<input type="submit" value="Submit" />
</form>
<div>
<a href="javascript:history.back();">
<span class="categoryLabelText">HOME</span>
</a>
</div>
</body>
</html>
My servlet:
package controller;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UpdateData extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
//Get container data from the JSP page
String container=request.getParameter("containerNumber");
String fullOutDate=request.getParameter("fullOut");
String emptyInDate=request.getParameter("emptyIn");
String emptyOutDate=request.getParameter("emptyOut");
String fullInDate=request.getParameter("fullIn");
String comments=request.getParameter("comments");
//Print the above got values in console
System.out.println("The username is" +container);
System.out.println("\nand the password is" +fullOutDate);
String connectionparams="jdbc:mysql://localhost:3306/rukerttracker";
String db="rukerttracker";
String uname="root";
String psword="Colorado1982";
Connection connection=null;
ResultSet rs;
try {
// Loading the available driver for a Database communication
Class.forName("com.mysql.jdbc.Driver");
//Creating a connection to the required database
connection = DriverManager.getConnection
(connectionparams, uname, psword);
//Add the data into the database
String sql = "insert into containerinventory values (?,?,?,?,?,?)";
try (PreparedStatement prep = connection.prepareStatement(sql)) {
prep.setString(1, container);
prep.setString(2, fullOutDate);
prep.setString(3, emptyInDate);
prep.setString(4, emptyOutDate);
prep.setString(5, fullInDate);
prep.setString(6, comments);
prep.executeUpdate();
}
}catch(Exception E){
System.out.println("The error is=="+E.getMessage());
}
finally{
connection.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if category page is requested
if (userPath.equals("/insertData")) {
// TODO: Implement category request
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
And finally my web.xml page:
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>controller.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/chooseLanguage</url-pattern>
<url-pattern>/viewTracker</url-pattern>
<url-pattern>/editTracker</url-pattern>
<url-pattern>/addToCart</url-pattern>
<url-pattern>/viewCompany</url-pattern>
<url-pattern>/category</url-pattern>
<url-pattern>/updateCart</url-pattern>
<url-pattern>/purchase</url-pattern>
<url-pattern>/viewCart</url-pattern>
<url-pattern>/checkout</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>UpdateData</servlet-name>
<servlet-class>controller.UpdateData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateData</servlet-name>
<url-pattern>/insertData</url-pattern>
</servlet-mapping>
I have two servlets, I don't know if this matters, but I couldn't get the application to work in the controller servlet, so I created the Update Data servlet.
Any help as to why I keep getting this 404 error would be greatly, greatly appreciated. Thanks for taking the time to look at this.
I think in form you are using POST method and your servlet does not have post method. please check it.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{...}
not available.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calling servlet from HTML form, but servlet is never invoked
I'm 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 html code:
<html>
<head>
<title> Sign Up </title>
</head>
<body>
<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>
</body>
</html>
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 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>login</servlet-name>
<servlet-class>Loginservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
I think, mistake is here: <form action="servlet/Loginservlet"
Try this <form action="/<your-app-name>/login"
since in form action you have given servlet/Loginservlet . you should map same in web.xml like
<url-pattern>/servlet/Loginservlet</url-pattern>
or change in the form like
action='login'
you can do any one of above.
try this
<form action="login" method="post" >
you servlet url is
<url-pattern>/login</url-pattern>
When you run your web application for local host then the url like
localhost:8080/test
then the test is the name of your application name which contain your web application into the web dir. Now suppose you create the index file then it will run index file from this only and another page url like
localhost:8080/test/page1.html
now from page1.html you start your login page then the link looks like for servlet is
localhost:8080/test/login
as define the url pattern for specific servlet that url you have to set for calling the specific servlet like above. this url will hide the actual servlet for the client you can set anything in url pattern