我正在制作一个简单的博客应用程序。用户输入公告,将其传递给servlet,通过DAO将其插入到POST方法的数据库中。 GET方法通过相同的DAO检索所有数据并将其传递给视图页面来创建arrayList。不确定我是否使用了正确的范围? servlet正在将公告插入数据库我肯定知道。
package testSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/testAnnounceServlet")
public class testAnnounceServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
AnnouncementDAO dao = new AnnouncementDAO();
ArrayList<Announcement> announcementList = new ArrayList<>(dao.getAllAnnouncements());
request.setAttribute("jspList", announcementList);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/testPost.jsp");
rd.forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String sentAnnouncement = request.getParameter("announceText");
Announcement announcementForDatabase = new Announcement();
AnnouncementDAO writeDAO = new AnnouncementDAO();
if(sentAnnouncement != null)
{
announcementForDatabase.setDate();
announcementForDatabase.setAnnouncement(sentAnnouncement);
try {
writeDAO.writeAnnouncement(announcementForDatabase);
response.sendRedirect("/test/testPost.jsp");
}
catch (Exception ex)
{
Logger.getLogger(testAnnounceServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
response.sendRedirect("/Error.jsp");
}
}
}
这是我的DAO
package testSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AnnouncementDAO
{
String driver = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/POSTS";
final String USER = "root";
final String PASS = "Sorosh1310";
Connection conn = null;
Statement stmt = null;
public void getConnection()
{
try
{
Class.forName(driver);
}catch (ClassNotFoundException ex)
{
Logger.getLogger(AnnouncementDAO.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
conn = DriverManager.getConnection(DB_URL,USER,PASS);
}catch (SQLException ex)
{
Logger.getLogger(AnnouncementDAO.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
if(stmt== null)
{
stmt = conn.createStatement();
}
} catch (SQLException ex)
{
Logger.getLogger(AnnouncementDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void closeConnection()
{
try
{
if(stmt!=null)
conn.close();
}catch(SQLException se)
{
}
try
{
if(conn!=null)
conn.close();
}
catch(SQLException se)
{
}
}
public void writeAnnouncement(Announcement passedAnnouncement)
throws Exception
{
Announcement dbAnnouncement = passedAnnouncement;
java.sql.Date sqlDate = dbAnnouncement.getDate();
String dbText = dbAnnouncement.getAnnouncement();
String SQL = "INSERT INTO POSTS.ANNOUNCEMENTS (AnnouncementDate, AnnouncementText)"+
"VALUES (?, ?)";
getConnection();
if(stmt != null)
{
try
{
PreparedStatement preparedStmt = conn.prepareStatement(SQL);
preparedStmt.setDate(1, sqlDate);
preparedStmt.setString(2, dbText);
preparedStmt.execute();
}catch (SQLException ex)
{
Logger.getLogger(AnnouncementDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public ArrayList<Announcement> getAllAnnouncements()
{
String retrieveSql = "SELECT * FROM POSTS.ANNOUNCEMENTS ORDER BY AnnouncementID";
ArrayList<Announcement> announcementList = new ArrayList<>();
getConnection();
if(stmt != null)
{
try
{
ResultSet rs = stmt.executeQuery(retrieveSql);
while (rs.next())
{
Announcement listItem = new Announcement();
listItem.setDate(rs.getDate("AnnouncementDate"));
listItem.setAnnouncement(rs.getString("AnnouncementText"));
announcementList.add(listItem);
}
}catch (SQLException ex)
{
Logger.getLogger(AnnouncementDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
closeConnection();
return announcementList;
}
/* public static void main(String[] args)
{
Announcement mainAnnounce = new Announcement();
mainAnnounce.setAnnouncement("This is a test from main");
mainAnnounce.setDate();
AnnouncementDAO mainDAO = new AnnouncementDAO();
try
{
mainDAO.writeAnnouncement(mainAnnounce);
} catch (Exception ex)
{
Logger.getLogger(AnnouncementDAO.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
ArrayList<Announcement> mainList = mainDAO.getAllAnnouncements();
for(Announcement item : mainList)
{
out.print("\n"+item.toString());
}
}
catch(Exception e)
{
System.err.println(e);
}
}
*/
}
这是我的观看页面
<%@page import="testSource.Announcement"%>
<!DOCTYPE HTML>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title></title>
</head>
<body>
<div>
<form action="${pageContext.request.contextPath}/testAnnounceServlet">
<c:forEach items="${jspList}" var="announcement">
<p class ="cssStylesParagraph">
<c:out value="${announcement.currentTime}"/>
<c:out value="${announcement.dbAnnouncement}"/>
</p>
</c:forEach>
</form>
</div>
<footer>
</footer><!-- end .footer -->
</body>
</html>
这是我的豆子
package testSource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Announcement
{
String dbAnnouncement = "";
java.sql.Date currentTime = null;
public String getAnnouncement()
{
return dbAnnouncement;
}
public java.sql.Date getDate()
{
return currentTime;
}
public void setDate(java.sql.Date dateToSet)
{
this.currentTime = dateToSet;
}
public void setDate()
{
String dateString = new Date().toString();
try {
Date utilDate = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy").parse(dateString);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
this.currentTime = sqlDate;
} catch (ParseException ex) {
Logger.getLogger(Announcement.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void setAnnouncement(String announcemenToSet)
{
this.dbAnnouncement = announcemenToSet;
}
@Override
public String toString()
{
return currentTime.toString()+":" +"\n"+ dbAnnouncement;
}
}
答案 0 :(得分:1)
您需要在控制器上执行GET请求,而不是在视图上执行。即您在浏览器的地址栏中看到的URL必须是servlet URL,而不是JSP URL。这样就可以调用servlet的doGet()
。
首先将testPost.jsp
文件移到/WEB-INF
文件夹中,这样您(也不是最终用户)就不能再犯这个错误了。
然后在servlet代码中更改forward()
调用,如下所示:
request.getRequestDispatcher("/WEB-INF/testPost.jsp").forward(request, response);
sendRedirect()
调用如下:
response.sendRedirect(request.getContextPath() + "/testAnnounceServlet");
最后确保通过以下网址打开/链接页面:
http://localhost:8080/test/testAnnounceServlet