2

I'm forwarding to a jsp that shows a table and a form for comments populated by jstl sql tags.

The problem is that the form works fine if I use response.sendRedirect("comments.jsp");

But since I need to retain session info between pages I want to use request.getRequestDispatcher("comments.jsp").forward(request, response); which triggers the post form and redirects subsequent posts to the servlet url.

LoginServlet

public class LoginServlet extends HttpServlet {
    Connection connection = null;
    PreparedStatement ptmt = null;
    ResultSet resultSet = null;
    User user = null;
    boolean fail = true;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String email = request.getParameter("email");
        String password = request.getParameter("password");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        if (null != email && null != password) {
            try {
                connection = ConnectionFactory.getInstance().getConnection();
                user = new User();
                String queryString = "SELECT * FROM USERINFO WHERE EMAIL=?";
                ptmt = connection.prepareStatement(queryString);
                ptmt.setString(1, email);
                resultSet = ptmt.executeQuery();
                resultSet.next();
                user.setEmail(resultSet.getString("EMAIL"));
                ...                    
                user.setSecret3(resultSet.getString("SECRET3"));
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            } finally {
            }
        }
        if (null != user.getPassword() && user.getPassword().equals(password)) {
            request.setAttribute("user",user);
            request.getRequestDispatcher("comments.jsp").forward(request, response);  
//            response.sendRedirect("comments.jsp");  

        }

comments.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Comments</title>
    </head>
    <body>
        <sql:setDataSource var="dataSource" driver="org.apache.derby.jdbc.ClientDriver"
                           url="jdbc:derby://localhost:1527/mp1"
                           user="app"  password="app"/>

        <sql:setDataSource var="dataSource2" driver="org.apache.derby.jdbc.ClientDriver"
                           url="jdbc:derby://localhost:1527/mp1"
                           user="app"  password="app"/>

        <H2>Comments</H2>

        <sql:query dataSource="${dataSource}" sql="SELECT * FROM COMMENTS" var="comments" />
        <table border=1>
            <c:forEach var="row" items="${comments.rows}">
                <tr>
                    <c:forEach var="col" items="${row}">
                        <td><c:out value="${col.value}" /></td>
                    </c:forEach>  
                </tr>
            </c:forEach>
        </table>  

        <form method="post">
            <table>
                <tr>
                    <td>Enter Email</td>
                    <td><input type="text" name="EMAIL"></td>
                </tr>
                <tr>
                    <td>Enter Comment</td>
                    <td><input type="text" name="COMMENT"></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="submit"></td>
                </tr>
            </table>
        </form>
        <c:if test="${pageContext.request.method=='POST'}">
            <c:catch var="exception">
                <sql:update dataSource="${dataSource2}" var="updatedTable">
                    INSERT INTO 
                    COMMENTS (EMAIL,COMMENT) 
                    VALUES (?, ?)
                    <sql:param value="${param.EMAIL}" />
                    <sql:param value="${param.COMMENT}" />
                </sql:update>
                <c:if test="${updatedTable>=1}">
                    <c:redirect url="/comments.jsp"/>
                </c:if>
            </c:catch>
            <c:if test="${exception!=null}">
                <c:out value="Unable to add comment." />
            </c:if>
        </c:if>
    </body>
</html>

BTW, this is a homework assignment were the teacher wants us learn how it was done the old way. So security and better technologies to use are not real concerns.

PS. I've solved this by separating the comments and add comment into separate pages. Perhaps a better solution would be to use the session instead of the request for object transfer.

jeremyjjbrown
  • 7,772
  • 5
  • 43
  • 55
  • 1
    This is not part of the answer but a recommendation: Don't define attributes in your servlet, they won't be thread safe. Read more about how servlets work here: [How do servlets work? Instantiation, session variables and multithreading](http://stackoverflow.com/a/3106909/1065197) – Luiggi Mendoza Sep 22 '12 at 23:21
  • whats happening after the last if statement in your servlet? The code cuts off. – Sean Sep 23 '12 at 01:13
  • @ Sean, Logic that directs to a different page. Nothing that could effect the outcome since it would not be executed. – jeremyjjbrown Sep 23 '12 at 01:25
  • 2
    Huh? 4 upvotes for a question wherein the concrete problem/question isn't been elaborated at all? The only problem description is in the title and says "causes form submission errors". What kind of errors are you talking about? What exactly happens (not)? Why isn't this elaborated *anywhere* in the question? The question is absolutely unclear. By the way, there's also some misunderstanding in concepts or terms: the "session info" has a longer lifetime than a redirect, perhaps you actually meant to say "request info"? Anyway, this doesn't seem to be related to the concrete problem. – BalusC Sep 23 '12 at 03:35
  • @Oleg Mikheev: please read the homework tag wiki – Mat Sep 23 '12 at 06:55
  • Homework tag is being deprecated. I started to add it but stackoverflow asked me not to. – jeremyjjbrown Sep 23 '12 at 14:05
  • @BalusC For someone intent on lecturing us all you sure do a poor job of reading. "which triggers the post form and redirects subsequent posts to the servlet url." – jeremyjjbrown Sep 23 '12 at 14:09
  • Sorry, I would indeed never have interpreted that sentence as a concrete problem description with a question. I do by the way still not understand the concrete problem, let alone how the answer posted so far was helpful in any way. But OK, it'll be my poor reading skills. Glad you "solved" it. – BalusC Sep 23 '12 at 20:35

1 Answers1

1
  1. Both redirect and forward should retain session since session is supported by cookies (in most cases).

  2. Your form doesn't have action parameter thus its behavior depends on the browser current URL (form gets posted to current URL instead of defined in action), and current URL is different in case of redirect and forward.

Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95
  • "Both redirect and forward should retain session", sure but I put the data into the request, which is not retained by by redirect. – jeremyjjbrown Sep 23 '12 at 14:07