Home>

I recently started learning java.
I am making a login screen with java, but when it is entered in the wrong format on the user information registration screen
I want to display an error notification on the login screen, but it doesn't work.
If i try just by registering without error notification, it will work, but if you write the error notification code, you will get an error.
I think that there is a difficulty in using forward from the content of the error,
I don't know the cause, so could you please teach me?

Type Exception Report
Unable to forward after committing message response
Explanation The server has encountered an unexpected condition. It prevents the request from being executed.
exception
java.lang.IllegalStateException: Unable to forward after committing response
    database.InsertCustomer.doPost (InsertCustomer.java:68)
    javax.servlet.http.HttpServlet.service (HttpServlet.java:652)
    javax.servlet.http.HttpServlet.service (HttpServlet.java:733)
    org.apache.tomcat.websocket.server.WsFilter.doFilter (WsFilter.java:53)
Caution All stack traces of the cause are logged on the server
Corresponding source code
<% @ page language = "java" contentType = "text/html;charset = UTF-8"
    pageEncoding = "UTF-8"%><% @ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%><! DOCTYPE html><html><head><meta charset = "UTF-8"><title>Insert title here</title><link rel = "stylesheet" href = "WEB-INF/style.css"></head><body><form action = "database/InsertCustomer" method = "POST">${param ['errors']}<table><tr><th align = "right">Name:</th><td><input type = "text" name = "name" size = 35 maxlength = "20"></td></tr><tr><th align = "right">email address:</th><td><input type = "text" name = "email" size = 35 maxlength = "50"></td></tr><tr><th align = "right">Password:</th><td><input type = "password" name = "password" size = 35 minlength = "8" maxlength = "15"></td></tr><tr><th align = "right">Password (for confirmation):</th><td><input type = "password" name = "validation" size = 35 minlength = "8" maxlength = "15"></td></tr><tr><th align = "right">Address:</th><td><input type = "text" name = "address" size = 35 maxlength = "20"></td></tr><tr><th align = "right">Phone number:</th><td><input type = "text" name = "tel" size = 35 maxlength = "15"></td></tr><tr><td colspan = "2"><input type = "submit" value = "register"></td></table></form></body></html>
package database;
import java.sql.Connection;import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
/ **
 * Servlet implementation class BaseServlet
 * /
@WebServlet ("/ database/BaseServlet")
public class BaseServlet extends HttpServlet {
    public Connection getConnection () {
        Connection con = null;
        String url = "jdbc: mariadb: // localhost: 3306/customer";
        String user = "root";
        String pass = "root";
        try {
            con = DriverManager.getConnection (url, user, pass);
        } catch (SQLException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return con;
    }
}
package database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class ErrorCheck extends BaseServlet {
    private ArrayList<String>errors = null;
    public ErrorCheck () {
        this.errors = new ArrayList<String>();
    }
  public void requiredCheck (String value, String name) {
    if (value == null || value.trim (). isEmpty ()) {
      this.errors.add (name + "is required");
    }
  }
  public void regExpCheck (String value, String pattern, String name) {
      if (! value.matches (pattern)) {
        this.errors.add (enter name + "in the correct format");
      }
    }
  public void passwordCheck (String value1, String value2) {
      if (! value1.matches ("[\\ w-\\ ./] {8,15}")) {
        this.errors.add ("Please enter the password in a combination of single-byte alphanumeric characters and symbols (-./_)");
      } else if (value1! = value2) {
        this.errors.add ("Passwords do not match");
      }
    }
  public void duplicateCheck (String value, String name) {
    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
      con = super.getConnection ();
      stmt = con.prepareStatement ("SELECT * FROM customer WHERE email =?");
      stmt.setString (1, value);
      rs = stmt.executeQuery ();
      if (rs.next ()) {this.errors.add (name + "duplicate");}
    } catch (SQLException e) {
      e.printStackTrace ();
    } catch (Exception e) {e.printStackTrace ();
    } finally {
      try {
        if (rs! = null) {rs.close ();}
        if (stmt! = null) {stmt.close ();}
        if (con! = null) {con.close ();}
      } catch (SQLException e) {
        e.printStackTrace ();
      } catch (Exception e) {
        e.printStackTrace ();
      }
    }
  }
  public boolean hasErrors () {
      return! this.errors.isEmpty ();
  }
  public String getErrorList () {
      StringBuffer buff = new StringBuffer ();
      buff.append ("<ul style ='color: red;'>");
      for (String err: errors) {
          buff.append ("<li>" + err + "</li>");
      }
      buff.append ("</ul>");
      return buff.toString ();
  }
}
package database;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/ **
 * Servlet implementation class InsertCustomer
 * /
