servlet和mysql显示错误

时间:2015-11-29 17:50:17

标签: mysql servlets

我目前正在尝试创建一个连接到mysql数据库并显示内容的servlet。到目前为止,我有一切都很好,一个问题。如果登录它会抓取数据库中的注释并显示它们。如果我注销并再次登录,它会再次显示相同的数据。所以它显示两次数据。如果我使用其他用户登录,则会显示之前的2和新用户数据。所以我不知道为什么它这样做。我不知道它是会话还是什么。下面是我的java和jsp文件

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

    public void init() throws ServletException
    {

        if (getServletContext().getAttribute("cs320.hw2.Note") == null)
            getServletContext().setAttribute("cs320.hw2.Note", new ArrayList<User>());



        try
        {
            Class.forName( "com.mysql.jdbc.Driver" );
        }
        catch( ClassNotFoundException e )
        {
            throw new ServletException( e );
        }
    }

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

        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("CurrentUser");
        List<Notes> entries = (List<Notes>) getServletContext().getAttribute(
                "cs320.hw2.Note");

        if (user == null) {
            // User isn't authenticated
            response.sendRedirect("Login");
            return;
        }
        else {


             Connection c = null;
                try
                {
                    String host = "";
                    String port = "";
                    String dbName = "";
                    String username = "";
                    String password = "";

                    String url = "jdbc:mysql://" + host + ":" + port + "/" + dbName;

                    c = DriverManager.getConnection( url, username, password );
                    Statement stmt = c.createStatement();
                    String sname = (String)session.getAttribute("name");
                    ResultSet rs = stmt.executeQuery( "select * from entry    where name ='"+sname+"'");


                    while( rs.next() )
                    {
                            int id          = rs.getInt("id");
                            String name     = rs.getString("name");
                            String note     = rs.getString("note");
                            String title    = rs.getString("title");

                            Notes entry = new Notes(id, name, note, title);
                            entries.add(entry);
                    }

                    request.setAttribute("entries", entries);

                    request.getRequestDispatcher( "/WEB-INF/homework2/MyNotes.jsp" ).forward(
                         request, response );

                    for (Notes u : entries) {
                        System.out.println("id " + u.id + "name:  " + u.name + "Note:  "
                                + u.note + "title:  " + u.title);
                    }
                }
                catch( SQLException e )
                {
                    throw new ServletException( e );
                }
                finally
                {
                    try
                    {
                        if( c != null ) c.close();
                    }
                    catch( SQLException e )
                    {
                        throw new ServletException( e );
                    }
                }


            }   

    }

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

        }

     }

我的jsp

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>MyNotes</title>
</head>
<body>

<p align="right">Hello, ${sessionScope.CurrentUser}!&nbsp;&nbsp;&nbsp;<a href="Logout">Logout</a></p>
<span>JOT&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="MyNotes">My Notes</a>&nbsp;|&nbsp;<a href="NewNote.jsp">New</a></span>
<br>
<br>
<br>

<table border=1px>
  <tr><th>Titles</th></tr>
<c:forEach items="${entries}" var="entry">
  <tr>
    <td>${entry.title}</td>
  </tr>
</c:forEach>
</table>


<p><a href="NewNote.jsp">New Note</a></p>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

问题是你的entries变量是在ServletContext中创建并存储的,即整个应用程序是相同的(因为servlet,因此它们的上下文总是单例)。

删除

if (getServletContext().getAttribute("cs320.hw2.Note") == null)
    getServletContext().setAttribute("cs320.hw2.Note", new ArrayList<User>());

来自init()方法的行,并替换

List<Notes> entries = (List<Notes>) getServletContext().getAttribute("cs320.hw2.Note");

List<Notes> entries = new ArrayList<Notes>();
doGet()方法中的

。您将拥有所有新的空条目列表,以填充从DB获得的值。