[java] The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I want to run easy registration jsp page with servlet. And it throw this error message:

description The server encountered an internal error that prevented it from fulfilling this request.

java.lang.NullPointerException
    com.java.task11.utils.ValidationUtils.isEmailValid(ValidationUtils.java:22)
    com.java.task11.webapp.RegistrationServlet.validateInputs(RegistrationServlet.java:95)
    com.java.task11.webapp.RegistrationServlet.processRegistration(RegistrationServlet.java:66)
    com.java.task11.webapp.RegistrationServlet.doPost(RegistrationServlet.java:39)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Here is my registration.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<c:set var="language"
       value="${not empty param.language ? param.language : not empty language ? language : pageContext.request.locale}"
       scope="session"/>
<fmt:setLocale value="${language}"/>
<fmt:setBundle basename="com.java.task11.i18n.text"/>

<html lang="${language}">
<head>
    <title>Registration</title>
    <jsp:include page="parts/header.jsp"/>
</head>

<body>
<div class="container-fluid registration">
    <div class="row">
        <div class="login-screen">
            <div class="login-part">
                <div class="login-ico col-md-1 col-sm-2 col-xs-12 col-md-offset-3">
                    <h4>
                        <small><fmt:message key="registration.label"/></small>
                    </h4>
                </div>
                <div class="login-form col-md-4 col-sm-8 col-xs-12 col-md-offset-1 col-sm-offset-1">
                    <form action="/registration" enctype="multipart/form-data" method="post">
                        <%-- error messages --%>
                        <div class="form-group">
                            <c:forEach items="${registrationErrors}" var="error">
                                <p class="error">${error}</p>
                            </c:forEach>
                        </div>
                        <%-- input fields --%>
                        <div class="form-group">
                            <input class="form-control" placeholder="<fmt:message key="employee.firstName"/>" name="first_name" required
                                   id="first-name"/>
                            <label class="login-field-icon fui-user"></label>
                        </div>
                        <div class="form-group">
                            <input class="form-control" placeholder="<fmt:message key="employee.lastName"/>" name="last_name" required
                                   id="last-name"/>
                            <label class="login-field-icon fui-user"></label>
                        </div>
                        <div class="form-group">
                            <div class="input-group">
                                <span class="input-group-btn">
                                    <span class="btn btn-primary btn-file">
                                    <fmt:message key="button.browse"/>
                                    <input type="file" name="userImage" accept="image/*"/>
                                    </span>
                                </span>
                                <input type="text" class="form-control" readonly="">
                            </div>
                        </div>
                        <div class="form-group">
                            <input class="form-control" type="email" placeholder="<fmt:message key="login.email"/>" name="email"
                                   pattern="[^ @]*@[^ @]*\.[^ @]{2,}" required id="email"/>
                            <label class="login-field-icon fui-mail"></label>
                        </div>
                        <div class="form-group">
                            <input class="form-control" type="password" placeholder="<fmt:message key="employee.password"/>" name="password" required
                                   id="password"/>
                            <label class="login-field-icon fui-lock"></label>
                        </div>
                        <div class="form-group">
                            <input class="form-control" type="text" placeholder="<fmt:message key="employee.position"/>" name="position" required
                                   id="position"/>
                            <label class="login-field-icon fui-plus"></label>
                        </div>
                        <div class="form-group">
                            <button class="btn btn-primary btn-lg btn-block" name="submit"
                                    type="submit" value="Submit">
                                <fmt:message key="button.submit"/>
                            </button>
                            <a class="login-link" href="<c:url value="/login"/>"><fmt:message key="registration.login"/></a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<jsp:include page="parts/scripts.jsp"/>
</body>
</html>

RegistrationServlet:

@WebServlet("/registration")
public class RegistrationServlet extends HttpServlet {
    private static Logger log = Logger.getLogger(RegistrationServlet.class);
    private EmployeeService employeeService = new EmployeeService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.getRequestDispatcher("/pages/registration.jsp").forward(request, response);
        } catch (ServletException | IOException e) {
            log.error(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            processRegistration(request, response);
        } catch (ServletException | IOException e) {
            log.error(e);
            e.printStackTrace();
        }
    }

    private void processRegistration(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String firstName = request.getParameter("first_name");
        String lastName = request.getParameter("last_name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String imageName = "default.png";
        String position = request.getParameter("position");

        System.out.printf("Request fields: %s %s %s %s %s%n", firstName, lastName, email, password, position);

        Part filePart = request.getPart("userImage");
        try {
            String contentType = filePart.getContentType();
            if (contentType.startsWith("image")) {
                File image = FileUploadUtils.uploadFile(this, "img\\employees", filePart);
                imageName = FileUploadUtils.getFilename(image);
            }
        } catch (Exception e) {
            log.error(e);
        }

        List<String> registrationErrors = validateInputs(firstName, lastName, email, password, position);

        if (registrationErrors.size() > 0) {
            request.setAttribute("registrationErrors", registrationErrors);
            request.getRequestDispatcher("/pages/registration.jsp").forward(request, response);
        } else {
            Employee employee = new Employee();
            employee.setFirstName(firstName);
            employee.setLastName(lastName);
            employee.setEmail(email);
            employee.setEncryptedPassword(password);
            employee.setImage(imageName);
            employee.setPosition(position);

            employeeService.save(employee);
            response.sendRedirect("/login");
        }

    }

    private List<String> validateInputs(String firstName, String lastName, String email, String password, String position) {
        List<String> registrationErrors = new ArrayList<>();

        if (ValidationUtils.isNullOrEmpty(firstName)) {
            registrationErrors.add(ValidationErrors.FIRST_NAME);
        }
        if (ValidationUtils.isNullOrEmpty(lastName)) {
            registrationErrors.add(ValidationErrors.LAST_NAME);
        }
        if (!ValidationUtils.isEmailValid(email)) {
            registrationErrors.add(ValidationErrors.EMAIL);
        }
        if (employeeService.getByEmail(email).getId() != 0) {
            registrationErrors.add(ValidationErrors.EMAIL_ALREADY_PRESENT);
        }
        if (ValidationUtils.isNullOrEmpty(password)) {
            registrationErrors.add(ValidationErrors.PASSWORD);
        }
        if (!ValidationUtils.isNullOrEmpty(position)) {
            registrationErrors.add(ValidationErrors.POSITION_EMPTY);
        }
        return registrationErrors;
    }
}

It couldn't extract from request parameters. From my easy checking it prints:

Request fields: null null null null null

I couldn't figure out why this happen?

Any suggestions?

This question is related to java jsp nullpointerexception servlet-3.0

The answer is


In here:

    if (ValidationUtils.isNullOrEmpty(lastName)) {
        registrationErrors.add(ValidationErrors.LAST_NAME);
    }
    if (!ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do

    if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jsp

Difference between request.getSession() and request.getSession(true) A child container failed during start java.util.concurrent.ExecutionException The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path Using if-else in JSP Passing parameters from jsp to Spring Controller method how to fix Cannot call sendRedirect() after the response has been committed? How to include js and CSS in JSP with spring MVC How to create an alert message in jsp page after submit process is complete getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How to pass the values from one jsp page to another jsp without submit button?

Examples related to nullpointerexception

Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference Null pointer Exception on .setOnClickListener - java.lang.NullPointerException - setText on null object reference NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference Java 8 NullPointerException in Collectors.toMap NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

Examples related to servlet-3.0

What is difference between @RequestBody and @RequestParam? The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0 Recommended way to save uploaded files in a servlet application How to set up JAX-RS Application using annotations only (no web.xml)? Can't import javax.servlet.annotation.WebServlet