@WebServlet ("/ database/InsertCustomer")
public class InsertCustomer extends BaseServlet {
   /**
     * @see HttpServlet # doPost (HttpServletRequest request, HttpServletResponse response)
     * /
    protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding ("UTF-8");
        String name = request.getParameter ("name");
        String email = request.getParameter ("email");
        String password = request.getParameter ("password");
        String validation = request.getParameter ("validation");
        String address = request.getParameter ("address");
        String tel = request.getParameter ("tel");
        String mailFormat = "[\\ w \\. \\-! # $\" \'%&() = ^ ~ \ | \\ [\\] {} * +<>,? /] + @ (? : [\\ w \\-] + \\.) + [\\ w \\-] + ";
        String telFormat = "[0-9] {10,11}";
        ErrorCheck errorCheck = new ErrorCheck ();
        errorCheck.requiredCheck (name, "name");
        errorCheck.regExpCheck (email, mailFormat, "email address");
        errorCheck.passwordCheck (password, validation);
        errorCheck.regExpCheck (tel, telFormat, name);
        if (errorCheck.hasErrors ()) {
            request.setAttribute ("errors", errorCheck.getErrorList ());
            RequestDispatcher dispatch = request.getRequestDispatcher ("http: // localhost: 8080/shopinfo /");
            dispatch.forward (request, response);}
        PreparedStatement statement = null;
        Connection con = null;
        String sql = "INSERT INTO customer (name, email, password, address, tel) VALUES (?,?,?,?,?)";
        try {
            con = super.getConnection ();
            statement = con.prepareStatement (sql);
            statement.setString (1, name);
            statement.setString (2, email);
            statement.setString (3, password);
            statement.setString (4, address);
            statement.setString (5, tel);
            statement.executeUpdate ();
        } catch (SQLException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            try {
                if (statement! = null) {con.close ();}
                if (con! = null) {con.close ();}
            } catch (Exception e) {
                e.printStackTrace ();
            } finally {
            RequestDispatcher dispatch = request.getRequestDispatcher ("http: // localhost: 8080/shopinfo /");
            dispatch.forward (request, response);
            }
        }
    }
}
<? xml version = "1.0" encoding = "UTF-8"?><web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xsi: schemaLocation = "http" //xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version = "4.0"><display-name>shopinf</display-name><welcome-file-list><welcome-file>entryCustomer.jsp</welcome-file><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file></welcome-file-list><servlet><servlet-name>BaseServlet</servlet-name><servlet-class>database.BaseServlet</servlet-class></servlet><servlet-mapping><servlet-name>BaseServlet</servlet-name><url-pattern>/BaseServlet</url-pattern></servlet-mapping><servlet><servlet-name>InsertCustomer</servlet-name><servlet-class>database.InsertCustomer</servlet-class></servlet><servlet-mapping><servlet-name>InsertCustomer</servlet-name><url-pattern>/InsertCustomer</url-pattern></servlet-mapping></web-app>
What I tried

I changed the forward to a redirect and tried it, and changed the position to write the forward.

Supplementary information (FW/tool version, etc.)

PC is mac with tomcat9.0 using java15 and eclipse.

  • Answer # 1

    After specifying forward or redirect in the Request Dispatcher, if the process is described again, the process will continue. Please return;at the right time.

    if (errorCheck.hasErrors ()) {
      request.setAttribute ("errors", errorCheck.getErrorList ());
      RequestDispatcher dispatch = request.getRequestDispatcher ("Transition destination JSP");
      dispatch.forward (request, response);
      return;
    }
    // If processing continues after this, it will be executed.

Related articles