Http status 404 -/the requested resource is not available [duplicate] - java

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 7 years ago.
I have written a servlet program for login page ..am using tomcat server...after i run on the server am getting the above mentioned error...
Below is my servlet code.
package demo;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
static private String dbUrl="jdbc:mysql://localhost:3306/employee";
static private String dbUn="root";
static private String dbPwd="root";
static private Connection ConObj;
static private Statement StmtObj;
static private ResultSet RsObj;
public void service(HttpServletRequest request,HttpServletResponse response)throws IOException
{
try {
Class.forName("com.mysql.jdbc.driver");
ConObj=DriverManager.getConnection(dbUrl, dbUn, dbPwd);
StmtObj=ConObj.createStatement();
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.write("<html><body>");
out.write("<h2>");
String ActLogName=request.getParameter("Logname");
String ActPwd=request.getParameter("Pwd");
String SqlQuery="select * from users where username='"+ActLogName+"' and password='"+ActPwd+"'";
RsObj=StmtObj.executeQuery(SqlQuery);
if(RsObj.next()==true)
{
String ExpLogName=RsObj.getString("username");
String ExpPwd=RsObj.getString("password");
if(ActLogName.equals(ExpLogName)&& ActPwd.equals(ExpPwd))
{
out.write("Login Success");
}
}
else
{
out.write("Login Failed");
}
out.write("</h2>");
out.write("</body></html>");
}
catch (ClassNotFoundException|SQLException exp) {
exp.printStackTrace();
}
finally{
try {
RsObj.close();
StmtObj.close();
ConObj.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Below is my html code
<!DOCTYPE html>
<html>
<head>
<title>login page</title>
</head>
<body>
<form action="http://localhost:8080/FlipKart/loginpage">
LoginName :<input type="text" name="Logname"><br>
Password :<input type="password" name="Pwd"><br>
<input type="submit" value="Login">
<input type="button" value="cancel">
</form>
</body>
</html>
Below is my web.xml code
<web-app>
<servlet>
<servlet-name>loginserv</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginserv</servlet-name>
<url-pattern>/loginpage</url-pattern>]
</servlet-mapping>
</web-app>
Can somebody help me to the resolve this issue..
Thanks in advance..:)

You are overriding the wrong method, override doPost() instead and modify your form to include method="post" like this :
public void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException
{
//...
}
and this
<form action="http://localhost:8080/FlipKart/loginpage" method="post">
Also, if you don't want to always include the full path of the context manually, you can read this.

Did you restart the server after making the package name change? Tomcat reads web.xml only on startup.
Besides, make sure your classes are under webapps/WEB-INF/classes folder.

It looks to me as though your application context needs to be changed. Perhaps it is being set to root. So it is not hitting /FlipKart
Look at this stackoverflow link for more information on setting the application context.
That is for tomcat 7. I know you can edit the META-INF/context.xml for previous versions. If you don't have that folder and file just create it.
EDIT
Check your tomcat log to see where it is getting deployed or if something caused it to not get deployed at all. If you're running from an IDE, you may be able to see from the console.

Wrong reference to class in web.xml
Use full name of Class with package name
<servlet>
<servlet-name>loginserv</servlet-name>
<servlet-class>demo.LoginServlet</servlet-class>
</servlet>

Related

how can i resolve this : The method received in the request-line is known by the origin server but not supported by the target resource

I m receiving error as "HTTP Status 405 – Method Not Allowed" when trying to execute the below query, I am not sure what I can do to resolve this.
Also, someone could suggest me where can I get flight APIs for free for testing.
package com.Gmaps.web.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Gmaps.web.DAO.GmapsDAOLayer;
import com.Gmaps.web.Model.GmapsModel;
/**
* Servlet implementation class GmUserData
*/
public class GmUserData extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response, String originAutocomplete) throws ServletException, IOException//, NumberFormatException
{
// String uid = request.getParameter("userid");
// GmapsDAOLayer dao = new GmapsDAOLayer();
// GmapsModel model = dao.getUser(uid);
RequestDispatcher rd = request.getRequestDispatcher("UserPage.jsp");
rd.forward(request, response);
// float orgin = Float.parseFloat(request.getParameter("desti"));
String orgin = request.getParameter("place");
GmapsDAOLayer dao = new GmapsDAOLayer();
GmapsModel model = dao.getUser(orgin);
System.out.println("origin: "+orgin);
}
}
And here is my index.html
<html>
<body>
<h2>Hello World!</h2>
<form action="getuserdata" method="get">
<input type= "text" name="userid"><br>
<input type= "text" name="firstname"><br>
<input type="submit">
</form>
</body>
</html>
Here is my web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>GmUserData</servlet-name>
<servlet-class>com.Gmaps.web.controller.GmUserData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GmUserData</servlet-name>
<url-pattern>/getuserdata</url-pattern>
</servlet-mapping>
</web-app>
Help would be much appreciated!
try with this <form action="/getuserdata" or just this action="GmUserData"

