java servlet提交按钮不起作用

时间:2014-05-03 09:42:45

标签: java forms jsp servlets

我一直在写一个小型登录servlet。登录部分工作得很好,但是当我按下注销提交按钮时 - 没有任何反应 Servlet代码如下:

public class LoginServlet extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 7638796169158385551L;
    private Database database = Database.getInstance();

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.write("<html><head><title>Login form</title></head>");
        if (!database.connected) {
            outLoginForm(out);
        } else {
            out.write("Hello " + database.getLoginName() + "!");
            outLogoutForm(out);
        }
        out.write("</body></html>");
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter("loginsub") != null) {
            if (isParameterEmpty(request, "login")
                    || isParameterEmpty(request, "pass")) {
                response.getWriter().write("Some fields are empty");
                doGet(request, response);
            }
            try {
                database.connect(request.getParameter("login"),
                        request.getParameter("pass"));
            } catch (ExceptionInInitializerError ex) {
                response.getWriter().write("Login or password is incorrect");
            }
        } else if (request.getParameter("logoutsub") != null) {
            database.disconnect();
        }
        doGet(request, response);
    }

    private boolean isParameterEmpty(HttpServletRequest request,
            String parameter) {
        if (request.getParameter(parameter).isEmpty())
            return true;
        return false;
    }

    protected void outLoginForm(PrintWriter out) {
        out.write("<FORM method =\"POST\">");
        out.write("Login:<input type=\"text\"name=\"login\"><br>");
        out.write("Password:<input type=\"password\"name=\"pass\"><br>");
        out.write("<input type=\"submit\"name=\"loginsub\" value=\"Login\"/><br>");
        out.write("</FORM><br>");
    }

    protected void outLogoutForm(PrintWriter out) {
        out.write("<FORM method =\"POST>\">");
        out.write("<input type=\"submit\"name=\"logoutsub\" value=\"Logout\"/><br>");
        out.write("</FORM><br>");
    }
}

任何人都可以帮我找出错误吗?我是JSP和java servlet的新手。

1 个答案:

答案 0 :(得分:0)

下面有一个问题(>

之后有一个额外的POST
 out.write("<FORM method =\"POST>\">");

替换为

out.write("<FORM method =\"POST\">");