Why my servlet doesn't run? [duplicate] - java

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
Here is my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Beer Selection Page</title>
</head>
<body >
<form method = "post"
action = "SelectBeer.do">
Select beer Characteristics<br/>
Color:
<select name="color" size="1">
<option>light
<option>amber
<option>brown
<option>dark
</select>
<br/><br/>
<center><input type="SUBMIT"></center>
</form>
</body>
</html>
Here is my 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>Test2</display-name>
<servlet>
<servlet-name>Ch3 beer</servlet-name>
<servlet-class>BeerSelect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ch3 beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
</web-app>
And here, is my servlet:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
/**
* Servlet implementation class BeerSelect
*/
public class BeerSelect extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public BeerSelect() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text.html");
PrintWriter out = response.getWriter();
out.println("Beer Selection Advice");
String c= request.getParameter("color");
out.println("Got beer color " + c);
}
}
And when I run it on the server, the response is
HTTP Status 404 - /Test2/
type Status report
message /Test2/
description The requested resource is not available.
Test2
.....Java Resources
...................src
......................default package
.....................................BeerSelect.java
.....WebContent
...............META-INF
...............WEB-INF
......................lib
......................web.xml
...............Beer.html
Also, does anybody know why the returned String "c" in the servlet is null??

The message: The requested resource is not available. is telling you that the resource (file) you tried to get via the URL /Test2/ is not available, that is, the server can't give it to you. Most probably it wasn't mapped.
In the context of your web application Test2 your servlet is mapped to:
/SelectBeer.do
That means, that outside the context of your web application your access URL should be something like:
http://server:port/Test2/SelectBeer.do
Assuming your HTML file is located in the root of your application context, you should be able to reference the servlet like this:
<form method = "post" action = "SelectBeer.do"> ...
since it is mapped relatively to the root, or using an absolute path like this:
<form method = "post" action = "/Test2/SelectBeer.do"> ...
Since you don't seem to have an index.html (or any welcome file configured in your web.xml), if you try accessing the root of your webapp Test2/ without explicitly including the file name, you will get a 404 error. To open the file correctly you will need to use:
http://server:port/Test2/Beer.html

