JSP显示新闻

一、用户登录:

采用之前的邮件登录系统的界面和验证

JSP显示新闻
 1 //设置数据格式
 2         response.setContentType("text/html;charset=utf-8");
 3         request.setCharacterEncoding("utf-8");
 4         PrintWriter pw = response.getWriter();
 5 
 6         //获取值
 7         String userID = request.getParameter("userID");
 8         String userPWD = request.getParameter("userPWD");
 9 
10         //连接数据库
11         Connection conn;
12 
13         //数据库连接驱动(mysql8的连接需要加上cj)
14         String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
15 
16         //需要使用的数据库路径
17         String url = "jdbc:mysql://localhost:3306/javaee?useSSL=false&serverTimezone=GMT%2B8";
18 
19         //数据库使用者信息
20         String user = "root";
21         String password = "1234567890";
22 
23         try {
24             Class.forName(JDBC_DRIVER);
25             conn = DriverManager.getConnection(url, user ,password);
26             if (!conn.isClosed()){
27                 System.out.println("数据库连接成功");
28             }
29             Statement stmt = conn.createStatement();
30             String sql_select = "select * from userinfo where id=‘"+ userID +"‘ and password=‘"+ userPWD +"‘";
31             ResultSet result = stmt.executeQuery(sql_select);
32             if (result.next()) {
33                 //登录成功的提示
34                 System.out.println(userID + " " + userPWD);
35                 System.out.println("用户名:" + userID + " 密码:" + userPWD);
36                 System.out.println("登录成功,欢迎你 " + userID);
37                 pw.println("登录成功" + "<br>" + "您的用户名:" + userID + "<br>" + "您的密码:" + userPWD);
38 
39                 //登录成功时设置Cookie
40                 Cookie userCookie = new Cookie("userID", userID);
41 
42                 //设置cookie保存的最大时间
43                 userCookie.setMaxAge(60*60*24*30);
44                 response.addCookie(userCookie);
45 
46                 //用户密码也用Cookie记录,方便自动登录
47                 Cookie pwdCookie = new Cookie("userPWD", userPWD);
48                 userCookie.setMaxAge(60*60*24*30);
49                 response.addCookie(pwdCookie);
50 
51                 //设置session
52                 HttpSession session = request.getSession();
53                 session.setMaxInactiveInterval(10);
54                 ServletContext sc = getServletContext();
55                 Object number = sc.getAttribute("onlineNumber");
56 
57                 pw.println("当前网页在线人数:" + number);
58 
59             }else{
60                 System.out.println("用户名或者密码错误");
61                 pw.println("登录失败"+"<br>"+"用户名或者密码错误");
62             }
63 
64             //关闭数据库的连接
65             result.close();
66             conn.close();
67 
68         }catch (ClassNotFoundException e){
69             System.out.println("数据库驱动没有安装");
70             e.printStackTrace();
71         }catch (SQLException e){
72             System.out.println("数据库连接失败");
73             e.printStackTrace();
74         }
login

 

二、新闻显示:

1、创建数据表:

JSP显示新闻
 1 CREATE DATABASE /*!32312 IF NOT EXISTS*/`NewsDB` /*!40100 DEFAULT CHARACTER SET utf8 */;
 2 
 3 USE `NewsDB`;
 4 
 5 /*Table structure for table `news` */
 6 
 7 DROP TABLE IF EXISTS `news`;
 8 
 9 CREATE TABLE `news` (
10   `id` INT(11) NOT NULL AUTO_INCREMENT,
11   `title` VARCHAR(100) DEFAULT NULL,
12   `conetnt` VARCHAR(1000) DEFAULT NULL,
13   `author` VARCHAR(50) DEFAULT NULL,
14   `addtime` DATETIME DEFAULT NULL,
15   PRIMARY KEY (`id`)
16 ) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
17 
18 /*Data for the table `news` */
19 
20 INSERT  INTO `news`(`id`,`title`,`conetnt`,`author`,`addtime`) VALUES (1,‘端午节的来源‘,‘端午节,又称端阳节、龙舟节、重午节、龙节、正阳节、天中节等,节期在农历五月初五,是中国民间的传统节日。端午节源自天象崇拜,由上古时代祭龙演变而来。仲夏端午,苍龙七宿飞升至正南中天,是龙飞天的日子,即如《易经·乾卦》第五爻的爻辞曰:“飞龙在天”。端午日龙星既“得中”又“得正”,乃大吉大利之象。端午节的起源涵盖了古老星象文化、人文哲学等方面内容,蕴含着深邃丰厚的文化内涵;在传承发展中杂揉了多种民俗为一体,节俗内容丰富。扒龙舟与食粽是端午节的两大礼俗,这两大礼俗在中国自古传承,至今不辍。‘,‘test‘,‘2020-06-25 10:19:42‘);
21 
22 /*Table structure for table `user` */
23 
24 DROP TABLE IF EXISTS `user`;
25 
26 CREATE TABLE `user` (
27   `uid` INT(11) NOT NULL AUTO_INCREMENT,
28   `userName` VARCHAR(30) DEFAULT NULL,
29   `pw` VARCHAR(15) DEFAULT NULL,
30   PRIMARY KEY (`uid`)
31 ) ENGINE=INNODB AUTO_INCREMENT=6 DEFAULT CHARSET=gb2312;
32 
33 /*Data for the table `user` */
34 
35 INSERT  INTO `user`(`uid`,`userName`,`pw`) VALUES (1,‘admin‘,‘admin‘);
createdatabase

 

