My code is to use java servlets and JDBC to store and retrieve the information from a database. There is no error in the IDE the program is running but, the rows aren't inserted into the database and an error occurred in the firefox browser.
The following code is from the SERVLET file
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class ServletRegister extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter("text/html");
String uname = req.getParameter("uname");
String passwd = req.getParameter("passwd");
String email = req.getParameter("email");
int phno = Integer.parseInt(req.getParameter("phno"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hack","root","");
PreparedStatement ps = con.prepareStatement("insert into student values(?,?,?,?)");
ps.setString(1,uname);
ps.setString(2,passwd);
ps.setString(3, email);
ps.setInt(4, phno);
int i = ps.executeUpdate();
if(i>0)
out.print("Registerd Successfully");
out.close();
}catch(Exception e) {
System.out.println(e);
}
}
}
The following code is from HTML file
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<form action="register">
<table>
<tr>
<td>Enter User Name: <input type="text" name="uname"> </td>
</tr>
<tr>
<td>Enter Password: <input type="password" name="passwd"> </td>
</tr>
<tr>
<td>Enter E-mail: <input type="email" name="email"> </td>
</tr>
<tr>
<td>Enter Phone.no: <input type="number" name="phno" min="6000000000" max="9999999999"></td>
</tr>
<tr>
<td><input type="submit"> <input type="reset"></td>
</tr>
</table>
</form>
</body>
</html>
The following code is from web.xml file
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.hacker.ServletRegister</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
The Error is:
Error obtained in firefox browser
You can use Postman to send a POST request to your server, or change doPost to doGet
In HTML file tag you did not mention the method= "post" So its taking the value by default "get" request.
i have my project structure as follows
here is my jsp
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<h2>Binary Search</h2>
<form action ="SearchServlet" method = "post">
<label>Enter size of the list</label>
<input type="text" name ="listSize"><br><br>
<label>Here is your Generated list...!!!</label><br><br>
<textarea rows="10" cols="50"><c:out value="${list}"/> </textarea><br><br>
<label>Enter number to search in the list</label>
<input type="text" name ="searchNumber"><br><br>
<button type="submit" name="button" value="generate">Generate List</button>
<button type="submit" name="button" value="search">Search Number</button>
<button type="reset" name="button" value="reset">Reset</button>
</form>
</body>
</html>
so when i click generate list button i am expecting it to redirect to my servlet and do my logic and return with arraylist to show it in text area.
here is my servlet
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SearchServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
GenerateList newList = new GenerateList();
SearchList searchList = new SearchList();
String button = request.getParameter("button");
ArrayList<Integer> newGeneratedList = new ArrayList<Integer>();
if ("generate".equals(button)) {
newGeneratedList = newList.GeneratedList(Integer.parseInt(request.getParameter("listSize")));
request.setAttribute("list",newGeneratedList);
response.sendRedirect("index.jsp");
} else if ("search".equals(button)) {
}
//doGet(request, response);
}
}
but i get 404 not found error when click this.i have searched for hours and cannot find why,and i am still a beginner of servlet.any leads/help would be great.
here is my web.xml also
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>SearchServlet</servlet-name>
<display-name>SearchServlet</display-name>
<description></description>
<servlet-class>SearchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BinarySearchServlet</servlet-name>
<url-pattern>/binarySearchServlet</url-pattern>
</servlet-mapping>
You can use request dispatcher in place of sendRedirect in your servlet.
Try this:
RequestDispatcher rd=request.getRequestDispatcher(jspName);
rd.forward(request, response);
In parameter write your JSP name from where you have call this servlet.
forward function will redirect to you at your desired page.
this is structure of projectThis servlet is placed in servlets package
package Servlets;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class OpenAccountServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String firstName=request.getParameter("firstname");
String lastName=request.getParameter("lastname");
String fatherName=request.getParameter("fathername");
String webPage=null;
webPage+="<html>";
webPage+="<head>";
webPage+="</head>";
webPage+="<body>";
webPage+=firstName;
webPage+=lastName;
webPage+=fatherName;
webPage+="</body>";
webPage+="</html>";
out.println(webPage);
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
doGet(request,response);
}
public void destroy(){
}
}
this is jsp page which i am using for accepting data from user.
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="openaccount.do">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="firstname" value=""></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastname" value=""></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit">
<input type="button" name="cancel" value="Cancel">
</td>
</tr>
</table>
</form>
</body>
</html>
and this is my web.xml file
<?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>Open_Account_controller</servlet-name>
<servlet-class>Servlets.OpenAccountServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Open_Account_controller</servlet-name>
<url-pattern>/openaccount.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
and whenever i am trying to run this, 404 error. i am using intelliJ idea IDE for development, and i am using 64 bit tomcat.
Try <form method="post" action="../openaccount.do">
When you remove the leading ../ It would try to load the url relative to current directory.
Better yet use a more generic form like:
action="${pageContext.request.contextPath}/openaccount.do"
This question already has answers here:
How to call servlet class from HTML form
(2 answers)
Closed 7 years ago.
How to call servlet file from html.I tried but when i click on submit its not taking any action,I am not getting any error also. and i want to submit data in database.action event is not working.Please help me
HTML code
<form name="form" method="post" action="NewServlet" >
<label for='name' ><font size="2">Your Full Name*: </label><br/>
<input type='text' name='name' id='name' maxlength="50" style="height:30px; width :250;" placeholder="Enter Full Name"/><br/><br/>
<label for='email' >Email Address*:</label><br/>
<input type='text' name='email' id='email' maxlength="50" style="height:30px; width :250;" placeholder="Enter your Email"/><br/><br/>
<label for='phone' >Phone Number*:</label><br/>
<input type='text' name='phone' id='phone' maxlength="15" style="height:30px; width :250;" placeholder="Enter Phone Number"/><br/><br/>
<label for='Reason' >Reason*:</label><br/>
<select name="reason" style="height:30px; width :250;">
<option>Select</option>
<option>Enquiry</option>
<option>Complain</option>
<option>Order</option>
</select>
</br>
</br>
</br>
<label for='message' >Address Or Message:</label><br/>
<textarea style="height:100px; width :400;" name='message' id='message' placeholder="Enter Address or Message"></textarea></p>
</b>
</size>
<%--
<input type='submit' name='btnSubmit' value="Submit"/>
--%>
<img src="Image/submit1.png" style="width:150px; height:70px;top:50%px; " onmouseover="this.src='Image/submit2.png'" onmouseout="this.src='Image/submit1.png'"/>
</form>
Servlet code
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String driver= "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url="jdbc:sqlserver://localhost:1433;databaseName=wristwatch; username=sa; password=abc#123;";
try {
//int id=Integer.parseInt(request.getParameter("txt_id"));
String nm=request.getParameter("name");
String email=request.getParameter("email");
int phone=Integer.parseInt(request.getParameter("phone"));
String reason=request.getParameter("reason");
String add=request.getParameter("Address");
Class.forName(driver);
Connection c=DriverManager.getConnection(url);
out.println("Data Inserted");
}
catch(Exception e)
{
System.out.print(e);
}
finally {
out.close();
}
}
web.xml
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
Change the processRequest(...){...} to doPost(...){...} in servlet.
This link might make you clear.
ProcessRequest Method
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I have written a Java servlet program and run it through local Tomcat 7, But it was showing following error :
HTTP Status 404 - /skypark/registration
type Status report
message /skypark/registration
description The requested resource is not available.
Apache Tomcat/7.0.33
I don't know what was the reason for it
my Html page is
<html>
<head>
<title>
User registration
</title>
</head>
<body>
<form action="registration" method="post">
<center>
<h2><b>Skypark User Registration</b></h2>
<table border="0">
<tr><td>
First Name
</td><td>
<input type="text" name="fname"/></br>
</td></tr><tr><td>
Last Name
</td><td>
<input type="text" name="lname"/></br>
</td></tr><tr><td>
UserName
</td><td>
<input type="text" name="uname"></br>
</td></tr><tr><td>
Enter Password
</td><td>
<input type="password" name="pass"></br>
</td></tr><tr><td>
Re-Type Password
</td><td>
<input type="password" name="pass1"></br>
</td></tr><tr><td>
Enter Email ID
</td><td>
<input type="email" name="email1"></br>
</td></tr><tr><td>
Phone Number
</td><td>
<input type="number" name="phone">
</td></tr><tr><td>
Gender<br>
</td></tr><tr><td>
<input type="radio" name="gender" value="Male">Male</input></br>
</td></tr><tr><td>
<input type="radio" name="gender" value="Female">Female</input></br>
</td></tr><tr><td>
Enter Your Date of Birth<br>
</td><td>
<Table Border=0>
<tr>
<td>
Date
</td>
<td>Month</td>
<td>Year</td>
</tr><tr>
<td> <select name="date">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
.
.
.
have some code
.
.
.
</table>
<input type="submit" value="Submit"></br>
</center>
</form>
</body>
</html>
My servlet is :
package skypark;
import skypark.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Registration extends HttpServlet
{
public static Connection prepareConnection()throws ClassNotFoundException,SQLException
{
String dcn="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:#JamesPJ-PC:1521:skypark";
String usname="system";
String pass="tiger";
Class.forName(dcn);
return DriverManager.getConnection(url,usname,pass);
}
public void doPost(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
{
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
try
{
String phone1,uname,fname,lname,dob,address,city,state,country,pin,email,password,gender,lang,qual,relegion,privacy,hobbies,fav;
uname=req.getParameter("uname");
fname=req.getParameter("fname");
lname=req.getParameter("lname");
dob=req.getParameter("date");
address=req.getParameter("address");
city=req.getParameter("city");
state=req.getParameter("state");
country=req.getParameter("country");
pin=req.getParameter("pin");
email=req.getParameter("email1");
password=req.getParameter("password");
gender=req.getParameter("gender");
phone1=req.getParameter("phone");
lang="";
qual="";
relegion="";
privacy="";
hobbies="";
fav="";
int phone=Integer.parseInt(phone1);
Connection con=prepareConnection();
String Query="Insert into regdetails values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(Query);
ps.setString(1,uname);
ps.setString(2,fname);
ps.setString(3,lname);
ps.setString(4,dob);
ps.setString(5,address);
ps.setString(6,city);
ps.setString(7,state);
ps.setString(8,country);
ps.setString(9,pin);
ps.setString(10,lang);
ps.setString(11,qual);
ps.setString(12,relegion);
ps.setString(13,privacy);
ps.setString(14,hobbies);
ps.setString(15,fav);
ps.setString(16,gender);
int c=ps.executeUpdate();
String query="insert into passmanager values(?,?,?,?)";
PreparedStatement ps1=con.prepareStatement(query);
ps1.setString(1,uname);
ps1.setString(2,password);
ps1.setString(3,email);
ps1.setInt(4,phone);
int i=ps1.executeUpdate();
if(c==1||c==Statement.SUCCESS_NO_INFO && i==1||i==Statement.SUCCESS_NO_INFO)
{
out.println("<html><head><title>Login</title></head><body>");
out.println("<center><h2>Skypark.com</h2>");
out.println("<table border=0><tr>");
out.println("<td>UserName/E-Mail</td>");
out.println("<form action=login method=post");
out.println("<td><input type=text name=uname></td>");
out.println("</tr><tr><td>Password</td>");
out.println("<td><input type=password name=pass></td></tr></table>");
out.println("<input type=submit value=Login>");
out.println("</form></body></html>");
}
else
{
out.println("<html><head><title>Error!</title></head><body>");
out.println("<center><b>Given details are incorrect</b>");
out.println(" Please try again</center></body></html>");
RequestDispatcher rd=req.getRequestDispatcher("registration.html");
rd.include(req,resp);
return;
}
}
catch(Exception e)
{
out.println("<html><head><title>Error!</title><body>");
out.println("<b><i>Unable to process try after some time</i></b>");
out.println("</body></html>");
RequestDispatcher rd=req.getRequestDispatcher("registration.html");
rd.include(req,resp);
return;
}
out.flush();
out.close();
}
}
And the web.xml file is
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="3.0"
metadata-complete="true">
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>skypark.Registration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/registration</url-pattern>
</servlet-mapping>
</web-app>
This i kept in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\skypark\WEB_INF\web.xml
and servlet class in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\skypark\WEB_INF\classes\skypark
and registration.html in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\skypark\
if any mistake in this makes above error means please help me.Thanks in advance....
I think the problem is with this two line :
<form action="registration" method="post"> in your html page.
<url-pattern>/Registration</url-pattern> in your web.xml
Your action is set to registration and your url pattern expects Registration (Note that capital R and small r ).
Just try changing them (both same ) and it should work
Try putting a request mapping to the method you want to be called by the request. If, for example, you use Spring framework, you need to set your servlet url-pattern in web.xml to htm in your case, then return the name of your html file.
#RequestMapping(value ="/registration",method = RequestMethod.GET)
public String render(Model model, HttpServletRequest request, HttpServletResponse response) {
{
--------------- compute ----
return "registration";
}
If you will put a request to /registration, the server will compute the method mapped to it then search for "registration" (returned value) to show.
Hope it helps !