使用 JSP、Servlet、JSTL 和命令模式显示数据库中的数据
Posted
技术标签:
【中文标题】使用 JSP、Servlet、JSTL 和命令模式显示数据库中的数据【英文标题】:Display data from a database using JSP, Servlets, JSTL and Command Pattern 【发布时间】:2013-05-06 00:27:36 【问题描述】:我正在尝试显示数据库中的数据,但在 JSP 上没有任何反应。我使用了设计模式命令。我的问题在哪里?
命令设计模式的结构:
这是我的代码:
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" >
<tr>
<td colspan="2" class="logo"><a href="http://localhost:8080/Blog_App/"> <img 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">© Stark, 2013 </span><a href="about.jsp">О проекте</a>
</td>
</tr>
</table>
</body>
</html>
我的控制器:
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;
我的视图命令:
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;
我的视图逻辑:
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;
【问题讨论】:
感谢您的努力,但有没有办法可以让问题更具体一些?无论如何都要为明显的努力+1。 主要问题是我的类ViewCommand没有被调用 我强烈建议在这种情况下使用调试器(这就是它们的用途)。 你在哪个JSP中调用控制器,你的JSP中没有form
。
【参考方案1】:
我在 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、Servlet、JSTL 和命令模式显示数据库中的数据的主要内容,如果未能解决你的问题,请参考以下文章
熟悉基于JSP和Servlet的Java Web开发,对Servlet和JSP的工作原理和生命周期有深入了解,熟练的使用JSTL和EL编写无脚本动态页面,有使用监听器过滤器等Web组件以及MVC架构
从servlet跳到jsp页面,并用jstl 进行判断和显示方法