Tomcat server shows a 404 error when using Servlet [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
I'm trying to write a simple servlet and it's not working and I can't figure out why. The code is very simple but somehow it's not working, and it's driving me nuts.
Here's the index.jsp file:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaEE</title>
</head>
<body>
<h1>Hello JavaEE World</h1>
<form action="helloServlet" method="post">
Enter a number: <input type="text" name="number" size="5" />
<input type="submit" value="Call Servlet" />
</form>
</body>
</html>
And here's the servlet file:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("helloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter write = response.getWriter();
write.println("OMG");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String number = request.getParameter("number");
PrintWriter write = response.getWriter();
write.println("Number: " + number);
write.flush();
}
}
But somehow it's not working. I provided the pictures below if anyone care.
Servlet File
index.jsp File
index.jsp on Browser
Error image when submitting form
Pom.xml if anyone care
Try changing the annotation to this:
#WebServlet(name = "helloServlet", urlPatterns = { "/helloServlet" })

404 Apache tomcat in a Java project

So this is my project:
Where Registro.java is:
package Ejer2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.*;
#SuppressWarnings("deprecation")
#WebServlet(urlPatterns="/Registro")
public class Registro extends HttpServlet implements SingleThreadModel{
private static final long serialVersionUID = 1L;
public Registro() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session=req.getSession(true);
Usuario miuser=(Usuario)session.getValue(session.getId());
if(miuser==null){
miuser=new Usuario(req.getParameter("user"),req.getParameter("password"));
session.putValue(session.getId(),miuser);
}
res.setContentType("text/html");
String user=req.getParameter("user");
//String pass = req.getParameter("pass");
PrintWriter toClient = res.getWriter();
toClient.println("<html>");
toClient.println("<title>REGISTRO REALIZADO</title>");
toClient.println("Usuario "+user+" registrado con exito");
toClient.println("</html>");
toClient.close();
}
}
And registro.html is:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registro</title>
</head>
<body>
<form action="/Ejer2/Registro" method="POST">
<input type=hidden name=registro value=resultadoRegistro>
<BR><BR>Username: <input type=text name=user>
<BR><BR>Password: <input type=password name=pass>
<BR><BR><input type=submit value="Enviar"><input type=reset>
</form>
</body>
</html>
When I run registro.html everything goes as expected:
But when I enter an username and a password it doesnt work:
4
It seems as if it doesnt find the Registro.java. I have tried changing the action="/Ejer2/Registro" to many other things like just /Registro orthe full http://... but still doesnt work.
This is my web.xml:
What can be the problem?
I guess you are missing servlet mapping in your web.xml. You need to register your servlet in web.xml (open web.xml file and at the bottom change tab to see actual source code not designer) add following code and you should be good to go
<servlet>
<servlet-name>RegistroServlet</servlet-name>
<servlet-class>Ejer2.Registro</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistroServlet</servlet-name>
<url-pattern>/Registro</url-pattern>
</servlet-mapping>
I also suggest you to step back and start with basic java before attemping to write web application. You have several newbie issueses with your code:
1) name of packages should start with lower case !
2) also url mapping should be with lower case like this /registro
in your form action change url to match urlmapping. In your case it's
form action="/Registro" ...
Ejer2 is name of package it has nothing to do with url mapping. Hope it helps to resolve your problem

Simple authentication using Servlet and Mysql

