将 html 文件写回浏览器:Java
我已经从浏览器读取了对 HTML 文档的请求,解析了请求中的文件,找到了指定的文件,现在剩下的就是将 HTML 文件的内容发送回浏览器。我目前正在做的事情似乎应该可以正常工作,但是浏览器不会接收 HTML 文件的内容。
public void sendResponse(File resource){
System.out.println(resource.getAbsolutePath());
Scanner fileReader;
try {
fileReader = new Scanner(resource);
while(fileReader.hasNext()){
socketWriter.println(fileReader.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
e.printStackTrace();
}
}
我做错了什么?没有抛出异常,但是浏览器只是不断地加载和加载。
I've read a request for an HTML document from my browser, parsed the file from the request, found the specified file, and now all that's left is to send back the contents of the HTML file to the browser. What I'm currently doing seems like it should work just fine, however, the contents of the HTML file are not received by the browser.
public void sendResponse(File resource){
System.out.println(resource.getAbsolutePath());
Scanner fileReader;
try {
fileReader = new Scanner(resource);
while(fileReader.hasNext()){
socketWriter.println(fileReader.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
e.printStackTrace();
}
}
What am I doing incorrectly? There is no exception thrown, but the browser just keeps loading and loading.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这表明您的代码陷入了无限循环。检查你的 while 循环。 nextLine() 没有向前移动文件指针?
that suggests your code is stuck in an infinite loop. Check your while loop. nextLine() is not moving the file pointer ahead?
如果不知道
socketWriter
是什么类型,则很难判断,但我想您需要关闭连接。在socketWriter
上查找close()
方法或类似方法,并在完成后调用它。It's hard to tell without knowing what type
socketWriter
is, but I imagine you'll need to close the connection. Look for aclose()
method or something similar onsocketWriter
and call it when you're done.从您的代码来看,socketWriter 的去向并不明显。诸如套接字之类的低级操作最好由 Web 服务器本身处理。通常,当我们必须将响应写回浏览器时,我们会使用 HttpServletResponse 对象,可在 servlet 的 goGet / doPost 方法中使用。有关更多详细信息,请参阅 javadoc。
It is not evident from your code, where socketWriter is going. Low level operations such as socket are best handled by the web server itself. Normally when we have to write a response back to the browser, we make use of HttpServletResponse object which is available in the goGet / doPost method of your servlet. Refer to the javadocs for more details.