Параметр сервлета init всегда показывает ноль - PullRequest
0 голосов
/ 19 января 2019

Я абсолютный новичок java2ee, и мне нужна помощь. Я следую инструкциям на YouTube (https://www.youtube.com/watch?v=sB7-ChpjWVw), и у меня также есть некоторые базовые знания по этой теме.

Дело в том, что: Независимо от того, как я стараюсь, всякий раз, когда я пытаюсь показать сервлет-init-параметр из web.xml в мой сервлет, он всегда заканчивается нулевым значением. Любопытный факт: не возникает проблем, когда я делаю то же самое с контекстными параметрами.

Я попытался переопределить метод init () вместо метода init (ServletConfig config). если я переопределяю метод init (ServletConfig config), я вызываю super.init (config). Я пытался переместить все внутри метода doGet (). проект уже настроен как динамический веб-проект. Я использовал каждую версию метода getInitParameter (String), которую нашел в StackOverflow.

все, что приходит мне в голову, это что-то не так в файле pom (может быть, какая-то старая зависимость? Какой-то отсутствующий плагин?).

вот код для web.xml, сервлета и pom.

пожалуйста, спасите меня, я занимаюсь этим уже 48 часов.

вот сервлет

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyFirstServlet
 */
@WebServlet("/MyFirstServlet")
public class MyFirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private ServletConfig servletConfig;
private String servletInitParameterValue;
private String contextParameterValue;

private String loginTime;

/**
 * @see HttpServlet#HttpServlet()
 */
public MyFirstServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see Servlet#init(ServletConfig)
 */
public void init(ServletConfig config) throws ServletException {

    System.out.println("Basic servlet***********************init()******************");
    super.init(config);
    this.servletConfig=config;

    //use ServletConfig to get servlet init parameters
    servletInitParameterValue =  getServletConfig().getInitParameter("parInit");
    System.out.println("servletInitParameterValue = "+ servletInitParameterValue);


    //use ServletConfig to get context init parameters
    contextParameterValue = config.getServletContext().getInitParameter("ContextParameter");
    System.out.println("contextParameterValue = "+ contextParameterValue );

}





/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    System.out.println("Basic servlet***********************doGet()******************");




    // get request parameter
    String requestParamValue = request.getParameter("param");

    //set response content type
    response.setContentType("text/html");


    //create web-page and write a message inside of it
    response.getWriter().append("Served at: ").append(request.getContextPath());
    PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<br>");
        out.println("<h3>"+this.getSerlvletInfo() + " invoked at " + new Date().getDate()+". "+ " i got init param "+ servletInitParameterValue
                + " and context param = "+ contextParameterValue + ".<br>"+"You logged in passing parameter value param as "+ requestParamValue
                +"</h3>"+ ".<br>");

        out.println("<a href='ExeServlet'>vai a seconda servlet</a>");
        out.println("</html>");
        out.println("</body>");


}






/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}







/**
 * @see Servlet#destroy()
 */
public void destroy() {
    System.out.println("i'm destroyed!");
}


public String getSerlvletInfo () {
    return this.servletConfig.getServletName();
}

public ServletConfig getServletConfig () {
    return servletConfig;
}


}

вот веб.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
"http://java.sun.com/dtd/web-app_2_3.dtd" >




<web-app>
  <display-name>Archetype Created Web Application</display-name>


  <context-param>
        <param-name>country</param-name>
        <param-value>Ita</param-value>
    </context-param>

  <context-param>
        <param-name>ContextParameter</param-name>
        <param-value>IO SONO IL PARAMETRO DI CONTESTO 2</param-value>
    </context-param>



  <servlet>
         <servlet-name>MyFirstServlet</servlet-name>
     <display-name>MyFirstServlet</display-name>
     <description></description>
    <servlet-class>servlet.MyFirstServlet</servlet-class>
    <init-param>
        <param-name>parInit</param-name>
    <param-value>IO SONO IL PARAMETRO DELLA SERVLET</param-value>
    <description></description>
    </init-param>
 </servlet>
 <servlet>
    <servlet-name>ExeServlet</servlet-name>
<display-name>ExeServlet</display-name>
<description></description>
<servlet-class>servlet.ExeServlet</servlet-class>
<init-param>
    <param-name>company</param-name>
    <param-value>thewebbcompany</param-value>
    <description></description>
    </init-param>
   </servlet>
  <servlet-mapping>
    <servlet-name>MyFirstServlet</servlet-name>
    <url-pattern>/servlet/MyFirstServlet</url-pattern>
   </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ExeServlet</servlet-name>
    <url-pattern>/ExeServlet</url-pattern>
  </servlet-mapping>
 </web-app>

и вот идет пом

                <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
              <modelVersion>4.0.0</modelVersion>
              <groupId>com.theStartupCentral</groupId>
              <artifactId>pizzashoppingcart</artifactId>
              <packaging>war</packaging>
              <version>0.0.1-SNAPSHOT</version>
              <name>pizzashoppingcart Maven Webapp</name>
              <url>http://maven.apache.org</url>




              <dependencies>
                <dependency>
                  <groupId>junit</groupId>
                  <artifactId>junit</artifactId>
                  <version>3.8.1</version>
                  <scope>test</scope>
                </dependency>
                <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>5.1.3.RELEASE</version>
            </dependency>
                <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.6</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>4.0.1</version>
                <scope>provided</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
            <dependency>
                <groupId>javax.validation</groupId>
                <artifactId>validation-api</artifactId>
                <version>1.0.0.GA</version>
            </dependency>



              </dependencies>

              <build>
                <plugins>
                    <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                         <fork>true</fork>
                    <executable>C:\Program Files\Java\jdk1.8.0_191\bin\javac</executable>    
                    </configuration>
                </plugin>
                </plugins>
            </build>



            </project>

Ответы [ 2 ]

0 голосов
/ 19 января 2019

Используйте аннотацию @WebServlet ИЛИ элементы web.xml.Не смешивайте их.https://www.codejava.net/java-ee/servlet/webservlet-annotation-examples показывает примеры указания параметров инициализации в аннотации.

0 голосов
/ 19 января 2019

Удалить аннотацию @WebServlet ("/ MyFirstServlet")

Сохраняйте только методы doGet () и doPost () и удаляйте все другие переменные и методы.

получить доступ к параметру init, используя следующий код.

public void init()  {
    String servletInitParameterValue =  getServletConfig().getInitParameter("parInit");
    System.out.println("servletInitParameterValue = "+ servletInitParameterValue);

    String contextParameterValue = getServletContext().getInitParameter("ContextParameter");
    System.out.println("contextParameterValue = "+ contextParameterValue ); }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...