Just change to url patter to <url-pattern>/Test2/*</url-pattern>
You create another pattern and you request a diffrent request.. You also can use wildcard *. Not.
Once you create a call the url pattern is searched over the pattern.. For this example above you need to put the url pattern in your request
localhost:8080/Test2/
Something like that will be match to the url pattern

Related

The requested resource is not available in Tomcat 8.0.2 [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
wel.html file
<html>
<head><title>Welcome Page</title></head>
<body>
Welcome HTML Page
<form action="Welcome" method="post">
<input type="submit" value="submit"/>
</form>
</body>
</html>
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>S1</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>S1</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>
Welcome.java Servlet file
import java.io.*;
import javax.servlet.*;
public class Welcome implements Servlet
{
ServletConfig config;
public void init(javax.servlet.ServletConfig config) throws javax.servlet.ServletException
{
System.out.println("...init...");
this.config=config;
}
public javax.servlet.ServletConfig getServletConfig()
{
System.out.println("...getServletConfig...");
return config;
}
public void service(javax.servlet.ServletRequest req,javax.servlet.ServletResponse res) throws javax.servlet.ServletException,java.io.IOException
{
System.out.println("...service...");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Welcome</h1>");
out.println("</body>");
out.println("</html>");
}
public java.lang.String getServletInfo()
{
System.out.println("...getServletInfo...");
return "";
}
public void destroy()
{
System.out.println("...destroy...");
}
}
Directory Structure
C:\apache-tomcat-8.0.22\webapps\MyApp\WEB-INF\classes
web.xml in WEB-INF
compiled java class in classes folder
wel.html in MyApp folder
When I deploy the project,its working upto wel.html.But after clicking submit button,the following error page is getting displayed
HTTP Status 404 - /MyApp/Welcome
type Status report
message /MyApp/Welcome
description The requested resource is not available.
Apache Tomcat/8.0.22
I am at a loss as to what is causing this problem.Please help me.
Thanks in advance.
I also copied and pasted to a new WebApp Project in Netbeans and everything works fine. Make sure that you made no typos:
do you have web.xml and not, e.g. web.xml.xml file?
do you have Welcome.class file in WEB-INF\classes folder?
Except for that, you don't use your imports consistently. When you invoke import at the beginning, just use ServletConfig config instead javax.servlet.ServletConfig config over and over again.
It appears to work just fine for me, Tomcat 8.0.23 and Oracle JDK 1.8.0_45, using copied and pasted code from your post. Guesses at your problem would be your class is not being deployed or that it is someplace other than the default package. Try adding it to a package and modify your servlet mapping to reflect the qualified class name.

Calling servlet from JSP [duplicate]

This question already has answers here:
Calling a servlet from JSP file on page load
(4 answers)
Closed 2 years ago.
Basically, I want to display the products in an ArrayList on a JSP page. I have done that in the servlet code. But theres no output.
Also Do I have to place products.jsp in the /WEB-INF folder? When I do that, I get a requested not resource error.
My Servlet Code (InventoryServlet.java)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
List<Product> products = new ArrayList<Product>();
products = Inventory.populateProducts(); // Obtain all products.
request.setAttribute("products", products); // Store products in request scope.
request.getRequestDispatcher("/products.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table.
} catch (Exception ex) {
throw new ServletException("Retrieving products failed!", ex);
}
}
My JSP Page (products.jsp)
<h2>List of Products</h2>
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.Description}</td>
<td>${product.UnitPrice}</td>
</tr>
</c:forEach>
</table>
Web.xml
<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>Inventory</servlet-name>
<servlet-class>com.ShoppingCart.InventoryServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Inventory</servlet-name>
<url-pattern>/products</url-pattern>
</servlet-mapping>
</web-app>
You need to open the page by requesting the servlet URL instead of the JSP URL. This will call the doGet() method.
Placing JSP in /WEB-INF effectively prevents the enduser from directly opening it without involvement of the doGet() method of the servlet. Files in /WEB-INF are namely not public accessible. So if the preprocessing of the servlet is mandatory, then you need to do so. Put the JSP in /WEB-INF folder and change the requestdispatcher to point to it.
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
But you need to change all existing links to point to the servlet URL instead of the JSP URL.
See also:
Servlets info page
Here is a diagram for web application folder structure. No need to place your JSPs under WEB-INF.
debug or put print statememnts in your Servlet to make sure that the arraylist has elements in it.
Right-click on your browser and view page source. Is there anything generated at all?
the difference between put a jsp file under WebRoot and WEB-INF is:
if you put under WebRoot, user can access your jsp file using the URL on the address bar of browser; if you put under WEB-INF, user can't access the file because it is hidden from public.
The only way you can access that is through Servlet using forward or redirect.

Customize <url-pattern> to link a Form to a FormAction

First, I am a newbie in Java/J2EE development. So, please be indulgent with my leak of vocabulary (but feel free to correct me ;)
Here is my first problem :
I built a first form (named form1) in a .jsp page :
<form name="form1" action="formaction1.do" method="get">
I redirect the result of my form to a FormAction1 java class :
<servlet>
<servlet-class>com.servlet.myproject.FormAction1</servlet-class>
<servlet-name>FormAction1</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>FormAction1</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Here is my FormAction1 java class :
public class FormAction1 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
request.getRequestDispatcher("formaction1.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
This is working fine.
Now, I'd like to create another form, named form2, and link it to FormAction2.
However, FormAction1 receives every .do request !
I tried to customize my <url-pattern> by writing :
<url-pattern>formaction1.do</url-pattern>
I guess it would've been too easy :D
Tomcat doesn't like it : I get a 404 error on every page of my project.
So, do you have any solution ?
Just a bonus question :
What's the point to use a class like FormAction1, rewrite doGet method, while I can just write :
<form name="form1" action="anotherFile.jsp" method="get">
and recover infos with a request.getParameter() in anotherFile.jsp ?
doesn't url-pattern requires a match starting from the beginning, in that case
<url-pattern>/formaction1.do</url-pattern>

unable to connect to server (error-404) [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I created a sample Dynamic Web Project in Eclipse, but when I am running my project with Tomcat 5.5 i am getting this error:
HTTP Status 404 - /greetingservlet/
type Status report
message /greetingservlet/
description The requested resource (/greetingservlet/) is not available.
My HTML/JSP source code is:
<!DOCTYPE greeting SYSTEM "hello.dtd">
<html>
<title>Insert title here</title>
<body BGCOLOR="YELLOW">
<center>
<h1>USER NAME ENTRY SREEN</h1>
<form action="./greet">
user name<input type="text" name="t1">
<br><br>
<input type="submit" value="get message">
</form>
</center>
</body>
</html>
My servlet source code is:
import java.io.*;
import javax.servlet.*;
/**
* Servlet implementation class Greetingservlt
*/
public class Greetingservlt extends GenericServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void service(ServletRequest request,ServletResponse response) throws ServletException,
IOException
{
String name=request.getParameter("t1");
response.setContentType("text");
PrintWriter pw=response.getWriter();
pw.println("<html>");
pw.println("<body bgcolor=wheat>");
pw.println("<h1>HELLO " + name + " WELCOME</h1>");
pw.println("</html>");
pw.close();
}
}
My web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app SYSTEM "Web-app.dtd">
<web-app>
<servlet>
<servlet-name>one</servlet-name>
<servlet-class>Greetingapplication</servlet-class>
</servlet>
<servlet-mapping id="ServletMapping_1283534546609">
<servlet-name>one</servlet-name>
<url-pattern>/greet</url-pattern>
</servlet-mapping>
</web-app>
The servlet is mapped on an url-pattern of /greet, not /greetingservlet as you seem to expect as per the error message. So, change the URL in browser address bar accordingly. Also, the servlet class is declared to be Greetingapplication, but it has the actual name Greetingservlt. So, you need to align out the one or the other, otherwise Tomcat is unable to locate/load the servlet. Also, packageless servlet classes used to fail on some specific Tomcat + JVM combinations. To be on the safe side, you'd like to place the servlet class (as every other Java class) in a package (don't forget to update the web.xml accordingly).
There are more problems in the code posted as far, but they are as far not relevant to this particular question. Maybe in a new question.
The 404 or Not Found HTTP response code indicates that the client was able to communicate with the server, but the server could not find the resource that was requested. And indeed...
First, according to your web.xml, your Servlet is mapped on /greet, and not /greetingservlet. So why are you trying to access /greetingservlet? Is this the name of your JSP? If yes, it's missing the .jsp extension. If no, then you should probably use /greet instead.
Second, your web.xml doesn't look correct, the servlet-class doesn't match the actual name of your servlet. It should be:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>My First Web Application</display-name>
<servlet>
<servlet-name>one</servlet-name>
<servlet-class>com.acme.Greetingservlt</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>one</servlet-name>
<url-pattern>/greet</url-pattern>
</servlet-mapping>
</web-app>
Replace com.acme with the real package of your servlet, if any(!). And redeploy the whole.
As a reminder, the URL to access the servlet is constructed like this:
http://localhost:8080/mywebapp/greet
A B C D
Where:
A is the hostname where Tomcat is running (the local machine here)
B is the port Tomcat is listening to (8080 is the default)
C is the context path of your webapp (the name of the war by default)
D is the pattern declared in the web.xml to invoke the servlet

