user246160
user246160

Reputation: 1397

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?

Upvotes: 0

Views: 14944

Answers (4)

BalusC
BalusC

Reputation: 1108632

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

<a href="servletUrl">click here</a>

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>

Upvotes: 1

fastcodejava
fastcodejava

Reputation: 41077

jsp files get converted to a servlet. You cannot call them directly.

EDIT : typo fixed.

Upvotes: 0

Thilo
Thilo

Reputation: 262474

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);

Upvotes: 3

thelost
thelost

Reputation: 6694

Do a http web request.

Upvotes: 0

Related Questions