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

StackOverflow https://stackoverflow.com/questions/22335466

Pregunta

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?

¿Fue útil?

Solución 2

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top