I am trying to create Simple login page. Here's my code:
Servlet :
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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("/MySQLConnect")
public class MySQLConnect extends HttpServlet {
private static final long serialVersionUID = 1L;
//do post method calling
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
String pass = request.getParameter("pass");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javademo", "root", "admin");
//prepared statement for calling query
PreparedStatement pst = conn.prepareStatement("Select user,pass from login where user=? and pass=?");
pst.setString(1, user);
pst.setString(2, pass);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
out.println("Correct login credentials");
}
else {
out.println("Incorrect login credentials");
}
} catch (Exception e) {
e.printStackTrace();
}
finally{}
}
}
index.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="MySQLConnect">
UserName :<input type="text" name="user" /><br/><br/>
Password :<input type="password" name="pass" /><br/><br/>
<input type="submit" value="Login" />
</form>
</body>
</html>
Web.xml
<display-name>AuthenticationUsingMySQL</display-name>
<servlet>
<servlet-name>MySQLConnect</servlet-name>
<servlet-class>MySQLConnect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MySQLConnect</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
I am trying to open the page using
http://localhost:8080/AuthenticationUsingMySQL/Login
But it is showing HTTP Status 405 - HTTP method GET is not supported by this URL
When you go to http://localhost:8080/AuthenticationUsingMySQL/Login on your browser you send GET request to your servlet which doesn't provide GET method.
Just go to http://localhost:8080/AuthenticationUsingMySQL/ and it will work.
If you are trying to open that link in your browser then that error makes sense. You need to use a tool like Fiddler, or set up a javascript test method, to test your code. It looks like you are constructing a POST method in your code. Web browsers, by default, use GET to access web resources, thus the need for a different tool which is able to perform a POST. Otherwise you will need to modify your code so it accepts GET requests.
You can't directly use te URL in the Browser as your webservlet supports POST request, so try to POST the request from JSP only or use the tools like POSTMAN, SOAPUI.

How to receive a file type parameter from html/jsp into a servlet

I want to take image as input into my web page. I have written following code in my jsp for this :-
<form action="Upload" method="get" enctype="multipart/form-data">
Image<input type="file" name="image" accept="image/jpg" id="image">
<input type="submit" value="submit">
</form>
but I do not know how to receive the "image" parameter in a servlet that is whether it should be a input stream or file, I have no idea. Please tell me the correct code for it.
Use Apache Commons File.
The form method must be method="POST".
Then in your web.xml you need to map the request to your servlet:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.stackoverflow.MyServletClass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/Upload</url-pattern>
</servlet-mapping>
Then you write a class that extends HttpServlet and implement to doPost() method.
well, just go here: http://www.codejava.net/java-ee/servlet/apache-commons-fileupload-example-with-servlet-and-jsp
After painstaking efforts and google search I found a solution to my problem. A page from Stackoverflow helped very much. First I changed the get method of my form to post like this
<form action="Upload" method="post" enctype="multipart/form-data">
Image<input type="file" name="image" id="image" accept="image/jpg">
<input type="submit" value="submit">
</form>
Then I wrote the following servlet code. We accept the <input type="file">data as Part data in servlet. Then we convert it to input stream. The input stream then can be saved in database. Here is my Servlet:-
package controller;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import model.ConnectionManager;
#MultipartConfig(location="/tmp", fileSizeThreshold=1048576, maxFileSize=20848820, maxRequestSize=418018841)
public class Upload extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part filePart=request.getPart("image");`// Retrieves <input type="file" name="image">`
String filePath = filePart.getSubmittedFileName();//Retrieves complete file name with path and directories
Path p = Paths.get(filePath); //creates a Path object
String fileName = p.getFileName().toString();//Retrieves file name from Path object
InputStream fileContent = filePart.getInputStream();//converts Part data to input stream
Connection conn=ConnectionManager.getConnection();
int len=(int) filePart.getSize();
String query = ("insert into IMAGETABLE(ID,NAME,LENGTH,IMAGE) VALUES(?,?,?,?)");
try {
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setInt(1, 5);
pstmt.setString(2, fileName);
pstmt.setInt(3, len);
pstmt.setBinaryStream(4, fileContent, len);
success=pstmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("Error : "+ex.getMessage());
}finally{
try{
if(fileContent!=null)fileContent.close();
if(conn!=null)conn.close();
}catch(IOException | SQLException ex){
System.out.println("Error : "+ex.getMessage());
}
}
}
}
After execution, it does the job successfully. We accept the image from user and save it in database. Hope this solution will help all :)

Categories

Resources