简体   繁体   English

无法使用servlet从索引访问其他JSP文件

[英]Can't access different JSP files from index with servlet

I'm trying out to set up a simple web app with TomCat, there is a servlet that's supposed to link my index page with a 2 buttons pointing at 2 different JSP. 我正在尝试使用TomCat设置一个简单的Web应用程序,有一个servlet应该将我的索引页面与指向2个不同JSP的2个按钮链接起来。

The thing it does is when I click on those buttons it doesn't change the page, it only puts the name of the Servlet "request" (sorry don't really know the exact term). 它所做的是,当我单击这些按钮时,它不会更改页面,它仅放置Servlet的名称“ request”(对不起,您实际上不知道确切的用语)。

Also when I tried to access directly by typing for example localhost:8080/reunion.jsp to access the pages directly it stays on index as if it's the only page there even if it looks like it's trying to load another page. 同样,当我尝试通过键入例如localhost:8080 / reunion.jsp直接访问页面来直接访问时,即使它看起来像是试图加载另一个页面,它仍停留在索引上,就好像它是那里的唯一页面一样。

Here is the code of the Servlet and Index. 这是Servlet和Index的代码。

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/Servlet")
public class Servlet extends HttpServlet {
    private ServletContext sc = this.getServletContext();

    public void init(ServletConfig config) throws ServletException{
        super.init(config);
        sc = this.getServletContext();
    }

    public Servlet(){
        super();
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getParameter("operation");

        if (op.equalsIgnoreCase("cv")){
            this.versPersonne(request, response);
        }
        if (op.equalsIgnoreCase("reunion")){
            this.versReunion(request, response);
        }

    }

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


    }

    private void versReunion(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher rd = sc.getRequestDispatcher("/reunion.jsp");
        rd.forward(request, response);
    }

    private void versPersonne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher rd = sc.getRequestDispatcher("/cv.jsp");
        rd.forward(request, response);
    }


}

Here is the index 这是索引

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
  <title>$Title$</title>
</head>
<body>

<form action="Servlet?operation=cv" method="post">
  <br><input type=submit value="Page personne"/>
</form>

<form action="Servlet?operation=reunion" method="post">
  <br><input type=submit value="Page réunion"/>
</form>

</body>
</html>

And just in case here is the web.XML file: 以防万一,这是web.XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>Servlet</servlet-name>
        <jsp-file>/index.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

My JSP files are all in the web folder. 我的JSP文件都在web文件夹中。

I looked really hard for an answer and tried many different things and configurations but can't seem to find an answer. 我真的很努力地寻找答案,并尝试了许多不同的方法和配置,但似乎找不到答案。

I do think the problem lies with the servlet configuration somehow but can't really find the answer. 我确实认为问题出在某种程度上与servlet配置有关,但无法真正找到答案。

UPDATE : Thanks to the first answers I deleted the XML file and updated the DoGet Method. 更新:由于有了第一个答案,我删除了XML文件并更新了DoGet方法。 At this point the web app does try to switch pages but it throws me a 500 Error Exception telling me that it failed to instantiate the servlet here is the log : 此时,Web应用程序确实尝试切换页面,但抛出500错误异常,告诉我未能实例化servlet,这是日志:

javax.servlet.ServletException: Erreur à l'instantiation de la classe servlet [com.example.Servlet]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:764)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1388)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:844)

And the root cause : 根本原因是:

java.lang.NullPointerException
javax.servlet.GenericServlet.getServletContext(GenericServlet.java:123)
com.example.Servlet.<init>(Servlet.java:15)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:764)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1388)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:844)

This is the project structure : 这是项目结构:

https://imgur.com/a/YTpq4hD https://imgur.com/a/YTpq4hD

Thanks in advance for your answers ! 预先感谢您的回答!

call method doPost(request,response); 调用方法doPost(request,response); inside doGet method as shown below, that should fix your issue. 在doGet方法中,如下所示,这应该可以解决您的问题。

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

    doPost(request, response);

}

also in Index.jsp you have specified form action as "Servlet?operation=reunion" change that to "/Servlet?operation=reunion" 同样在Index.jsp中,您已将表单操作指定为"Servlet?operation=reunion"将其更改为"/Servlet?operation=reunion"

similarly change "Servlet?operation=cv" to "/Servlet?operation=cv" 类似地,将"Servlet?operation=cv"更改为"/Servlet?operation=cv"

Your web.xml file is the culprit. 您的web.xml文件是罪魁祸首。

You want to use your servlet as /Servlet , in the WebServlet annotation, but at the same time, the xml file maps index.jsp to any URL with /* . 您想在WebServlet批注WebServlet servlet用作/Servlet ,但是与此同时,xml文件将index.jsp映射到带有/* 任何URL

As you have declared the mapping with the WebServlet annotation, and as index.jsp is the default page, just remove the mapping frow web.xml and strip it down to: 当您使用WebServlet批注声明了映射,并且由于index.jsp是默认页面时,只需删除映射眉头web.xml并将其剥离为:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

</web-app>

Or even simplier remove the web.xml file since it does not contain anything longer. 甚至更简单地删除web.xml文件,因为它不再包含任何内容。


You have another error in your servlet code: you try to initialize the ServletContext at creation time which you should not. 您的Servlet代码中还有另一个错误:您尝试在创建时初始化ServletContext,但不应这样做。 It should be: 它应该是:

@WebServlet("/Servlet")
public class Servlet extends HttpServlet {
    private ServletContext sc;    // delay initialization to init

    public void init(ServletConfig config) throws ServletException{
        super.init(config);
        sc = this.getServletContext();
    }

But in fact you have no reason to store a reference to the ServletContext. 但是实际上,您没有理由存储对ServletContext的引用。 You use it only to get a RequestDispatcher when you could simply get it from the Request : 当您可以简单地从Request获取它时,仅将其用于获取RequestDispatcher

private void versReunion(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    RequestDispatcher rd = request.getRequestDispatcher("/reunion.jsp");
    rd.forward(request, response);
}

That's all. 就这样。 Do the same in versPersonne and you can remove any line refering to sc ... versPersonne做同样的versPersonne ,您可以删除任何versPersonne sc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM