jsp - 使用 JSP、Servlet、JSTL 和命令模式显示数据库中的数据

标签 jsp jakarta-ee servlets dao command-pattern

我正在尝试显示数据库中的数据,但在 JSP 上没有任何 react 。我使用了一个设计模式命令。我的问题在哪里?

命令设计模式的结构:

enter image description here

这是我的代码:

JSP页面:

<%@ 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>

我的 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);
}

}

我的请求助手:
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;
}
}

我的界面命令:
package com.stark.command;

//imports

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

我的 View 命令:
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;
}

}

我的 View 逻辑:
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;
}

}

还有我的帖子DAO:
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;
}

}

最佳答案

我在 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;
}

在我的 JSP 页面中,我添加了标签,但是当我按下提交按钮时它就起作用了。如何制作自动提交的表格?

JSP代码:
<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>

关于jsp - 使用 JSP、Servlet、JSTL 和命令模式显示数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16497186/

相关文章:

java - 在 tomcat servlet 中检测客户端断开连接?

java - 如何在 Spring Boot 应用程序中配置 DispatcherServlet?

java - 使用 servlet 的正确方法是什么?

jsp - 如何使用c :out tag in some format显示日期

java - 为什么当有很多请求时应用程序会挂起?

java - JPA:读取并坚持一个事务,同时阻塞不同线程中的读取

java - 如何从 Servlet 访问/调用 Java 程序

java - 从网页中的 servlet 读取 Quicktime 电影?

spring - 在JSP页面中获取用户名。主体.用户名不起作用

java - 表达语言 : how to simplify this statement ("in"-like clause needed)