mercredi 29 mars 2017

Servlet error in doGet when POST request

I'm building a website with a chat using a Tomcat server. For that chat, I've got a form (with text input) that calls a JS function, that performs a jQuery POST request...

<!DOCTYPE html>

<html>
<body>
    <form method="post" action="javascript:submitNewMessage()" accept-charset="UTF-8" id="msgForm">
        <input type="text" name="msg" id="msgField"/>
        <input type="submit" name="submit" value="Send"/>
    </form>

    <script src="jquery.js"></script>
    <script>
"use strict";

function submitNewMessage() {
var msg = document.getElementById("msgField").value;
$.post("chatController", {message:msg, author:"${user.username}", gameId:"${game}", chat:"${chat.type}"});
}
</script>
</body>
</html>

... to this controller, chatController.java :

@WebServlet(urlPatterns = {"/chatController"})
public class ChatController extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    request.setAttribute("user", new User(request.getParameter("user")));
    request.setAttribute("game", Integer.parseInt(request.getParameter("gameId")));
    request.setAttribute("chat", new ChatRoom(ChatRoomType.fromString(request.getParameter("chat"))));
    request.setAttribute("lastMessage", 0);

    request.getRequestDispatcher("/WEB-INF/chat.jsp").forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try {
        ChatDAO dao = new ChatDAO(this.ds);
        if (dao.submitMessage(...) // not implemented yet, returns false) {
                throw new ServletException();
            }
    } catch (Exception e) {
        response.sendError(400);
    }
}
}

The GET of chatController is used when the user joins the chat, and then only POST is used to submit messages. When I join the chat page, no error. But when I submit a message, the debugger (of Firefox) tells me XML parsing error : no element found at line 1. The HTML returned by chatController contains a Java error in the doGet method (NumberFormatException: null, at the 2nd line of doGet, where I do Integer.parseInt).

Why is the doGet method called here ? I do a POST request on chatController... And when I print something in doGet, it doesn't appear in the log : so why is that line throwing an error ? What's wrong with that code ?

Thanks for any help.




Aucun commentaire:

Enregistrer un commentaire