• 使用基本MVC2模式创建新闻网站


    基本的操作就是连接数据库的进行简单的增删改查,然后数据的回显。此处遇到的主要的问题一个是使用ueditor富文本编辑的时候,需要配置。

    其次最需要注意的就是数据库的操作语句以及数据库的连接,新闻表的代码,由于之前已经做过登录,不在附上该操作代码。在操作数据库时,如果频繁的需要连接数据库,那么可以将连接的代码单独写到一个类中去。

    复制代码
      1 package dao;
      2 
      3 import java.sql.Connection;
      4 import java.sql.DriverManager;
      5 import java.sql.PreparedStatement;
      6 import java.sql.ResultSet;
      7 import java.sql.SQLException;
      8 import java.sql.Statement;
      9 import java.util.ArrayList;
     10 import java.util.List;
     11 
     12 import bean.News;
     13 
     14 public class Newsdao {
     15     private static final long serialVersionUID = 1L;
     16 //    private String driverName="com.mysql.jdbc.Driver";
     17 //    private String url="jdbc:mysql://localhost:3306/newsdata?useSSL=false&serverTimezone=UTC";
     18 //    private String name="root";
     19 //    private String pwd="123456";
     20     static Connection con=null;
     21     public static  Connection getCon() {
     22         String driverName="com.mysql.cj.jdbc.Driver";
     23         String url="jdbc:mysql://localhost:3306/newsdata?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
     24         String name="root";
     25         String pwd="123456";
     26                 try {
     27                     Class.forName(driverName);
     28                     try {
     29                         con = DriverManager.getConnection(url, name, pwd);
     30                     } catch (SQLException e) {
     31                         e.printStackTrace();
     32                     }
     33                     
     34                 } catch (ClassNotFoundException e) {
     35                     e.printStackTrace();
     36                 }
     37         return con;
     38     } 
     39     //添加新闻
     40         public boolean addNews(News news) {
     41             con=Newsdao.getCon();
     42             boolean flag=false;
     43             String sql="insert news(title,type,datetime,content) values('"+news.getTitle()+"','"
     44             +news.getType()+"','"
     45                     +news.getDateTime()+"','"
     46                     +news.getContent()+"')";
     47             //System.out.println("添加的sql语句"+sql);
     48             try {
     49                 PreparedStatement ps=con.prepareStatement(sql);
     50                 int i=ps.executeUpdate();
     51                 //System.out.println("i的值"+i);
     52                 ps.close();
     53                 con.close();
     54                 if(i>0) {
     55                     flag =true;
     56                 }
     57             } catch (SQLException e) {
     58                 System.out.println("添加出错啦");
     59                 e.printStackTrace();
     60             }
     61             
     62             return flag;
     63         }
     64         public List<News> selectByID(int id){
     65             con=Newsdao.getCon();
     66             List<News> list=new ArrayList<>();
     67             String sql="select * from news where id="+id+"";
     68             System.out.println(sql);
     69             Statement state;
     70             ResultSet rs;
     71             try {
     72                 state = con.createStatement();
     73                 rs=state.executeQuery(sql);
     74                 while(rs.next()) {
     75                     News news=new News();
     76                     news.setTitle(rs.getString("title"));
     77                     news.setContent(rs.getString("content"));
     78                     news.setDateTime(rs.getString("dateTime"));
     79                     news.setType(rs.getString("type"));
     80 ;                    news.setId(id);
     81                     list.add(news);
     82                     //System.out.println(news.getTitle());
     83                 }
     84                 rs.close();
     85                 state.close();
     86                 con.close();
     87             } catch (SQLException e) {
     88                 System.out.println("查询出错啦");
     89                 e.printStackTrace();
     90             }
     91             return list;
     92         }
     93         
     94         
     95         //删除新闻
     96         public List<News> selectAll(){
     97             con=Newsdao.getCon();
     98             List<News> list=new ArrayList<News>();
     99             String sql="select * from news";
    100             Statement state;
    101             ResultSet rs;
    102             try {
    103                 state = con.createStatement();
    104                 rs=state.executeQuery(sql);
    105                 while(rs.next()) {
    106                     News news=new News();
    107                     news.setId(rs.getInt("id"));
    108                     news.setTitle(rs.getString("title"));
    109                     news.setContent(rs.getString("content"));
    110                     news.setDateTime(rs.getString("dateTime"));
    111                     news.setType(rs.getString("type"));
    112                     list.add(news);
    113                     //System.out.println(news.getType());
    114                 }
    115                 rs.close();
    116                 state.close();
    117                 con.close();
    118             } catch (SQLException e) {
    119                 System.out.println("查询出错啦");
    120                 e.printStackTrace();
    121             }
    122             return list;
    123         }
    124         
    125         //修改新闻
    126         
    127         public boolean update(News news) {
    128             con=Newsdao.getCon();
    129             boolean flag=false;
    130             String sql="update news set title='"+news.getTitle()+"',type='"+news.getType()
    131                     +"',dateTime='"+news.getDateTime()
    132                     +"',content='"+news.getContent()+"' where id="+news.getId()+"";
    133             System.out.println(sql);
    134             Statement state=null;
    135             try {
    136                 state = con.createStatement();
    137                 int i=state.executeUpdate(sql);
    138                 System.out.println(i);
    139                 if(i>0) {
    140                     flag=true;
    141                 }
    142             } catch (SQLException e) {
    143                 System.out.println("更新错误啦");
    144                 e.printStackTrace();
    145             }
    146             
    147             return false;
    148         }
    149         
    150         //删除
    151         public boolean delete(int  id) {
    152             con=Newsdao.getCon();
    153             boolean flag=false;
    154             String sql="delete from news where id='"+id+"'";
    155            // System.out.println(sql);
    156             PreparedStatement ps;
    157             try {
    158                 ps = con.prepareStatement(sql);
    159                 int i=ps.executeUpdate();
    160                 if(i>0){
    161                     flag=true;
    162                 }
    163             } catch (SQLException e) {
    164                 System.out.println("删除出错啦");
    165                 e.printStackTrace();
    166             }
    167             
    168             return flag;
    169         }
    170     
    171 }
    复制代码


    新闻的添加

    package servlet;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import bean.News;
    import dao.Newsdao;
    
    /**
     * Servlet implementation class AddServlet
     */
    @WebServlet("/AddServlet")
    public class AddServlet extends HttpServlet {
    
           
        public AddServlet() {
            super();
        }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request,response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
            String title=request.getParameter("title");
            String type=request.getParameter("type");
            String datetime=request.getParameter("datetime");
            String content=request.getParameter("ueditor");
            System.out.println("这是ueditor的内容"+title+content);
            News news=new News();
            news.setTitle(title);
            news.setContent(content);
            news.setDateTime(datetime);
            news.setType(type);
            
            Newsdao nd=new Newsdao();
            
            try{
                nd.addNews(news);
                response.sendRedirect("newslistServlet");
                //request.getRequestDispatcher("/newslist.jsp").forward(request, response);
            }catch(Exception e) {
                System.out.println("添加失败");
            }
        }
    
    }
    View Code
    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
           <%@page import="java.util.*" %>
           <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
            <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html" charset="utf-8">
    <script type="text/javascript" charset="utf-8" src="utf8-jsp/ueditor.config.js"></script>
        <script type="text/javascript" charset="utf-8" src="utf8-jsp/ueditor.all.min.js"> </script>
        <script type="text/javascript" charset="utf-8" src="utf8-jsp/lang/zh-cn/zh-cn.js"></script>
    
    <title>新闻页</title>
    <style type="text/css">
    
    body{
    margin-top:20px;
    backgroud-color:#ff2812;
    text-align:center;
    }
    .text{
        500px;
        height:20px;
        
    }
    .btn{
      right: 35px;
      bottom: 25px;
       100px;
      height: 30px;
      background: #759fc7;
      font-size: 15px;
      color: #fff;
      letter-spacing: 10px;
      margin-left:40px;
      text-align: center;
    }
    </style>
    </head>
    <body>
    <div >
    <h2>添加新闻</h2>
    <form action="addServlet" method="POST" >
    新闻标题     <input class="text" type="text" name="title" ><br><br>
    
    新闻类别  
     <input type="radio" name="type" value="娱乐" checked="checked"/>娱乐
                         <input type="radio" name="type" value="体育"/>体育
                         <input type="radio" name="type" value="国际"/>国际
                         <input type="radio" name="type" value="社会"/>社会
                         <input type="radio" name="type" value="财经"/>财经
                         <input type="radio" name="type " value="科技"/>科技
    <br><br>
    发布时间       <input class="text" type="text" name="datetime"  ><br><br>
    正文编辑
    <script id="editor" type="text/plain" name="ueditor" style="1024px;height:500px;margin-left:100px"></script>
    
    <button class="btn" type="submit">保存</button >
    <!-- <button class="btn" type="submit">退出</button> -->
    </form>
    </div>
    
    <script type="text/javascript">
        var ue=UE.getEditor('editor');
         function getPlainTxt() {
                var arr = [];
                arr.push("使用editor.getPlainTxt()方法可以获得编辑器的带格式的纯文本内容");
                arr.push("内容为:");
                arr.push(UE.getEditor('editor').getPlainTxt());
                alert(arr.join('
    '))
            }
    </script>
    </body>
    </html>
    View Code

    删除

    package servlet;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import dao.Newsdao;
    
    /**
     * Servlet implementation class DeleteServlet
     */
    @WebServlet("/DeleteServlet")
    public class DeleteServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        public DeleteServlet() {
            super();
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request,response);
        }
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            String id=(String)request.getParameter("id");
            System.out.println("被删除的新闻");
            int nid=Integer.parseInt(id);
            Newsdao nd=new Newsdao();
            nd.delete(nid);
            response.sendRedirect("newslistServlet");
            //request.getRequestDispatcher("/newslist.jsp").forward(request, response);
        }
    
    }
    View Code

    修改

    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
           <%@page import="java.util.*" %>
           <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
            <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html" charset="utf-8">
    <script type="text/javascript" charset="utf-8" src="utf8-jsp/ueditor.config.js"></script>
        <script type="text/javascript" charset="utf-8" src="utf8-jsp/ueditor.all.min.js"> </script>
        <script type="text/javascript" charset="utf-8" src="utf8-jsp/lang/zh-cn/zh-cn.js"></script>
    
    <title>新闻页</title>
    <style type="text/css">
    
    body{
    margin-top:20px;
    backgroud-color:#ff2812;
    text-align:center;
    }
    .text{
        500px;
        height:20px;
        
    }
    .btn{
      right: 35px;
      bottom: 25px;
       100px;
      height: 30px;
      background: #759fc7;
      font-size: 15px;
      color: #fff;
      letter-spacing: 10px;
      margin-left:40px;
      text-align: center;
    }
    </style>
    </head>
    <body>
    <div >
    <h2>修改新闻</h2>
    <form action="updateServlet" method="GET" >
    <c:forEach var="s" items="${item}">
    新闻编号          <input class="text" type="text" name="id" value="${s.id }"><br><br>
    新闻标题     <input class="text" type="text" name="title" value="${s.title }"><br><br>
    
    新闻类别  
             <input type="radio" name="type" value="娱乐"  ${("娱乐"eq s.type)?"checked":""}/>娱乐
            <input type="radio" name="type" value="体育" ${("体育"eq s.type)?"checked":""}/>体育
            <input type="radio" name="type" value="国际"  ${("国际"eq s.type)?"checked":""}/>国际
            <input type="radio" name="type" value="社会"  ${("社会"eq s.type)?"checked":""}/>社会
            <input type="radio" name="type" value="财经"  ${("财经"eq s.type)?"checked":""}/>财经
            <input type="radio" name="type" value="科技"  ${("科技"eq s.type)?"checked":""}/>科技
    <br><br>
    发布时间       <input class="text" type="text" name="datetime" value="${s.dateTime }" ><br><br>
    正文编辑
    <script id="editor" type="text/plain" name="editor" style="1024px;height:500px;margin-left:100px">${s.content}</script>
    
    <button class="btn" type="submit">保存</button >
    <!-- <button class="btn" type="submit">退出</button> -->
    </form>
    </div>
    </c:forEach>
    <script type="text/javascript">
       
        var ue=UE.getEditor('editor');
        UE.getEditor('editor').setContent('${s.content}');
        /* function setContent(isAppendTo) {
            var arr = [];
            arr.push("使用editor.setContent('欢迎使用ueditor')方法可以设置编辑器的内容");
            ue.getEditor('editor').setContent('欢迎使用ueditor', isAppendTo);
            alert(arr.join("
    "));
        }  */
        //alter("gg");
        //UE.getEditor('editor').setContent('${s.content}');
        
            function getContent() {
                var arr = [];
                arr.push(UE.getEditor('editor').getContent());
                alert(arr.join("
    "));
            }
            
            
         
    </script>
    </body>
    </html>
    View Code
    package servlet;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import bean.News;
    import dao.Newsdao;
    
    /**
     * Servlet implementation class UpnewsServlet
     */
    @WebServlet("/UpdateServlet")
    public class UpdateServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
       
        public UpdateServlet() {
            super();
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request,response);
            
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("utf-8");
            String id=request.getParameter("id");
            System.out.println("id的值为"+id);
            int nid=Integer.parseInt(id);
            String title=request.getParameter("title");
            String type=request.getParameter("type");
            String datetime=request.getParameter("datetime");
            String content=request.getParameter("editor");
            News news=new News();
            news.setId(nid);
            news.setTitle(title);
            news.setContent(content);
            news.setDateTime(datetime);
            news.setType(type);
            Newsdao nd=new Newsdao();
            try{
                nd.update(news);
                response.sendRedirect("newslistServlet");
            }catch(Exception e) {
                System.out.println("修改失败");
            }
        }
    
    }
    View Code
    package servlet;
    
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import bean.News;
    import dao.Newsdao;
    
    /**
     * Servlet implementation class ShowServlet
     */
    @WebServlet("/ShowServlet")
    public class ShowServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        public ShowServlet() {
            super();
        }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request,response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;cahrset=utf-8");
            String id=request.getParameter("id");
            int nid=Integer.parseInt(id);
            
            Newsdao nd=new Newsdao();
            List<News> list=nd.selectByID(nid);
            request.setAttribute("item", list);
            
            System.out.println(list.size());
            request.getRequestDispatcher("/update.jsp").forward(request, response);
            
        }
    
    }
    View Code

    查找

    package servlet;
    
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import bean.News;
    import dao.Newsdao;
    @WebServlet("/SelectServlet")
    public class SelectServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        public SelectServlet() {
            super();
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request,response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;cahrset=utf-8");
            String id=request.getParameter("id");
            int nid=Integer.parseInt(id);
            Newsdao nd=new Newsdao();
            List<News> list=nd.selectByID(nid);
            request.setAttribute("news", list);
            
            System.out.println(list.size());
            request.getRequestDispatcher("/content.jsp").forward(request, response);
            
            
            
        }
    
    }
    View Code

  • 相关阅读:
    Redis-cluster集群
    MySQL-binlog日志格式
    MySQL-备份与恢复
    PG-内存参数配置标准
    [POJ1724]Roads
    [POJ1062][最短路]昂贵的聘礼
    我的小博客美化记(仍在持续修改和增加,敬请持续关注)
    [离散化模板][并查集][洛谷1955]程序自动化分析
    python调用百度接口解析/逆解析地址
    datax安装部署
  • 原文地址:https://www.cnblogs.com/hechunhang/p/10886755.html
Copyright © 2020-2023  润新知