如何在servlet中调用JSP,该servlet也在文件夹中

时间:2021-07-26 00:32:18

I have a project in Netbeans. In "Source Packages" I have a servlet, myServlet.java. But it is inside folders. Its com.login.controller. In "Web Pages" I have 2 JSPs, login.jsp and home.jsp. login.jsp is inside of folder "jsp/login/login.jsp" while home.jsp is at "jsp/home/home.jsp".

我在Netbeans有一个项目。在“源包”中,我有一个servlet,myServlet.java。但它是在文件夹内。它的com.login.controller。在“Web页面”中,我有2个JSP,login.jsp和home.jsp。 login.jsp位于文件夹“jsp / login / login.jsp”内,而home.jsp位于“jsp / home / home.jsp”。

Now my question is what is the best way of invoking JSP page from servlet when using getRequestDispatcher? In my login.jsp when I clicked login button it call myServlet.java and then it will process if the inputs are valid it should then directed in home.jsp using getRequestDispatcher. What Should I enter in its parameter as path? What I thought are the ff:

现在我的问题是在使用getRequestDispatcher时从servlet调用JSP页面的最佳方法是什么?在我的login.jsp中,当我单击登录按钮时,它调用myServlet.java,然后它将处理如果输入有效,则应使用getRequestDispatcher指向home.jsp。我应该在其参数中输入什么路径?我认为是ff:

getRequestDispatcher("home.jsp");
getRequestDispatcher("jsp/home/home.jsp");
getRequestDispatcher("../../../jsp/home/home.jsp"); //Getting back of 

directory 3x because I thought my servlet is inside 3 folders that's why.

目录3x因为我认为我的servlet在3个文件夹内,这就是原因。

But all of these 3 did not work. What should I do? I don't know. Please help me. Thanks in advance.

但所有这3个都不起作用。我该怎么办?我不知道。请帮我。提前致谢。

1 个解决方案

#1


1  

Make use of contextpath, it will give you root path.

利用contextpath,它会给你根路径。

request.getContextPath()

So if you want to access home.jsp, navigate from Web-Content folder i.e

因此,如果您想访问home.jsp,请从Web-Content文件夹导航,即

getRequestDispatcher(request.getContextPath()+"/jsp/home/home.jsp");

Similarly, when you want to send request to Servlet, you can use

同样,当您想向Servlet发送请求时,您可以使用

 getRequestDispatcher(request.getContextPath()+"/myServlet.java");

#1


1  

Make use of contextpath, it will give you root path.

利用contextpath,它会给你根路径。

request.getContextPath()

So if you want to access home.jsp, navigate from Web-Content folder i.e

因此,如果您想访问home.jsp,请从Web-Content文件夹导航,即

getRequestDispatcher(request.getContextPath()+"/jsp/home/home.jsp");

Similarly, when you want to send request to Servlet, you can use

同样,当您想向Servlet发送请求时,您可以使用

 getRequestDispatcher(request.getContextPath()+"/myServlet.java");