500错误,message_list.jsp文件出错

500错误,message_list.jsp文件出错

10-Jun-2019 17:29:41.194 涓ラ噸 [http-nio-8080-exec-6] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [MessageListServlet] in context with path [/JDBCMessageBoard_war_exploded] threw exception
 java.lang.NullPointerException
    at com.imooc.jdbc.dao.MessageDAO.getMessages(MessageDAO.java:61)
    at com.imooc.jdbc.service.MessageService.getMessages(MessageService.java:34)
    at com.imooc.jdbc.servlet.MessageListServlet.service(MessageListServlet.java:41)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.imooc.jdbc.filter.UserFilter.doFilter(UserFilter.java:30)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.imooc.jdbc.filter.CharsetEncodingFilter.doFilter(CharsetEncodingFilter.java:28)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

http://img1.sycdn.imooc.com//climg/5cfe23250001402517790513.jpg

正在回答

登陆购买课程后可参与讨论,去登陆

14回答

同学你好,空对象是哪个呢?需要同学贴出完整的截图以及信息哦~

同学也可以按照如下思路自行进行查找,去查找输出的空对象是如何创建的,有没有创建过程,如果没有的话,需要创建该对象。

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~

  • bitchbiss 提问者 #1
    哇,是sql语句出了错误,资料里的sql语句少个分号,找的人头大,谢谢老师的耐心解答
    2019-06-12 18:45:09
吃吃吃鱼的猫 2019-06-12 19:02:13

同学你好

编程中也需要耐心和细心,同学能够自己找出错误,也是很棒的呢~

继续加油吧~

祝:学习愉快~

吃吃吃鱼的猫 2019-06-12 17:51:08

同学你好,

还是报MessageDao中第62行空指针异常吗?

同学使用System.out.println();方法输出62行的对象信息,检查是否为空对象。

http://img1.sycdn.imooc.com//climg/5d00cad20001dc5005770293.jpg

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~

  • 提问者 bitchbiss #1
    输出了,是空对象
    2019-06-12 18:24:24
提问者 bitchbiss 2019-06-12 16:35:47
吃吃吃鱼的猫 2019-06-12 16:22:34

同学你好,

MySQL是版本8的话,mysql-connector-java也需要是8以上的。

同学需要更换mysql-connector-java的jar包,可以参考以下链接中的标识教辅进行操作。

https://class.imooc.com/lesson/721#mid=17932

http://img1.sycdn.imooc.com//climg/5d00b5e90001603d04560530.jpg

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~

  • 提问者 bitchbiss #1
    改了还是报同样的错误
    2019-06-12 16:35:19
吃吃吃鱼的猫 2019-06-12 11:24:51

同学你好,

问一下同学mysql-connector-java的jar包版本是多少呢?

祝:学习愉快~

  • 提问者 bitchbiss #1
    版本是5.1.18,但MySQL是8版本的
    2019-06-12 16:09:50
提问者 bitchbiss 2019-06-11 20:04:29

ConnectionUtil.java

package com.imooc.jdbc.common;

import java.sql.*;

/*
**数据库公共操作类
 */
public class ConnectionUtil {
    private static String url="jdbc:mysql://localhost:3306/message_board";
    private static String user="root";
    private static String password="990906";
    private ConnectionUtil(){ }
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("找不到驱动类,驱动加载失败");
            e.printStackTrace();
        }
    }

    /**
     * 获得数据库连接
     * @return
     */
    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(url,user,password);
        }catch (SQLException e){
            System.out.println("创建数据库连接失败");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 释放数据库资源
     * @param rs ResultSet
     * @param stmt Statement
     * @param conn Connection
     */
    public static void release(ResultSet rs, Statement stmt,Connection conn){
     try{
         if (rs!=null){
             rs.close();
         }
     }catch (SQLException e){
         e.printStackTrace();
     }finally {
         try{
             if(stmt!=null){
                 stmt.close();
             }
         }catch (SQLException e){
             e.printStackTrace();
         }finally {
             try{
                 if (conn!=null){
                     conn.close();
                 }
             }catch (SQLException e){
                 e.printStackTrace();
             }
         }
     }
    }
}

报错信息

11-Jun-2019 20:04:01.899 涓ラ噸 [http-nio-8080-exec-4] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [MessageListServlet] in context with path [/JDBCMessageBoard_war_exploded] threw exception
 java.lang.NullPointerException
    at com.imooc.jdbc.dao.MessageDAO.getMessages(MessageDAO.java:62)
    at com.imooc.jdbc.service.MessageService.getMessages(MessageService.java:34)
    at com.imooc.jdbc.servlet.MessageListServlet.service(MessageListServlet.java:41)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.imooc.jdbc.filter.UserFilter.doFilter(UserFilter.java:30)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.imooc.jdbc.filter.CharsetEncodingFilter.doFilter(CharsetEncodingFilter.java:28)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

吃吃吃鱼的猫 2019-06-11 18:56:07

同学你好

