'Why I am getting java.lang.IllegalStateException when the validate servlet is called?

I have a login web application. Whenever I login, the request must be validated by validate Servlet and it must be forwarded to admin.jsp Everything is fine except I got this exception java.lang.IllegalStateException.

Code:

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;
    }

}
}

The output:

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)


Solution 1:[1]

Sorry, this question is unanswerable based on the stacktrace you give: The servlet does not even appear in the stacktrace, so either this servlet can't be the problem or you're omitting the "root cause" stacktrace.

Further, there are a lot more problems with your code and you should really go through a basic tutorial for servlet development. These can't be corrected in a single answer on stackoverflow

  • The way you use bean as a member of your servlet will result in disaster (race condition). You must not have member variables (state) in a servlet.
  • You're taking care of authentication yourself - you clearly shouldn't do this, it's a well solved problem
  • On top, you're obviously storing clear text passwords in the database and you're always enumerating the whole user database instead of just fetching a single value (imagine to have many users...)
  • From this code I'm assuming that one can also skip the validation by just going to /afterlogin.jsp or /admin.jsp manually.
  • The parameters to your methods are arguable as well and create a hard to maintain implementation.

This is an incomplete list.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Olaf Kock