开发者

how to call jsp file from java?

开发者 https://www.devze.com 2022-12-22 16:25 出处:网络
I have two jsp file and one java file. My constrai开发者_运维知识库nts is if jspfile1 call java then java file call the jspfile2.Is it possible?

I have two jsp file and one java file. My constrai开发者_运维知识库nts 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

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


Do a http web request.


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

EDIT : typo fixed.

0

精彩评论

暂无评论...
验证码 换一张
取 消