how to call jsp file from java? - 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.

Related

HttpServletRequest does not return null?

I have a form:
<form action='?hasScenario=1' method='post' enctype='multipart/form-data'>
<input type='file' name='file'/>
<input type='submit' />
</form>
In tomcat 8.0 I want to do:
private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
Part filePart = request.getPart("file");
....
}
In documentation I see I should get null if user doesn't enter any value. I havn't (intentionally) configured anything special for multipart/file uploading in web.xml or server. But instead of null I get:
java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
I would like to handle nicely cases, when some parameters are not provided, how to do that? Catching and doing nothing on IllegalStateException is not nice way for me - in case of no parameter I'd like to ask user for file instead of scaring him with 'error/warning' words.
It is a great way to find answer myself - just ask question to others :)
multipart-config in web.xml is a must. So my servlet part looks currently like:
<servlet>
<description>Scenario</description>
<servlet-name>Scenario</servlet-name>
<servlet-class>path-to-the-servlet</servlet-class>
<multipart-config>
<max-file-size>3145728</max-file-size>
<max-request-size>5242880</max-request-size>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>Scenario</servlet-name>
<url-pattern>/scenario</url-pattern>
</servlet-mapping>
Before calling getPart it's important to check there are any data, like with:
if (request.getContentType() != null)
Part filePart = request.getPart("file");
...
And so finally filePart is null or a valid variable
Still I can't understand how have they made getParameter working in this post
How to upload files to server using JSP/Servlet? but this is different story :)

Servlet forwarding

I'm using in my project the embebed jetty and came up with a few problems. I have these two pages:
índex.jsp
result.jsp
And these two servlets:
upload
search
In the índex.jsp there is a form to upload a file and the upload process in handle by the upload servlet but then I should return a message to the índex.jsp to tell if the upload was done.
request.setAttribute("message", "Upload Sucedded!");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
This will forward the message to the índex page but the url will be /upload and I would like to be the índex. So there is some other way of struct my files and maybe make my welcome file some servlet instead of the índex.jsp?
This has nothing to do with Jetty. That's default behavior of forwarding.
Ugly solution:
If you want to rewrite your URL, use a redirect instead and pass the parameter by session. After displaying the message, remove it from session.
Better solution:
Change the name of your upload servlet by IndexServlet. This servlet will handle GET and POST requests for your index.jsp page. In the end of the processing, you will forward to your JSP page. By doing this, you can directly post the form to your current page:
<form action="index.jsp" method="POST" enctype="multipart/form-data">
<!-- your fields ... -->
</form>
Then your servlet:
#WebServlet("index.jsp")
public class IndexServlet extends HttpServlet {
//using ... to avoid parameters and exceptions to be thrown
#Override
public void doGet(...) throws ... {
//this method should only forward to your view
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
//using ... to avoid parameters and exceptions to be thrown
#Override
public void doPost(...) throws ... {
//current implementation...
//in the end, forward to the same view
request.setAttribute("message", "Upload Sucedded!");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
}
More info:
Difference between JSP forward and redirect
The simplest solution would be to change upload servlet to use redirect and use request parameter instead of attribute like this:
// upload servlet
response.sendRedirect("index.jsp?message=YourMessage");
Then in index.jsp use request.getParameter("message") or EL to display your message.

How can I set the URL for a JSP page?

In a servlet I would just do
#WebServlet("/myURL")
But how would I do that with a JSP page?
Just like any servlet, you can map a particular URL-pattern to a JSP.
Simply add this snippet in your deployment descriptor
<servlet>
<servlet-name>fooBar</servlet-name>
<jsp-file>/foo.jsp</jsp-file> <!-- Your JSP. Must begin with '/' -->
</servlet>
<servlet-mapping>
<servlet-name>fooBar</servlet-name>
<url-pattern>/bar</url-pattern> <!-- Any URL you want here -->
</servlet-mapping>
There is no facility to have annotations inside the JSP so if you don't want to make an entry inside the web.xml and work purely with annotations, you have a work around to make a sevlet that simply forwards the RequestDispatcher to the JSP and you can annotate this servlet with the URL that you want.
#WebServlet("/bar") //your URL pattern
public class DummyServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/path/to/foo.jsp").forward(request, response);
}
}

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>

Categories

Resources