1、首先确认下mysql中是否有同学写的数据库,确认该数据库中是否有message表。

2、同学贴出改正后的ConnectionUtil.java的信息以及完整报错信息,方便老师为同学解决问题。

3、问一下同学的数据库版本以及数据库连接版本分别是多少,两者版本需要对应?

数据库为5的话,数据库连接版本也要为5,驱动写为:

com.mysql.jdbc.Driver

数据库为8的话,数据库连接版本也要为8,驱动写为:

com.mysql.cj.jdbc.Driver

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~


  • 提问者 bitchbiss #1
    数据库写好着,版本是8,改了后还是报错,文件和报错信息在回答里,另外几个java文件也在回答里,谢谢老师
    2019-06-11 20:06:32
提问者 bitchbiss 2019-06-11 18:28:07
吃吃吃鱼的猫 2019-06-11 09:43:57

同学你好,如图所示,url中没有数据库名称。

http://img1.sycdn.imooc.com//climg/5cff071800010f9104440023.jpg

正确的url格式为:

jdbc:mysql://localhost:3306/数据库名称

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~

  • 提问者 bitchbiss #1
    写了还是连接数据库失败
    2019-06-11 18:27:34
提问者 bitchbiss 2019-06-10 20:04:25

ConnectionUtil.java

package com.imooc.jdbc.common;
import java.sql.*;
/*
**数据库公共操作类
 */
public class ConnectionUtil {
    private static String url="jdbc:mysql://localhost:3306";
    private static String user="root";
    private static String password="990906";
    private ConnectionUtil(){ }
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("找不到驱动类,驱动加载失败");
            e.printStackTrace();
        }
    }
    /**
     * 获得数据库连接
     * @return
     */
    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(url,user,password);
        }catch (SQLException e){
            System.out.println("创建数据库连接失败");
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 释放数据库资源
     * @param rs ResultSet
     * @param stmt Statement
     * @param conn Connection
     */
    public static void release(ResultSet rs, Statement stmt,Connection conn){
     try{
         if (rs!=null){
             rs.close();
         }
     }catch (SQLException e){
         e.printStackTrace();
     }finally {
         try{
             if(stmt!=null){
                 stmt.close();
             }
         }catch (SQLException e){
             e.printStackTrace();
         }finally {
             try{
                 if (conn!=null){
                     conn.close();
                 }
             }catch (SQLException e){
                 e.printStackTrace();
             }
         }
     }
    }
}

[2019-06-10 07:43:57,951] Artifact JDBCMessageBoard:war exploded: Artifact is deployed successfully
[2019-06-10 07:43:57,951] Artifact JDBCMessageBoard:war exploded: Deploy took 3,751 milliseconds
10-Jun-2019 19:44:03.781 淇℃伅 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Users\Shinelon\tomcat\apache-tomcat-8.5.37\webapps\manager]
10-Jun-2019 19:44:04.828 淇℃伅 [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
10-Jun-2019 19:44:04.880 淇℃伅 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Users\Shinelon\tomcat\apache-tomcat-8.5.37\webapps\manager] has finished in [1,097] ms
创建数据库连接失败
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client
null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:943)
    at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:4113)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1308)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2336)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2369)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2153)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at com.imooc.jdbc.common.ConnectionUtil.getConnection(ConnectionUtil.java:28)
    at com.imooc.jdbc.dao.MessageDAO.getMessages(MessageDAO.java:55)
    at com.imooc.jdbc.service.MessageService.getMessages(MessageService.java:34)
    at com.imooc.jdbc.servlet.MessageListServlet.service(MessageListServlet.java:41)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.imooc.jdbc.filter.UserFilter.doFilter(UserFilter.java:30)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.imooc.jdbc.filter.CharsetEncodingFilter.doFilter(CharsetEncodingFilter.java:28)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

好帮手慕阿满 2019-06-10 18:54:30

同学你好,建议同学在Connection conn = ConnectionUtil.getConnection();后输出一下conn,查看是否有值输出,如:

http://img1.sycdn.imooc.com//climg/5cfe36be0001ab5806310205.jpg

祝:学习愉快~

  • 提问者 bitchbiss #1
    创建数据库连接失败。 错误和代码在回答里
    2019-06-10 20:02:59
提问者 bitchbiss 2019-06-10 18:21:24

MessageDAO.java

61行:stmt = conn.prepareStatement(sql);

MessageService.java

34行:return messageDAO.getMessages(page, pageSize);

MessageListServlet.java

41行:List<Message> messages = messageService.getMessages(page, 5);//分页查询全部留言


MessageDAO.java

package com.imooc.jdbc.dao;

import com.imooc.jdbc.bean.Message;
import com.imooc.jdbc.common.ConnectionUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息DAO
 *
 * @version 1.0
 */
public class MessageDAO {

