When I am running the following code, I am receiving an Servlet 404 error [duplicate] - servlets

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 1 year ago.
I am running the following code, Which is html version, It shows the name and age boxes.
<!-- Main.html -->
<!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>A First page</title>
</head>
<body>
<form action="Thanks.jsp" method="get">
Enter Your Name: <input type="text" name="yourName"><br>
Enter Your Age :<input type="text" name="yourAge"><br>
<input type="submit" value="Sumitting">
</form>
</body>
</html>
but when i run the code of same logic which is a servlet version, it got an error
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Code as follows :
import java.io.IOException;
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.io.*;
#WebServlet("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
public Main() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out = response.getWriter(); //Is added
out.println("<form action=\"http://localhost\" method=\"post\">");
out.println("Enter Your Name: <input type=\"text\" name " +
"= \"yourName=\" </input><br>");
out.println("Enter Your Age : <input " +
"type=\"text\" name = \"yourAge=\" </input>");
out.close();
}
}
Adding web.xml as requested by #RomanC
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="w3.org/2001/XMLSchema-instance"
xmlns="xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="xmlns.jcp.org/xml/ns/javaee
xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>yi.Main</servlet-class>
</servlet>
</web-app>

Make Sure To add all the html elements (Tag) in servlet.
Try this:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter(); //Is added
String htmlTag
= "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(htmlTag
+ "<html>\n"
+ "<head><title>Reg Form</title></head>\n"
+ "<body bgcolor = \"#f0f0f0\">\n"
+ "<h1 align = \"center\">Regform</h1>\n"
+ "<ul>\n"
+ "<form action=\"http://localhost\" method=\"post\">"
+ "Enter Your Name: <input type=\"text\" name = \"yourName\"</input><br><br>\n"
+ "Enter Your Age : <input type=\"text\" name = \"yourAge\" </input>\n"
+ "</ul>\n"
+ "</body>"
+ "</html>");
out.close();
}
As you are using #Webservlet Annotation you don't require need to mention servlet Mapping in web.xml but still if you are looking for xml
<servlet>
<servlet-name>Main</servlet-name>
<servlet-class>test.Main</servlet-class> //test is the Package
</servlet>
<servlet-mapping>
<servlet-name>Main</servlet-name>
<url-pattern>/Main</url-pattern>
</servlet-mapping>
Run the Servlet File you will get the exact URL.(Right Click on Servlet and Run File)
Generally it's like this: "http://localhost:8084/NameofYourApplication/Main"

Related

How to solve this error, HTTP method POST is not supported by this URL?

