Java 如何重定向到 WEB-INF 文件夹内的 JSP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22928427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:06:11  来源:igfitidea点击:

How to redirect to JSP inside WEB-INF folder

javajqueryhtmljspservlets

提问by Haris Mehmood

I have a jsp with a NAV in it, which further contains and UL with the following elements as shown in the code below,

我有一个带有 NAV 的 jsp,它进一步包含 UL 和以下元素,如下面的代码所示,

<nav>
     <ul>
        <li class="current"><a>Home</a></li>
        <li><a>Access Control</a></li>
        <li><a>Site Administration</a></li>
        <li><a>Dashboard</a></li>
        <li><a>Visitor Management</a></li>
      </ul>                
</nav>

What I want to do is to redirect this page to the corresponding jsp page whenever an LI is clicked. Now since all the pages are inside WEB-INF Folder, I cant figure out how to do so. I dont want to create a jsp out side WEB-INF and then put servlet redirection code in it. Thanks in advance.

我想要做的是每当单击 LI 时将此页面重定向到相应的 jsp 页面。现在由于所有页面都在 WEB-INF 文件夹中,我不知道该怎么做。我不想在 WEB-INF 外面创建一个 jsp,然后将 servlet 重定向代码放入其中。提前致谢。

What can I use here ?

我可以在这里使用什么?

P.S: Started web development few months before. Thanks in advance.

PS:几个月前就开始了 Web 开发。提前致谢。

采纳答案by Hirak

You need to invoke a servlet through href on the LI.

您需要通过 LI 上的 href 调用 servlet。

In the servlet, you need to use requestdispatcher to redirect to your jsp

在servlet中,需要使用requestdispatcher重定向到你的jsp

RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( "/WEB-INF/sample.jsp" );
dispatcher.forward( request, response );

=================EDIT : Sample Code =========================================

================编辑:示例代码 ============================== ============

Index.html

索引.html

<nav>
     <ul>
        <li class="current"><a href="/DynamicTest/MyServlet">Home</a></li>
        <li><a>Access Control</a></li>
        <li><a>Site Administration</a></li>
        <li><a>Dashboard</a></li>
        <li><a>Visitor Management</a></li>
      </ul>                
</nav>

Servlet code

小服务程序代码

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher("/WEB-INF/sample.jsp");
        dispatcher.forward(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

Jsp location :

Jsp位置:

WEB-INF/sample.jsp