    /**
     * 保存留言信息
     * @param message
     * @return
     */
    public boolean save(Message message) {
        Connection conn = ConnectionUtil.getConnection();
        String sql = "insert into message(user_id, username, title, content, create_time) values (?, ?, ?, ?, ?)";
        PreparedStatement stmt = null;
        try {
            stmt = conn.prepareStatement(sql);
            stmt.setLong(1, message.getUserId());
            stmt.setString(2, message.getUsername());
            stmt.setString(3, message.getTitle());
            stmt.setString(4, message.getContent());
            stmt.setTimestamp(5, new Timestamp(message.getCreateTime().getTime()));
            stmt.execute();
        } catch (Exception e) {
            System.out.println("保存留言信息失败。");
            e.printStackTrace();
            return false;
        } finally {
            ConnectionUtil.release(null, stmt, conn);
        }
        return true;
    }

    /**
     * 分页查询全部留言
     * @param page 当前页码
     * @param pageSize 每页记录数
     * @return
     */
    public List<Message> getMessages(int page, int pageSize) {
        Connection conn = ConnectionUtil.getConnection();
        String sql = "select * from message order by create_time desc limit ?, ?";//limit m, n:从第m条开始,取出总共n条记录
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<Message> messages = new ArrayList<>();
        try {
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, (page - 1) * pageSize);
            stmt.setInt(2, pageSize);
            rs = stmt.executeQuery();
            while (rs.next()) {
                messages.add(new Message(rs.getLong("id"),
                        rs.getLong("user_id"),
                        rs.getString("username"),
                        rs.getString("title"),
                        rs.getString("content"),
                        rs.getTimestamp("create_time")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionUtil.release(rs, stmt, conn);
        }
        return messages;
    }

    /**
     * 计算所有留言数量
     * @return
     */
    public int countMessages() {
        Connection conn = ConnectionUtil.getConnection();
        String sql = "select count(*) total from message";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            while (rs.next()) {
                return rs.getInt("total");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionUtil.release(rs, stmt, conn);
        }
        return 0;
    }

}

MessageService.java

package com.imooc.jdbc.service;

import com.imooc.jdbc.bean.Message;
import com.imooc.jdbc.dao.MessageDAO;

import java.util.Date;
import java.util.List;

/**
 * 消息Service
 *
 * @version 1.0
 */
public class MessageService {

    private MessageDAO messageDAO;

    public MessageService() {
        messageDAO = new MessageDAO();
    }

    public boolean addMessage(Message message) {
        message.setCreateTime(new Date());
        return messageDAO.save(message);
    }

    /**
     * 分页查询全部留言
     * @param page 当前页码
     * @param pageSize 每页记录数
     * @return
     */
    public List<Message> getMessages(int page, int pageSize) {
        return messageDAO.getMessages(page, pageSize);
    }

    /**
     * 计算所有留言数量
     * @return
     */
    public int countMessages() {
        return messageDAO.countMessages();
    }

}

MessageListServlet.java

package com.imooc.jdbc.servlet;

import com.imooc.jdbc.bean.Message;
import com.imooc.jdbc.service.MessageService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 消息列表Servlet
 *
 * @version 1.0
 */
public class MessageListServlet extends HttpServlet {

    private MessageService messageService;

    @Override
    public void init() throws ServletException {
        super.init();
        messageService = new MessageService();
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageStr = request.getParameter("page");//当前页码
        int page = 1;//页码默认值为1
        if (null != pageStr && (!"".equals(pageStr))) {
            try {
                page = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        List<Message> messages = messageService.getMessages(page, 5);//分页查询全部留言
        int count = messageService.countMessages();
        int last = count % 5 == 0 ? (count / 5) : ((count / 5) + 1);
        request.setAttribute("last", last);
        request.setAttribute("messages", messages);
        request.setAttribute("page", page);
        request.getRequestDispatcher("/WEB-INF/views/biz/message_list.jsp").forward(request, response);
    }

    @Override
    public void destroy() {
        super.destroy();
        messageService = null;
    }

}


好帮手慕阿满 2019-06-10 17:59:15

同学你好,页面中的报错是因为jstl的jar包没有导入到项目中,如图:

http://img1.sycdn.imooc.com//climg/5cfe29600001a29403440205.jpg

下边的两个jar包都没有导入到项目中,导入到项目中的jar包前边应该向右的箭头,建议同学在jar包上点击右键,选择add to Library,将jar包导入到项目中再试试。

另外,如下代码是那一行,建议同学具体指出来。

http://img1.sycdn.imooc.com//climg/5cfe29da0001bf2307220162.jpg

祝:学习愉快~

  • 提问者 bitchbiss #1
    老师代码我贴回答里了
    2019-06-10 18:22:03
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
Java数据库开发与实战应用2018版
  • 参与学习           人
  • 提交作业       277    份
  • 解答问题       4297    个

Java数据库开发的必备技能,从流行的MySQL数据库开始,到Java原生的数据库管理接口JDBC的使用,再到常用的数据持久化框架MyBatis,让你向Java工程师的目标又迈进了一步!

了解课程
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师