2、新增Servlet : NewsController.java 并配置在WEB.XML中

<servlet>
<servlet-name>NewsController</servlet-name>
<servlet-class>servlet.NewsController</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>NewsController</servlet-name>
<url-pattern>/NewsController</url-pattern>
</servlet-mapping>

在NewsController.java 中doGet中重写doPost方法并在doPost方法中获取action参数,根据参数不同分别进行不同请求

JSP显示新闻

 3、创建service类   NewsService.java,在类中调用DAO中并返回新闻信息

public class NewsService {


    public List<NewsBean> query_all_news() {
        NewsDao newsDao = new NewsDao();
        
          return newsDao.query_all_news();
    }
    
    public NewsBean getNews(String id) {
        NewsDao newsDao = new NewsDao();
        return newsDao.getNews(id);
    }
}

4、新增DBUtils.java 及 NewsDao.java类

在DBUtils.java中添加连接数据库及关闭数据库代码

public static Connection getConnection(){
        String dbUserName = "root";
        String dbUserPasswd = "123456";
        
        String dbURL = "jdbc:mysql://localhost:3406/NewsDB?serverTimezone=Asia/Shanghai";
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection) DriverManager.getConnection(dbURL,dbUserName,dbUserPasswd);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } 
        return conn;
    }
    

    public static void closeConnection(Connection conn) {

        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }

 

public List<NewsBean> query_all_news() {
        Connection conn = DBUtils.getConnection();
        String sql = "select * from news";
        ArrayList<NewsBean> results = new ArrayList<NewsBean>();
        
        try {
            PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();

            while(rs.next()){
                
                NewsBean temp = new NewsBean();
                temp.setId(rs.getString("id"));
                temp.setTitle(rs.getString("title"));
                temp.setConetnt(rs.getString("conetnt"));
                temp.setAuthor(rs.getString("author"));
                temp.setAddtime(rs.getDate("addtime"));
                results.add(temp);
            }
            rs.close();
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtils.closeConnection(conn);
        }
        return results;
    }
    
    public NewsBean getNews(String id) {
        Connection conn = DBUtils.getConnection();
        String sql = "select * from news where id=‘"+id+"‘ ";
        NewsBean result = new NewsBean();
        
        try {
            PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();

            while(rs.next()){

                result.setId(rs.getString("id"));
                result.setTitle(rs.getString("title"));
                result.setConetnt(rs.getString("conetnt"));
                result.setAuthor(rs.getString("author"));
                result.setAddtime(rs.getDate("addtime"));
            }

            rs.close();
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtils.closeConnection(conn);
        }
        return result;
    }

 

5、前端显示页面:

<c:forEach items="${newsList }" var="ctxt">
            <tr>
                <td>
                    ${ctxt.title } </td>
                   <td> ${ctxt.author } </td>
                   <td> ${ctxt.addtime } </td>
                    <td><a href="/JspNewsList/NewsController?action=toShowNews&id=${ctxt.id }">查看详情</a></td>
            
          
            </tr>        
            </c:forEach>

 

 

JSP显示新闻

上一篇:MVC2 项目实践


下一篇:kubernetes资源均衡器Descheduler