how to call jsp file from java?

I have two jsp file and one java file. My constraints is if jspfile1 call java then java file call the jspfile2. Is it possible?
How to achieve this?
If by "Java file" you mean a Servlet, you can use the RequestDispatcher:
request.getRequestDispatcher("/my.jsp").include(request, response);
request.getRequestDispatcher("/my.jsp").forward(request, response);
The normal way is using a Servlet. Just extend HttpServlet and map it in web.xml with a certain url-pattern. Then just have the HTML links or forms in your JSP to point to an URL which matches the servlet's url-pattern.
E.g. page1.jsp:
<form action="servletUrl">
<input type"submit">
</form>
or
click here
The <form> without method attribute (which defaults to method="get") and the <a> links will call servlet's doGet() method.
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Do your Java code thing here.
String message = "hello";
request.setAttribute("message", message); // Will be available in ${message}.
// And then forward the request to a JSP file.
request.getRequestDispatcher("page2.jsp").forward(request, response);
}
}
If you have a <form method="post">, you'll have to replace doGet by doPost method.
Map this servlet in web.xml as follows:
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/servletUrl</url-pattern>
</servlet-mapping>
so that it's available by http://example.com/contextname/servletUrl. The <form> and <a> URL's have to point either relatively or absolutely to exact that URL to get the servlet invoked.
Now, this servlet example has set some "result" as request attribute with the name "message" and forwards the request to page2.jsp. To display the result in page2.jsp just do access ${message}:
<p>Servlet result was: ${message}</p>
Do a http web request.
jsp files get converted to a servlet. You cannot call them directly.
EDIT : typo fixed.

Categories

Resources