为什么我在调用validate servlet时会收到java.lang.IllegalStateException?

时间:2016-08-29 06:20:40

标签: java jsp servlets

我有一个登录Web应用程序。 每当我登录时,必须通过验证Servlet验证请求,并且必须将其转发到admin.jsp 一切都很好,除了我得到了这个异常java.lang.IllegalStateException。

代码:

/*
 * DEVELOPER : SURAJ GAUTAM
 * CAMPUS: SHANKERDEV
 * FACULTY: BIM
 * COMPANY : UNKNOWN IT COMPANY
 */
package com.suraj.technepbankapplication;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Suraj Gautam
 */
@WebServlet(name = "validate", urlPatterns = {"/validate"})
public class validate extends HttpServlet {

DataBean bean = new DataBean();
int count = 0;

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

}




@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //the form inputted is sent to the Databean Class

    settingValue(req.getParameter("userid"), req.getParameter("password"));
    try {
        if (!isValid(req, resp)) {

           req.getRequestDispatcher("/index.jsp").forward(req, resp);
        } else if (bean.getUserId().equals("admin")) {

          req.getRequestDispatcher("/admin.jsp").forward(req, resp);
        } else {

            req.getRequestDispatcher("/afterlogin.jsp").forward(req, resp);
        }
    } catch (SQLException | ClassNotFoundException ex) {
        System.out.println(ex.getMessage());
    }

}

public boolean isValid(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, ClassNotFoundException {
    String userId = req.getParameter("userid");
    String password = req.getParameter("password");
    if (userId.length() <4 || password.length() < 4) {
        return false;
    } else {
        return loginValidate(req, resp);
    }
}

//setting DataBean class Value
public void settingValue(String userid, String password) {

    bean.setUserId(userid);
    bean.setPassword(password);
}

public boolean loginValidate(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, ClassNotFoundException {
    String url = "jdbc:mysql://localhost/technep";
    String user = "root";
    String password = "";
    String query = "SELECT id, password FROM technep_login";

    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection(url, user, password);

    PreparedStatement preparedStatement = conn.prepareStatement(query);

    ResultSet resultSet = preparedStatement.executeQuery();
    while (resultSet.next()) {
        //working till here
        if (resultSet.getString("id").trim().equals(bean.getUserId()) && resultSet.getString("password").trim()
                .equals(bean.getPassword())) {
            count = 1;
            break;

        }

    }
    if (count == 1) {
        return true;
    } else {
        return false;
    }

}
}

输出:

Warning:   StandardWrapperValve[jsp]: Servlet.service() for servlet jsp    threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:777)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:224)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:195)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:188)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:240)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:185)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:137)
at org.apache.jsp.DBimage_jsp._jspService(DBimage_jsp.java:93)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at       org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPoo    l.java:571)
at java.lang.Thread.run(Thread.java:745)

1 个答案:

答案 0 :(得分:0)

很抱歉,根据您提供的堆栈跟踪,这个问题是无法解决的:servlet甚至没有出现在堆栈跟踪中,因此要么这个servlet不是问题,要么你省略了&#34;根本原因&#34;栈跟踪。

此外,您的代码存在很多问题,您应该通过servlet开发的基本教程。这些不能在stackoverflow上的单个答案中得到纠正

  • 使用bean作为servlet成员的方式将导致灾难(竞争条件)。您不能在servlet中拥有成员变量(state)。
  • 您自己负责身份验证 - 您显然不应该这样做,这是一个解决得很好的问题
  • 最重要的是,您显然在数据库中存储了明文密码,并且您始终枚举整个用户数据库,而不是仅仅获取单个值(想象有很多用户......)
  • 从此代码开始,我假设您也可以手动转到/afterlogin.jsp/admin.jsp来跳过验证。
  • 您的方法的参数也是可论证的,并且创建了难以维护的实现。

这是一份不完整的清单。