Calling servlet from JSP [duplicate] - java

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.

Related

How to Map Servlet Actions to JSP Path with Annotations?

I have a simple Maven servlet/jsp application that I deploy to a local Tomcat 9 (via Eclipse). JSP pages are stored under root folder (src\main\webapp\*.jsp) which when Maven installs a WAR, they go under the root folder (MyAppContext\*.jsp along side MyAppContext\META-INF\ and MyAppContext\WEB-INF\).
The servlets' URL patterns are annotated for each servlet, e.g. /doactionone, /doactiontwo, etc. Most servlets perform the dispatching to various JSP pages, but I do have a direct anchor link on one.
I wanted to move these JSP pages into their own respective directory, so I moved them to src\main\webapp\jsp\*.jsp folder, and when the Maven install is run, they get placed under MyAppContext\jsp\.
The only entry I have in web.xml is a welcome file that after relocating the JSP files, it points to jsp\doactionone.jsp which loads that corresponding JSP page. This page contains a simple form:
<form action="doactionone" method="post">
...
<a href="jsp/doactiontwo.jsp">
<input type="submit" />...
</form>
The submission on this page actually calls the right servlet (the one defined with doactionone URL pattern). I also have a link that takes the user to the second page (doactiontwo.jsp).
However, when I navigate to that second page via this link, which has another simple form (see below), and perform the submission (post), I see in browser's debugging that the URL request is http://localhost:8080/MyAppContext/jsp/doactiontwo which, for obvious reason, would return a 404 status (and get no hit to this servlet's doPost() (or doGet()) methods either).
<form action="doactiontwo" method="post">
...
<input type="submit" />...
</form>
If I try to modify the second servlet's URL pattern to /jsp/doactiontwo, I can hit the servlet, but when doactiontwo actually dispatches/forwards the request after processing to the first servlet (doactionone) with:
RequestDispatcher rd = request.getRequestDispatcher("doactionone.jsp");
rd.forward(request, response);
when it gets loaded, when hover over the URL on the first page that initially was pointing to the second JSP page (<a href="jsp/doactiontwo.jsp">), now actually points to:
jsp/jsp/doactiontwo.jsp
The funny part is that the source code of doactionone.jsp still shows it as jsp/doactiontwo.jsp, but hovering over it shows http://localhost:8080/MyAppContext/jsp/jsp/doactiontwo, and when clicked, it obviously results in 404 status.
Can somebody explain why, first of all, the submission on the second JSP page requires the servlet to have a pattern of /jsp/doactiontwo to work rather than /doactiontwo? And is there a way around to avoid appending /jsp to the URL pattern?
And second, why when the second servlet processes the request and dispatches/forwards it to the first page, the URL now contains two jsp/'s?
You need to change your design to allow the controllers, a.k.a. Servlets, to drive your application. In this particular case, use the URL Pattern of second Servlet (doactiontwo) in place of you link:
#WebServlet(urlPatterns = { "doactiontwo" }
public class DoActionTwoServlet extends HttpServlet { /* ... */ }
<form action="doactionone" method="post">
...
<a href="doactiontwo"> <!-- This should match your second servlet's URL pattern -->
<input type="submit" />...
</form>
Now, since the default method when anchor link is invoked is GET, you need to overwrite DoActionTwoServlet's doGet() method, and forward those requests to an actual doactiontwo.jsp:
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("jsp/doactiontwo.jsp");
rd.forward(request, response);
}

Why my servlet doesn't run? [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.
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

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.

What is the best way to create a Java Servlet or JSP that optionally includes content depending on URL parameters

I want to create a JSP page or servlet that will work in 2 ways.
A user visits their own profile page:
http//something.com/profile/
Or they visit their friends page:
http://something.com/profile/FriendsName
They could also visit their own page through an explicit URL like:
http://something.com/profile/YourName
I have a servlet-mapping setup as follows to map any requests to /profile to my JSP that will handle that request.
<servlet>
<servlet-name>Profile</servlet-name>
<jsp-file>/profile.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Profile</servlet-name>
<url-pattern>/profile</url-pattern>
</servlet-mapping>
Then I was thinking I could setup a filter that will parse the HTTPServletRequest's URL to read after the /profile/.
<filter>
<filter-name>profile-filter</filter-name>
<filter-class>ProfileFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>profile-filter</filter-name>
<url-pattern>/profile*</url-pattern>
</filter-mapping>
Now the filter could set attributes in the HttpServletRequest, how would i go about pulling those out in the JSP page to check if a user name was specified and check if your own name was set?
How would I go about creating a page scoped bean in the ServletFilter so I could use in the JSP page using jspBean like this:
<jsp:useBean id="profileInfo" scope="page" class="ProfileInfo" />
I think a filter only serves to artificially break the logic apart. You can very easily determine the value of the portion of the URL that doesn't match the url-pattern described in the web.xml. The HttpServletRequest class has a method that returns this value for you, it's called getPathInfo(). Here's an example:
<%
String path = request.getPathInfo();
if (path == null || "".equalsIgnoreCase(path)) {
// The path was empty, display the current user's profile
} else {
// Display the named profile
}
%>
This doesn't help you at all with the request beans, but I think it helps with the design.
I'm not completely following the question, but if you want a jsp to access request parameters or attributes, just do:
<%
String parameter = request.getParameter("parameter");
String attribute = request.getAttribute("attribute");
%>
You can also get access to the request url, etc... if you need to do anything with those.
Personally, I'd recommend that you use a servlet to handle your requests, and forward to the jsp of your choosing (possibly after setting session information that the jsp can use).
Using server level filters and request attributes for this kind of thing may be a bit overkill, but only you know your project's true requirements.

Categories

Resources