0

I was wondering about the net to use MVC in my JSP project and found a great discussion here, now I have following:

public class Subject {
private String subjectId = null;
private String subjectName = null;

public String getSubjectId() {
    return subjectId;
}

public void setSubjectId(String subjectId) {
    this.subjectId = subjectId;
}

public String getSubjectName() {
    return subjectName;
}

public void setSubjectName(String subjectName) {
    this.subjectName = subjectName;
}
}

and my SubjectDAO class is :

public class SubjectDAO {

public List<Subject> subjectList() throws SQLException{
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    List<Subject> subjects = new ArrayList<>();

    try {
        connection = DatabaseManager.initConnection();
        statement = connection.prepareStatement(Constant.SUBJECT_QUERY);
        resultSet = statement.executeQuery();

        while (resultSet.next()) {
            Subject subject = new Subject();
            subject.setSubjectId(resultSet.getString("_id"));
            subject.setSubjectName(resultSet.getString("subj_name"));               
            subjects.add(subject);
        }
    } finally {
        if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
        if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
        if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
    }

    return subjects;
}
}

and in my ControllerServlet I have :

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
try {
        List<Subject> subjects = subjectDAO.subjectList();          
        request.setAttribute("subjects", subjects);
        getServletContext().getRequestDispatcher("/content.jsp").forward(
                request, response);
    } catch (Exception e) {
        throw new ServletException("Cannot obtain subjects from DB", e.getCause());
    }
}

my JSP as View is :

    <c:forEach items="${subjects}" var="subject">                       
    <li
        <c:catch>
            <c:choose>
                <c:when test="${subject.subjectId == param.subj_id}">
                <c:out value="class=\"selected\""/>
                </c:when>
            </c:choose> 
        </c:catch>                      
    ><a href='/programming-iqs/admin-controller?action=manage-content&amp;subj_id=
    <c:out value="${subject.subjectId}"/>'>
    <c:out value="${subject.subjectId}"/>
    </a> 
        </li>
   </c:forEach>

using the code above I'm getting :

javax.servlet.ServletException: Cannot obtain subjects from DB

I'm unable to resolve this issue, any help is greatly appreciated.

NOTE

Before using/implementing MVC my code for JSP was :

<%
ResultSet sujectResult = DatabaseManager.getSubjects();

    while (sujectResult.next()) { %>
        <li <%
            String selectedSubject = request.getParameter("subj_id");
            try {
                if (selectedSubject.equals(sujectResult.getString("_id"))) {%>
                                class="selected" <%}%>><a
                        href='/programming-iqs/admin-controller?action=manage-content&amp;subj_id=
<%= sujectResult.getString("_id")%>'>
<%= sujectResult.getString("subj_name")%>
</a> <%
} catch (NullPointerException e) {

} 


} %></li>

and off-course that code was working very well, now please help me in implementing MVC. Thanks

Community
  • 1
  • 1
Arshad Ali
  • 3,082
  • 12
  • 56
  • 99
  • Which framework are you using? Or you want to implement MVC guidelines using servlets/Jsps? – Shailesh Saxena May 15 '14 at 04:42
  • Can you give more details on your error. Try to add a `e.printStackTrace()` in the catch block of the `doGet()` method – AdityaKeyal May 15 '14 at 04:43
  • @ShaileshSaxena I'm simply using servlets/Jsps. – Arshad Ali May 15 '14 at 04:44
  • The exception occurred inside SubjectDAO.subjectList. You need whole stack trace to understand what happened. – Roman May 15 '14 at 04:44
  • @Super User - is it for education purposes or for real production use? If latter then I would strongly suggest to use an open source framework like Struts 2 or Spring MVC, why reinvent the wheel? – Roman May 15 '14 at 04:46
  • @Roman this is for Children of my village and I'm only trying to make a MCQs website for them to take their exams. – Arshad Ali May 15 '14 at 04:49
  • @AdityaKeyal `e.printStackTrace()` givis me `java.lang.IllegalStateException: Cannot forward after response has been committed`. – Arshad Ali May 15 '14 at 04:50
  • @SuperUser still I would go with a framework. What srarts as a small project can grow into a big project over time and investing a bit of time into right approach from the beginning will pay off big time. – Roman May 15 '14 at 04:51
  • @Roman very much kind of you for suggestion, but can you please give me solution of above `Context`. – Arshad Ali May 15 '14 at 04:54
  • 1
    @Super User: Do you have any other redirect/forward statement before getServletContext().getRequestDispatcher("/content.jsp").forward( request, response); in your servlet? or you trying to write something to response using out.write after forwarding the control? – Shailesh Saxena May 15 '14 at 05:00
  • add e.printStackTrace(); before `throw new ServletException("Cannot obtain subjects from DB", e.getCause());` – Scary Wombat May 15 '14 at 05:01
  • Try to change the code `getServletContext().getRequestDispatcher("/content.jsp").forward(request, response);` to `request.getRequestDispatcher("/content.jsp").forward(request, response);` and see – AdityaKeyal May 15 '14 at 05:06

2 Answers2

1

General reason of java.lang.IllegalStateException: Cannot forward after response has been committed exception is any one of below:

  1. You already redirected/forwarded the control from your servlet/JSp and still trying to write something to response using outStream out.write("something")
  2. You already redirected control from your Servlet/JSp and again trying to send control somewhere from same servlet/JSP below previous Redirect/Forward without proper conditions( Though based on conditions you can redirect/forward to different resources but two redirect/forward should not contradict/conflict to each other)

For example: This is correct --

if(condition1)
 redirect to resource 1
else if(condition 2)
 redirect to resource 2
else
 redirect to resource 3

But this is wrong --

if(condition 1)
 redirect to resource 1
again
 redirect to resource 2

For more info refer to these links: Link1 Link2 Link3

Community
  • 1
  • 1
Shailesh Saxena
  • 3,472
  • 2
  • 18
  • 28
-1

You can add e.printStackTrace();

    protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
try {
        List<Subject> subjects = subjectDAO.subjectList();          
        request.setAttribute("subjects", subjects);
        getServletContext().getRequestDispatcher("/content.jsp").forward(
                request, response);
    } catch (Exception e) {
        e.printStackTrace();
        throw new ServletException("Cannot obtain subjects from DB", e.getCause());
    }
}

Then just check your app server console. It should show you what's the problem.

Roman
  • 1,278
  • 2
  • 12
  • 14