I have below code:
When I run in Apache tomcat server it gives me this error:
HTTP Status 405 - HTTP method POST is not supported by this URL
Below I mention one admin.html file which I am calling.
It's have post method, and calling [MoviesServlet.java] which have override doPost(). //(I also try in other workspace.)
admin.html
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="fs" method="post">
<h1>Released Movie</h1>
</form>
</body>
MovieServlet.java
public class MovieServlet extends HttpServlet{
private SessionFactory factory = HibernateUtil.getSessionFactory();
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
web.xml
<display-name>hib_servlet_getUpdate</display-name>
<welcome-file-list>
<welcome-file>admin.html</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>MovieServlet</servlet-name>
<url-pattern>/fs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>MovieServlet</servlet-name>
<servlet-class>com.jspiders.getUpdateApp.Servlet.MovieServlet</servlet-class>
</servlet>
Its seems that your MovieServlet.java not shown all, but let me help you if you are using
RequestDispatcher view = request.getRequestDispatcher("index_F.html");
view.forward(request, response);
Do this
response.sendRedirect("index.html");
return;
I wish that this could help you solve the problem.

Cannot get a RequestDispatcher

I've read lots of similar questions and tryed all suggested methods for fixing the problem, however it's unsuccessfully. Now I really don't have any ideas what to do with this (localhost:8080/testWebApp/home):
HTTP Status 500 -
...
exception
java.lang.NullPointerException
test.web.servlet.TestServlet.doGet(TestServlet.java:37)
javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I use maven 3.3.9 and tomcat7 7.0.70-1. My project directory has the following hierarchy:
webApp/
pom.xml
src/
main/
java/
test/web/servlet/
TestServlet.java
webapp/
index.html
WEB-INF/
views/
home.jsp
web.xml
Here is the TestServlet code:
package test.web.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
#WebServlet(urlPatterns = { "/home"})
public class TestServlet extends HttpServlet {
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public TestServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/views/home.jsp");
//The following attempts are unsuccessful too:
//RequestDispatcher dispatcher = request.getRequestDispatcher("/home.jsp");
//RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/home.jsp");
dispatcher.forward(request, response); // error (37 line)
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Here is web.xml code:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_4.dtd">
<web-app>
<welcome-file-list>
<welcome-file>home</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
home.jsp code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body>
<%-- <jsp:include page="main.jsp"></jsp:include> --%>
<h3>Home</h3>
<br><br>
<b>You have the following options:</b>
<ul>
<li>Login</li>
</ul>
</body>
</html>
Some useful lines from pom.xml:
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<server>tomcat-7.0.70-1</server>
<url>http://localhost:8080/manager/text</url>
<path>/testWebApp</path>
</configuration>
</plugin>
Thank you for help!
You cannot get a RequestDispatcher for arbitrary files in your application. The argument to getRequestDispatcher() must be a valid URL path for your application, not a relative file system Location. This is why the dispatcher is null.
If you want to have your JSPs residing under WEB-INF (which is a good idea), then you must create appropriate <servlet-mapping> elements for them.
After deeper investigation of servlet documentation (especially mapping topic) I made some modifications of web.xml and TestServlet.java. It's important that:
The WEB-INF directory is not part of the public document tree of the
application. No file contained in the WEB-INF directory can be served
directly to a client by the container.
In my case views folder is inside WEB-INF (for user access limitation from the outside).
So, it's need to add the following lines (web.xml):
...
<servlet>
<servlet-name>home</servlet-name>
<jsp-file>/WEB-INF/views/home.jsp</jsp-file>
<init-param>
<param-name>home</param-name>
<param-value>Home Page</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/homepg</url-pattern>
</servlet-mapping>
...
And corrected TestServlet.java:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/homepg");
P.S.
Thanks gsl for pointing in the proper direction!
You are dispatching the request to /WEB-INF/views/home.jsp url, but in your WEB-INF/views folder you have Home.jsp.
Just change the file name from Home.jsp to home.jsp and re-deploy the application, it should work fine.
Note: You are dispatching the request to a valid path i.e, /WEB-INF/views/home.jsp

If I refresh a page continuously, does HTTP GET method invokes doGet() method of a servlet every time for every refresh?

I'm trying to post some data using HTTP GET method. Of course, I should choose POST method to post the data.
Here the question is, if I refresh a page continuously, for every refresh, does HTTP GET method invokes doGet() method of a servlet every time?
My understanding is that in case of POST method, every time it invokes doPOst() method of a servlet for every refresh.
My html page looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>user registration</title>
</head>
<body>
<form action="hello" method="get">
User Name: <input type="text" name="userName" /> <br> <br> User Id: <input
type="text" name="userId" /> <br><br>
Select the profession:
<input type="radio" value="Developer" name="proffession">Developer
<input type="radio" value= "Architect" name="profession">Architect<br><br>
Select your location:
<select name="location" multiple size=3>
<option value="Bangalore">Bangalore</option>
<option value="Mangalore">Mangalore</option>
<option value="Udupi">Udupi</option>
<option value="Bhatkal">Bhatkal</option>
</select><br><br>
<input type="submit">
</form>
</body>
</html>
If you are hitting the refresh Button(F5 or Ctrl+R) then deferentially it will hit the application through GET method only, even you mention the POST in form but you are hitting the app page with the URL only.
I don't think the spec is specific on this, but why not have a debug statement in your code and find out? I think that's the fastest way of finding out what happens in your specific setup
Answer is Yes. doGet() method will be invoked for every page refresh in case of GET method as well!
We can debug this scenario by initializing a global variable in init() method and increment the global variable every time either doGet() or doPost() method is called.
Following code demonstrate the same:
package org.shan.jspservlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class XmlServlet extends HttpServlet {
private int hitCount;
public void init()
{
// Reset hit counter.
hitCount = 0;
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String userId = request.getParameter("userId");
response.setContentType("text/html");
hitCount++;
response.getWriter().print(
"<html><body><h1> Hello from XML servlet to " + userName
+ "</h1></body></html>");
response.getWriter().print(
"<html><body><h1> Your id is: " + userId
+ "</h1></body></html>");
response.getWriter().print("hitcount: "+ hitCount);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String userId = request.getParameter("userId");
String profession = request.getParameter("profession");
// String location = request.getParameter("location");
String location[] = request.getParameterValues("location");
response.setContentType("text/html");
response.getWriter().print(
"<html><body><h1> Hello from XML servlet to " + userName
+ "</h1></body></html>");
response.getWriter().print(
"<html><body><h1> Your id is: " + userId
+ "</h1></body></html>");
response.getWriter().print(
"<html><body><h1> Your profession is: " + profession
+ "</h1></body></html>");
response.getWriter().print(
"<html><body><h1> Your at following " + location.length
+ " palces!!!</h1></body></html>");
for (int i = 0; i < location.length; i++)
response.getWriter().print(
"<html><body><h1>" + location[i]
+ "</h1></body></html>");
}
}
You can observe that for very page refresh, the hitCount is getting incremented!!!

net4india server Internal Server Error - Login Page Error

I have uploaded sample project of checking the connectivity of database in net4india.
In eclipse it working fine however when deployed to server through .war file it is not working giving the below error.
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your reques
Please contact the server administrator at webmaster#xxxxxx.in to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log
I am posting the complete code below. Please verify and suggest me the solution.
1) Servlet location is: LoginExample\src\com\journaldev\servlet\LoginServlet.java
2) Web.xml location is: LoginExample\WebContent\WEB-INF
3) Login.html & LoingSuccess.jsp: LoginExample\WebContent
4) jdbc.properties location is: LoginExample\build\classes
[Above locations are as per folderwise]
just to reconfirm, it is working fine in eclipse however it is once I deploy it, it is giving the error. Please help me out.
LoginSuccess.jsp
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!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=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<h3>Hi ABC, Login successful.</h3>
Login Page
</body>
</html>**strong text**
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
jdbc.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://XXX.XX.XXX.XX:3306/abc
user=abc
password=abc
LoginServlet.java
package com.journaldev.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet(
description = "Login Servlet",
urlPatterns = { "/LoginServlet" },
initParams = {
#WebInitParam(name = "user", value = "xyz"),
#WebInitParam(name = "password", value = "xyz")
})
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
//we can create DB connection resource here and set it to Servlet context
if(getServletContext().getInitParameter("dbURL").equals("jdbc:mysql://XXX.XX.XXX.XX:3306/abc") &&
getServletContext().getInitParameter("dbUser").equals("abc") &&
getServletContext().getInitParameter("dbUserPwd").equals("abc"))
getServletContext().setAttribute("DB_Success", "True");
else throw new ServletException("DB Connection error");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
//get servlet config init params
String userID = getServletConfig().getInitParameter("user");
String password = getServletConfig().getInitParameter("password");
//logging example
log("User="+user+"::password="+pwd);
if(userID.equals(user) && password.equals(pwd)){
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
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>LoginExample</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>dbURL</param-name>
<param-value>jdbc:mysql://XXX.XX.XXX.XX:3306/abc</param-value>
</context-param>
<context-param>
<param-name>dbUser</param-name>
<param-value>abc</param-value>
</context-param>
<context-param>
<param-name>dbUserPwd</param-name>
<param-value>abc</param-value>
</context-param>
</web-app>
Thank you very much in advance for your help.

Passing Image and Username to servlet

I am passing an fileUpload and name of the user to the servlet.I am able to upload a file but not the username as i am fetching the value of the user by requst.getparemeter("userName") but it is giving me null value.I Checked everything but not able to unserstand what exactly the problem..
<html>
<head>
<title>AJAX jquery file Upload in Java Web Application</title>
<script src="js/Jquery-1.9.1.js"></script>
<script src="js/jquery.ajaxfileupload.js"></script>
<script language="Javascript">
function validateName(){
var empName=document.getElementById("userName").value;
alert(empName);
}
</script>
<style type="text/css">
.centered{
width:100%;
margin-left:auto;
margin-right:auto;
text-align:center;
}
</style>
</head>
<body>
<form action="UploadFile" method="post" enctype="multipart/form-data" >
<div class="centered">
<h2 style="text-align:center;">Using AJAX, jquery and Servlet to upload File in Java Web Application</h2>
<input id="userName" name="userName" type="text" placeholder="minutes"/>
<input type="file" name="file" /><br/>
<input type="submit" value="submit" onclick="validateName()"/>
</div>
</form>
</body>
</html>
package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Iterator;
import javax.servlet.http.*;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadFile()
{
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println( "Save Path in Database:");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String empName=request.getParameter("userName");
System.out.print("here the name of the file is "+empName);
try{
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
empName=request.getParameter("empName");
if (!item.isFormField()) {
String fileName = item.getName();
System.out.print("here the name of the file is "+fileName);
String fileSplit[]=fileName.split("\\.");
System.out.println("the length of the file"+fileSplit.length);
String fileDatabasePath=empName+"."+fileSplit[1];
System.out.println("Name of the file is "+fileDatabasePath);
String fileBase = getServletContext().getInitParameter("IMAGE_FILEBASE");
File filePath = new File(fileBase + File.separator);
File uploadedFile = new File(filePath + "/" + fileName);
item.write(uploadedFile);
// Save the below path in database
String url = getServletContext().getInitParameter("imgsd") + fileName ;
String url1="E:/Suraj/AjaxServletFileUpload/WebContent/images/"+fileDatabasePath;
System.out.println( "Save Path in Database: "+url1);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>UploadFile</servlet-name>
<servlet-class>com.UploadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadFile</servlet-name>
<url-pattern>/UploadFile</url-pattern>
</servlet-mapping>
<context-param>
<param-name>IMAGE_FILEBASE</param-name>
<param-value>E:/Suraj/AjaxServletFileUpload/WebContent/images/ </param-value>
</context-param>
<context-param>
<param-name>imgsd</param-name>
<param-value>http://localhost:8080/AjaxServletFileUpload/</param-value>
</context-param>
</web-app>
I am not able to get any error in console.I am a null value in my console. I am passing an fileUpload and name of the user to the servlet.I am able to upload a file but not the username as i am fetching the value of the user by requst.getparemeter("userName") but it is giving me null value .
You are using Apache Commons File Upload for the file but still trying to use request.getParameter for the username. You can't do that. If your form is "multipart/form-data" then you have to use Apache Commons File Upload for all the parameters in the form since request.getParameter will not work.

Resources