Display data from a database using JSP, Servlets, JSTL and Command Pattern

stark picture stark · May 11, 2013 · Viewed 8.8k times · Source

I'm trying to display data from a database, but nothing happens on JSP. I used a design pattern Command. Where is my problem?

Structure of Command design pattern:

enter image description here

Here is my code:

JSP page:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Profile page</title>
</head>
<body>

<table border="0" align="center" class="container" width="80%">

<tr>
<td width="100%" colspan="2" class="logo"><a href="http://localhost:8080/Blog_App/">        <img alt="Logo" src="img/logo.png"></a></td>
</tr>
<tr>
<td class="content">
<div class="edit">

<input type="hidden" name="command" value="view" />
<c:forEach var="item" items="${viewList}">
<c:out value="${item.header}" /><br>
<c:out value="${item.text}" /><br>
</c:forEach>

</div>
</td>

<td class="control">
<div class="reg">

<h3>Hello</h3>
<p>Your Profile</p>
</div>
</td>

</tr>
<tr>
<td colspan="2" class="about">
<span class="copyright">&#169 Stark, 2013 </span><a href="about.jsp">О проекте</a>
</td>
</tr>

</table>

</body>
</html>

My Controller:

package com.stark.controller;

//imports

@WebServlet("/controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;

RequestHelper requestHelper = RequestHelper.getInstance();

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

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

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");

    String page = null;
    try{
        Command command = requestHelper.getCommand(request);
        page = command.execute(request, response);
    } catch (ServletException e) {
        e.printStackTrace();
    }
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
    dispatcher.forward(request, response);
}

}

My RequestHelper:

package com.stark.controller;

//imports

public class RequestHelper {

public static RequestHelper instance = null;
HashMap<String, Command> commands = new HashMap<String, Command>();

private RequestHelper(){
    commands.put("reg", new RegCommand());
    commands.put("login", new LoginCommand());
    commands.put("edit", new EditCommand());
    commands.put("view", new ViewCommand());
    System.out.println("Helper Works");
}

public Command getCommand(HttpServletRequest request){
    String action = request.getParameter("command");
    Command command = commands.get(action);
    if(command == null){
        command = new NoCommand();
    }
    return command;
}

public static RequestHelper getInstance(){
    if(instance == null){
        instance = new RequestHelper();
    }
    return instance;
}
}

My Interface Command:

package com.stark.command;

//imports

public interface Command {
public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}

My ViewCommand:

package com.stark.command;

//imports

public class ViewCommand implements Command{

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");

    System.out.println("View Command Works");

    String page = null;

    HttpSession ses = request.getSession();
    String username = (String) ses.getAttribute("username");

    ViewLogic viewLogic = new ViewLogic();

    List<Posts> viewList = new ArrayList<Posts>(); 
    viewList = viewLogic.getPostsList(username);
    request.setAttribute("viewList", viewList);

    page = "/profile.jsp";

    return page;
}

}

My ViewLogic:

package com.stark.logic;

//imports

public class ViewLogic {

public List<Posts> getPostsList(String username){
    System.out.println("Logic View Check");
    int author_id = 0;
    List<Posts> viewList = new ArrayList<Posts>();

    User user = new User();
    user.setUsername(username);

    UserDAO userDAO = new UserDAO();
    author_id = userDAO.checkID(user);

    PostsDAO postsDAO = new PostsDAO();
    viewList = postsDAO.viewPosts(author_id);

    return viewList;
}

}

And my postsDAO:

package com.stark.dao;

//imports

public class PostsDAO {

private Connection con = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;

public PostsDAO(){
    con = DBConnection.getConnection();
}

public void addPost(int id, Posts posts){
    try {
        pstmt = con.prepareStatement("INSERT INTO posts (author_id, header,  text) VALUES (?, ?, ?)");
        pstmt.setInt(1, id);
        pstmt.setString(2, posts.getHeader());
        pstmt.setString(3, posts.getText());
        pstmt.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            pstmt.close();
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }   
    }
}

public List<Posts> viewPosts(int author_id){
    List<Posts> viewList = new ArrayList<Posts>();
    try {
        System.out.println("Check 1");
        pstmt = con.prepareStatement("SELECT posts.header, posts.text FROM posts WHERE author_id = ?;");
        pstmt.executeQuery();
        rs = pstmt.getResultSet();
        while(rs.next()){
            Posts posts = new Posts();
            posts.setHeader(rs.getString("header"));
            posts.setText(rs.getString("text"));
            viewList.add(posts);
            System.out.println(rs.getString("header") + rs.getString("text"));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return viewList;
}

}

Answer

stark picture stark · May 11, 2013

I found error in my PostsDAO:

public List<Posts> viewPosts(int author_id){
    System.out.println(author_id);
    List<Posts> viewList = new ArrayList<Posts>();
    try {
        System.out.println("Check 1");
        pstmt = con.prepareStatement("SELECT posts.header, posts.text FROM posts WHERE author_id = ?;");
//I forgot set parameter for ?
        pstmt.setInt(1, author_id);
        pstmt.executeQuery();
        rs = pstmt.getResultSet();
        while(rs.next()){
            Posts posts = new Posts();
            posts.setHeader(rs.getString(1));
            posts.setText(rs.getString(2));
            viewList.add(posts);
            System.out.println(rs.getString("header") + rs.getString("text"));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return viewList;
}

And in my JSP page I added tag, but it's works when I press the submit button. How to make autosubmited form?

JSP code:

<form action="controller" method="get">
<input type="hidden" name="command" value="view" />
<c:forEach var="item" items="${viewList}">
<c:out value="${item.header}" /><br>
<c:out value="${item.text}" /><br>
</c:forEach>
<input type="submit">
</form>