gpt4 book ai didi

java - Java Servlet 中参数未正确传递

转载 作者:行者123 更新时间:2023-12-01 18:59:13 26 4
gpt4 key购买 nike

我正在尝试编写一个简单的 java servlet 来列出目录中的文件。该路径存储在 web.xml 的 init-param 中。当我调用 getInitParameters() 时,它返回目录路径。但是当我尝试将它传递给处理程序时,它返回 null。不确定我做错了什么。有什么帮助吗?

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

interface Handler {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException;
}

class DispatchChoice {
public final String param;
public final GetHandler getHandler;
public DispatchChoice (String param, Handler getHandler)
{
this.param = param;
this.getHandler = getHandler;
}
}

public class MyServlet extends HttpServlet
{
String value;
public void init() throws ServletException {
value = getInitParameter("addressfile"); // correct value is saved here
System.out.println("Init value : "+value);
}
DispatchChoice myChoice = new DispatchChoice("/test1", new FileHandler(value));

public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException
{
myChoice.getHandler.doGet(request, response);
}
}

class FileHandler implements Handler {
private String place;
public FileHandler (String value){
this.place = value; // this is NULL, not the value from above
System.out.println("Param value : " + value);
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
File directory = new File(place); //is NULL
File[] files = directory.listFiles();
PrintWriter pw = response.getWriter();
for (int index = 0; index < files.length; index++) {
pw.println(files[index].getName());
}
}
}

web.xml

<servlet>
<servlet-name>ListManagerServlet</servlet-name>
<servlet-class>savva.listmanagerservlet.ListManagerServlet</servlet-class>
<init-param>
<param-name>addressfile</param-name>
<param-value>d:\\temp\\</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ListManagerServlet</servlet-name>
<url-pattern>/ListManagerServlet</url-pattern>
</servlet-mapping>

最佳答案

DispatchChoice myChoice = new DispatchChoice("/test1", new FileHandler(value));

该行在init()之前执行,因此value仍然是null并且尚未分配!相反,将赋值移到 init() 内,如下所示:

DispatchChoice myChoice;

public void init() throws ServletException
{
value = getInitParameter("addressfile"); // correct value is saved here
myChoice = new DispatchChoice("/test1", new FileHandler(value));
System.out.println("Init value : "+value);
}

关于java - Java Servlet 中参数未正确传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12871990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com