尝试使用tomcat注销时出现Http 500错误

时间:2014-05-05 19:34:18

标签: java tomcat servlets

我遇到了我正在制作的servlet的问题。你必须登录系统,你还需要注销,我使用文件注册用户。登录工作正常,它从文件中读取用户,但由于某种原因退出不起作用。当我按下注销按钮时出错:

enter image description here

以下是LogoutServlet类的代码

    package nl.hu.sp.lesson1.dynamicexample;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

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

public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        RequestDispatcher rd = null;

        try {
            String data = null;
            File file = new File(
                    "C:/apache-tomcat-8.0.5/webapps/LoginAssignment/loggedusers.txt");
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            while ((data = br.readLine()) != null) {
                String[] de = data.split(" ");
                if (de[0].equals("vimal")) {
                    data.trim();

                    rd = req.getRequestDispatcher("testpage.html");
                }
            }
            rd.forward(req, resp);
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您正在阅读文本文件并搜索“vimal”,如果发现您正在初始化rd;如果未找到rd为空。它在文本文件中找不到“vimal”,rd变为null,因此抛出空指针异常。

添加空检查

if (rd != null) {
    rd.forward(req, resp);
}