• jdbc03 使用servlet实现


    <%@page import="cn.bdqn.bean.News"%>
    <%@page import="cn.bdqn.service.impl.NewsServiceImpl"%>
    <%@page import="cn.bdqn.service.NewsService"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path + "/";
    %>
    <%-- 引入需要的jstl标签库--%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE HTML>
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <style type="text/css">
    <%--
    表格中的数据 居中显示          --%> td {
        text-align: center;
    }
    </style>
    </head>
    <%-- 需要引入了 外部javaBean  --%>
    <jsp:useBean id="service" class="cn.bdqn.service.impl.NewsServiceImpl" />
    <jsp:useBean id="pageUtil" class="cn.bdqn.util.PageUtil" />
    <body>
      <form action="newsList.jsp" method="get">
        <h1>显示新闻信息</h1>
        <table border="1">
            <tr>
                <td>新闻编号</td>
                <td>新闻标题</td>
                <td>新闻作者</td>
                <td>创建时间</td>
                <td>操作</td>
            </tr>
    
            <%
                //获取分页的四要素
                int pageSize = 3; //页大小
                int pageIndex = 1; //当前页面
                String num = request.getParameter("pageIndex");//获取pageIndex
                if (num != null && num != "") { //因为第一次打开页面的时候 请求中 压根没有  pageIndex的属性
                    pageIndex = Integer.parseInt(num);
                } else {
                    pageIndex = 1;
                }
                //给通用的工具类 赋值
                pageUtil.setPageIndex(pageIndex);
                pageUtil.setPageSize(pageSize);
                pageUtil.setTotalCountSize(service.getTotalCountSize()); //总记录数
                pageUtil.getTotalPageCount(); //获取总页数
    
                List<News> news = service.getNewsByPageList(pageIndex, pageSize);
                //把响应的数据放入作用域
                request.setAttribute("news", news);
                request.setAttribute("pageUtil", pageUtil);
            %>
            <c:forEach items="${news}" var="n" varStatus="s">
                <c:if test="${s.count%2==0}">
                    <tr bgcolor="green">
                </c:if>
                <c:if test="${s.count%2!=0}">
                    <tr bgcolor="pink">
                </c:if>
                <td>${n.getId()}</td>
                <td>${n.getTitle()}</td>
                <td>${n.getAuthor()}</td>
                <td>${n.getCreateDate()}</td>
                <td><a href="update.jsp?id=${n.getId()}">修改</a>
                </td>
                </tr>
            </c:forEach>
    
            <tr>
                <td>当前页:${pageUtil.getPageIndex()}</td>
                <td>总页数:${pageUtil.getTotalPageCount()}</td>
                <td>总记录数${pageUtil.getTotalCountSize()}</td>
            </tr>
         
    <%--   引入需要的分页界面   --%>
    <c:import url="page.jsp">
        <c:param name="pageIndex" value="${pageUtil.pageIndex}"></c:param>
        <c:param name="totalPageCount" value="${pageUtil.totalPageCount}"></c:param>
    </c:import>
        </table>
        
        </form>
    </body>
    </html>
    修改后的newsList.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <%-- 引入需要的jstl标签库--%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'page.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
    <script type="text/javascript">
     function  page(form,num){
         //把传递来的num赋值给当前的页码
         form.pageIndex.value=num;
         form.submit();     
     }
    
    </script>
    
      </head>
      
      <body>
      
      
    <%--  表单隐藏域  保存 当前页--%>
      <input type="hidden" name="pageIndex">
    <%--javaScript:伪协议 !  不会跳转界面,只是让我们通过这个连接直接调用JavaScript代码  --%>
            <tr>
                <c:if test="${param.pageIndex>1}">
                    <td><a href="javaScript:page(document.forms[0],1)">首页</a></td>
                    <td><a href="javaScript:page(document.forms[0],${param.pageIndex-1})">上一页</a></td>
                </c:if>
                <%--    如果当前页码小于总页数    --%>
                <c:if test="${param.pageIndex <param.totalPageCount}">
                    <td><a href="javaScript:page(document.forms[0],${param.pageIndex+1})">下一页</a>
                    </td>
                    <td><a href="javaScript:page(document.forms[0],${param.totalPageCount})">最后一页</a>
                    </td>
                </c:if>
                <td><a href="addNews.jsp">新增</a></td>
            </tr>
    
      </body>
    </html>
    公用的page.jsp

    ================使用servlet==========================

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>新闻信息的登录界面</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
       <h1>登录界面</h1>
    <%--  action="Login"    Login必须在web.xml中又对应的url-pattern --%>
         <form action="Login"  method="post">
             <table>
                 <tr>
                   <td>用户名:</td>
                   <td><input  type="text" name="userName"/></td>
                 </tr>
                 <tr>
                   <td>密码:</td>
                   <td><input  type="password" name="password"/></td>
                 </tr>
                 <tr>
                   <td></td>
                   <td><input  type="submit" value="登录"/></td>
                 </tr>
             </table>
         </form>
      </body>
    </html>
    修改login.jsp的action
    public class LoginServlet extends HttpServlet { //处理登录请求的servlet
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
         doPost(request, response);  //交给 doPost()处理请求
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
              System.out.println("进入了 LoginServlet");
              request.setCharacterEncoding("utf-8");
               //01.获取用户信息
             String  userName= request.getParameter("userName");
             String  password= request.getParameter("password");
             User user=new User();  //把信息保存在 user中
             user.setPassword(password);
             user.setUserName(userName);
               //02.从数据库取值
             UserService service=new UserServiceImpl();
              boolean  flag= service.login(user);
               if(flag){
                   //重定向到 新闻列表servlet   如果直接到新闻界面  是没有值的!
                   response.sendRedirect("NewsListServlet");
               }else{
                   //重定向到 新闻登录界面
                   response.sendRedirect("login.jsp");
               }
        }
    
    }
    创建LoginServlet

    newsList.jsp修改后的代码

    <%@page import="cn.bdqn.bean.News"%>
    <%@page import="cn.bdqn.service.impl.NewsServiceImpl"%>
    <%@page import="cn.bdqn.service.NewsService"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path + "/";
    %>
    <%-- 引入需要的jstl标签库--%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE HTML>
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <style type="text/css">
    <%--
    表格中的数据 居中显示          --%> td {
        text-align: center;
    }
    </style>
    </head>
    <body>
      <form action="NewsListServlet" method="get">
        <h1>显示新闻信息</h1>
        <table border="1">
            <tr>
                <td>新闻编号</td>
                <td>新闻标题</td>
                <td>新闻作者</td>
                <td>创建时间</td>
                <td>操作</td>
            </tr>
    
            <c:forEach items="${news}" var="n" varStatus="s">
                <c:if test="${s.count%2==0}">
                    <tr bgcolor="green">
                </c:if>
                <c:if test="${s.count%2!=0}">
                    <tr bgcolor="pink">
                </c:if>
                <td>${n.getId()}</td>
                <td>${n.getTitle()}</td>
                <td>${n.getAuthor()}</td>
                <td>${n.getCreateDate()}</td>
                <td><a href="update.jsp?id=${n.getId()}">修改</a>
                </td>
                </tr>
            </c:forEach>
    
            <tr>
                <td>当前页:${pageUtil.getPageIndex()}</td>
                <td>总页数:${pageUtil.getTotalPageCount()}</td>
                <td>总记录数${pageUtil.getTotalCountSize()}</td>
            </tr>
         
    <%--   引入需要的分页界面   --%>
    <c:import url="page.jsp">
        <c:param name="pageIndex" value="${pageUtil.pageIndex}"></c:param>
        <c:param name="totalPageCount" value="${pageUtil.totalPageCount}"></c:param>
    </c:import>
        </table>
        
        </form>
    </body>
    </html>
    把newsList.jsp中的java代码提取到NewsListServlet中
    public class NewsListServlet extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
             doPost(request, response);
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("进入了 NewsListServlet");
            PageUtil pageUtil=new PageUtil();
            NewsService service =new NewsServiceImpl();
            //获取分页的四要素
            int pageSize = 3; //页大小
            int pageIndex = 1; //当前页面
            String num = request.getParameter("pageIndex");//获取pageIndex
            if (num != null && num != "") { //因为第一次打开页面的时候 请求中 压根没有  pageIndex的属性
                pageIndex = Integer.parseInt(num);
            } else {
                pageIndex = 1;
            }
            //给通用的工具类 赋值
            pageUtil.setPageIndex(pageIndex);
            pageUtil.setPageSize(pageSize);
            pageUtil.setTotalCountSize(service.getTotalCountSize()); //总记录数
            pageUtil.getTotalPageCount(); //获取总页数
    
            List<News> news = service.getNewsByPageList(pageIndex, pageSize);
            //把响应的数据放入作用域
            request.setAttribute("news", news);
            request.setAttribute("pageUtil", pageUtil);
            //转发到newsList.jsp界面
            request.getRequestDispatcher("/newsList.jsp").forward(request, response);
        }
    
    }
    NewsListServlet代码
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>cn.bdqn.servlet.LoginServlet</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>NewsListServlet</servlet-name>
        <servlet-class>cn.bdqn.servlet.NewsListServlet</servlet-class>
      </servlet>
    
    
      <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/Login</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>NewsListServlet</servlet-name>
        <url-pattern>/NewsListServlet</url-pattern>
      </servlet-mapping>    
      
      
      
      
      
      
      
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
    web.xml文件中的配置
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>新闻信息新增界面</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    <%--  引入我们需要的  富文本 编辑器    --%>
     <script type="text/javascript" src="ckeditor/ckeditor.js"></script>
    <style type="text/css">
      div{
      height:900px;
      width:900px;
         margin:auto;
        padding: auto;
      }
    </style>
    <script type="text/javascript">
    <%--验证用户有没有选择 新闻类别 --%>
      function  check(){
          var goryId=  document.getElementById("goryId").value;
          if(goryId==0){
              alert("请选择新闻类别.....");
              return  false;
          }
          return  true;
      }
    </script>
    
    
    </head>
      <body>
      <div>
      <h1>新闻信息新增界面</h1>
    <%-- action="NewsAddServlet"   NewsAddServlet是web.xml文件中   url-pattern  --%>
       <form action="NewsAddServlet" enctype="multipart/form-data" method="post" onsubmit="return  check()">
             <table>
                 <tr>
                   <td>新闻分类:</td>
                   <td>
                     <select name="categoryId" id="goryId">
                       <option  value="0">请选择新闻类别</option>
                       <option  value="1">国内</option>
                       <option  value="2">国际</option>
                       <option  value="3">娱乐</option>
                       <option  value="4">军事</option>
                       <option  value="5">财经</option>
                     </select>
                   </td>
                 </tr>
                 <tr>
                   <td>新闻标题:</td>
                   <td><input  type="text" name="title"/></td>
                 </tr>
                 <tr>
                   <td>新闻作者:</td>
                   <td><input  type="text" name="author"/></td>
                 </tr>
                 
                 <tr>
                   <td>新闻摘要:</td>
                   <td><input  type="text" name="summary"/></td>
                 </tr>
                 <tr>
                   <td>创建时间:</td>
                   <td><input  type="date" name="createDate"/></td>
                 </tr>
                 <tr>
                   <td>选择文件:</td>
                   <td><input  type="file" name="picPath"/></td>
                 </tr>
                 
                  <tr>
                   <td>新闻内容:</td>
                   <td><textarea class="ckeditor" name="content">
                   
                     </textarea>
                   </td>
                 </tr>
                 <tr>
                   <td></td>
                   <td><input  type="submit" value="新增"/></td>
                 </tr>
             </table>
         </form>
      </div>
    
      </body>
    </html>
    修改addNews.jsp的action
    public class NewsAddServlet extends HttpServlet { // 新闻的新增
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response); // 默认执行doPost()
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("进入了NewsAddServlet");
            News news = new News();
            NewsService service = new NewsServiceImpl();
            // 解决乱码问题
            request.setCharacterEncoding("utf-8");
    
            // 01.文件上传到 哪里去??? 我们必须指定用户的上传位置
            String uploadFilePath = request.getSession().getServletContext()
                    .getRealPath("upload/");
            // 不确定文件是否已经存在
            File file = new File(uploadFilePath);
            if (!file.exists()) {
                // 不存在 创建
                file.mkdirs();
            }
            // 02.判断前台的form表单是否带有文件
            boolean flag = ServletFileUpload.isMultipartContent(request);
            try {
                if (flag) { // 如果是文件上传
                    /*
                     * 如果上传的文件比较小,则直接保存在内存中,速度快! 文件大的时候,以临时文件的形式,保存在电脑的临时文件夹中!
                     * 我们使用FileItemFactory 接口的对应 实现类 来完成 上传操作
                     */
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    // 能把请求中的所有元素进行获取! 返回一个FileItem的集合
                    List<FileItem> items = upload.parseRequest(request);
                    // 获取Iterator迭代器
                    Iterator<FileItem> iter = items.iterator();
                    // 事先给 没给元素定义一个名称
                    String fileName = "";
                    while (iter.hasNext()) { // 遍历出每一个元素
                        FileItem item = iter.next();
                        if (item.isFormField()) { // 如果是普通的元素
                            fileName = item.getFieldName(); // 获取普通元素的名称
                            if (fileName.equals("title")) {
                                news.setTitle(item.getString("utf-8"));
                            } else if (fileName.equals("author")) {
                                news.setAuthor(item.getString("utf-8"));
                            } else if (fileName.equals("content")) {
                                news.setContent(item.getString("utf-8"));
                            } else if (fileName.equals("summary")) {
                                news.setSummary(item.getString("utf-8"));
                            } else if (fileName.equals("createDate")) {
                                news.setCreateDate(new SimpleDateFormat(
                                        "yyyy-MM-dd").parse(item.getString("utf-8")));
                            } else if (fileName.equals("categoryId")) {
                                news.setCategoryId(Integer.parseInt(item
                                        .getString("utf-8")));
                            }
                        } else { // 操作上传的文件
                            String fimeName = item.getName(); // 获取上传文件的名称
                            if (fimeName != null && fimeName != "") {
                                File fullFile = new File(fimeName);
                                // 相当于在uploadFilePath 这个文件下面
                                // 创建一个文件fullFile.getName()
                                File saveFile = new File(uploadFilePath,
                                        fullFile.getName());
                                // 写入 真正的上传
                                try {
                                    item.write(saveFile);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                news.setPicPath(fullFile.getName()); // 给news的文件路径赋值
                            }
                        }
                    }
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            service.addNews(news); // 调用底层代码 进行新增操作
            // 新增成功了之后 需要返回到新闻列表界面 转发 会引起 表单的重复提交
            // request.getRequestDispatcher("newsList.jsp").forward(request,
            // response);
            // 重定向 NewsListServlet 拿到值 放入作用于中 才能 去newsList.jsp页面
            response.sendRedirect("NewsListServlet");
        }
    }
    创建NewsAddServlet

    =================实现新闻的修改===============================

    <%@page import="cn.bdqn.bean.News"%>
    <%@page import="cn.bdqn.service.impl.NewsServiceImpl"%>
    <%@page import="cn.bdqn.service.NewsService"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path + "/";
    %>
    <%-- 引入需要的jstl标签库--%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE HTML>
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <style type="text/css">
    <%--
    表格中的数据 居中显示          --%> td {
        text-align: center;
    }
    </style>
    </head>
    <body>
      <form action="NewsListServlet" method="get">
        <h1>显示新闻信息</h1>
        <table border="1">
            <tr>
                <td>新闻编号</td>
                <td>新闻标题</td>
                <td>新闻作者</td>
                <td>创建时间</td>
                <td>操作</td>
            </tr>
    
            <c:forEach items="${news}" var="n" varStatus="s">
                <c:if test="${s.count%2==0}">
                    <tr bgcolor="green">
                </c:if>
                <c:if test="${s.count%2!=0}">
                    <tr bgcolor="pink">
                </c:if>
                <td>${n.getId()}</td>
                <td>${n.getTitle()}</td>
                <td>${n.getAuthor()}</td>
                <td>${n.getCreateDate()}</td>
                <td><a href="FindNewsServlet?id=${n.getId()}">修改</a>
                <a href="NewsDelServlet?id=${n.getId()}">删除</a>
                </td>
                </tr>
            </c:forEach>
    
            <tr>
                <td>当前页:${pageUtil.getPageIndex()}</td>
                <td>总页数:${pageUtil.getTotalPageCount()}</td>
                <td>总记录数${pageUtil.getTotalCountSize()}</td>
            </tr>
         
    <%--   引入需要的分页界面   --%>
    <c:import url="page.jsp">
        <c:param name="pageIndex" value="${pageUtil.pageIndex}"></c:param>
        <c:param name="totalPageCount" value="${pageUtil.totalPageCount}"></c:param>
    </c:import>
        </table>
        
        </form>
    </body>
    </html>
    修改后的newsList界面
    public class FindNewsServlet extends HttpServlet { // 根据id查询到指定的新闻
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response); // doPost()
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            NewsService service = new NewsServiceImpl();
            News news = service.findById(request.getParameter("id"));
            // 放入作用域
            request.setAttribute("news", news);
            // 转发到update.jsp页面
            request.getRequestDispatcher("/update.jsp").forward(request, response);
        }
    
    }
    点击修改按钮后进入的FindNewsServlet
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <%-- 引入需要的jstl标签库--%>
    <%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>新闻信息修改界面</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    <%--  引入我们需要的  富文本 编辑器    --%>
     <script type="text/javascript" src="ckeditor/ckeditor.js"></script>
      </head>
      
      <body>
      <h1>新闻信息修改界面</h1>
       <form action="NewsUpdateServlet" enctype="multipart/form-data" method="post" onsubmit="return  check()">
             <table>
                 <tr>
                   <td>新闻分类:</td>
                   <td>
                     <select name="categoryId" id="goryId">
                       <option  value="0">请选择新闻类别</option>
    <%--     下拉框内容的回显              --%>
                       <option <c:if test="${news.categoryId==1}">selected</c:if> value="1">国内</option>
                       <option <c:if test="${news.categoryId==2}">selected</c:if> value="2">国际</option>
                       <option <c:if test="${news.categoryId==3}">selected</c:if> value="3">娱乐</option>
                       <option <c:if test="${news.categoryId==4}">selected</c:if> value="4">军事</option>
                       <option <c:if test="${news.categoryId==5}">selected</c:if>value="5">财经</option>
                     </select>
                   </td>
                 </tr>
                 <tr>
    <%--     页可以使用表单的隐藏域         --%>
                   <td>新闻编号:</td>
                   <td><input  type="text" value="${news.id}" name="id" readonly="readonly"/></td>
                 </tr>
                 <tr>
                   <td>新闻标题:</td>
                   <td><input  type="text" value="${news.title}" name="title"/></td>
                 </tr>
                 <tr>
                   <td>新闻作者:</td>
                   <td><input  type="text" value="${news.author}" name="author"/></td>
                 </tr>
                 
                 <tr>
                   <td>新闻摘要:</td>
                   <td><input  type="text" value="${news.summary}" name="summary"/></td>
                 </tr>
                 <tr>
                   <td>创建时间:</td>
                   <td><input  type="text" value="<f:formatDate value='${news.createDate}' pattern='yyyy-MM-dd'/>" name="createDate"/>
                     
                   </td>
                 </tr>
                 <tr>
                   <td>选择文件:</td>
                   <td><input  type="file"  name="picPath"/></td>
                 </tr>
                 
                  <tr>
                   <td>新闻内容:</td>
                   <td><textarea class="ckeditor" name="content">
                       ${news.content}
                     </textarea>
                   </td>
                 </tr>
                 <tr>
                   <td></td>
                   <td><input  type="submit" value="修改"/></td>
                 </tr>
             </table>
         </form>
      </div>
      </body>
    </html>
    修改后的update.jsp页面
    public class NewsUpdateServlet extends HttpServlet { // 修改新闻
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response); // doPost()
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("进入了NewsUpdateServlet");
            News news = new News();
            NewsService service = new NewsServiceImpl();
            // 解决乱码问题
            request.setCharacterEncoding("utf-8");
            // 01.文件上传到 哪里去??? 我们必须指定用户的上传位置
            String uploadFilePath = request.getSession().getServletContext()
                    .getRealPath("upload/");
            // 不确定文件是否已经存在
            File file = new File(uploadFilePath);
            if (!file.exists()) {
                // 不存在 创建
                file.mkdirs();
            }
            // 02.判断前台的form表单是否带有文件
            boolean flag = ServletFileUpload.isMultipartContent(request);
            try {
                if (flag) { // 如果是文件上传
                    /*
                     * 如果上传的文件比较小,则直接保存在内存中,速度快! 文件大的时候,以临时文件的形式,保存在电脑的临时文件夹中!
                     * 我们使用FileItemFactory 接口的对应 实现类 来完成 上传操作
                     */
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    // 能把请求中的所有元素进行获取! 返回一个FileItem的集合
                    List<FileItem> items = upload.parseRequest(request);
                    // 获取Iterator迭代器
                    Iterator<FileItem> iter = items.iterator();
                    // 事先给 没给元素定义一个名称
                    String fileName = "";
                    while (iter.hasNext()) { // 遍历出每一个元素
                        FileItem item = iter.next();
                        if (item.isFormField()) { // 如果是普通的元素
                            fileName = item.getFieldName(); // 获取普通元素的名称
                            if (fileName.equals("title")) {
                                news.setTitle(item.getString("utf-8"));
                            } else if (fileName.equals("author")) {
                                news.setAuthor(item.getString("utf-8"));
                            } else if (fileName.equals("content")) {
                                news.setContent(item.getString("utf-8"));
                            } else if (fileName.equals("summary")) {
                                news.setSummary(item.getString("utf-8"));
                            } else if (fileName.equals("createDate")) {
                                news.setCreateDate(new SimpleDateFormat(
                                        "yyyy-MM-dd").parse(item.getString("utf-8")));
                            } else if (fileName.equals("categoryId")) {
                                news.setCategoryId(Integer.parseInt(item
                                        .getString("utf-8")));
                            } else if (fileName.equals("id")) { // 设置新闻编号
                                news.setId(Integer.parseInt(item.getString("utf-8")));
                            }
                        } else { // 操作上传的文件
                            String fimeName = item.getName(); // 获取上传文件的名称
                            if (fimeName != null && fimeName != "") {
                                File fullFile = new File(fimeName);
                                // 相当于在uploadFilePath 这个文件下面
                                // 创建一个文件fullFile.getName()
                                File saveFile = new File(uploadFilePath,
                                        fullFile.getName());
                                // 写入 真正的上传
                                try {
                                    item.write(saveFile);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                news.setPicPath(fullFile.getName()); // 给news的文件路径赋值
                            }
                        }
                    }
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            service.updateNews(news); // 调用底层代码 进行修改操作
            // 重定向 NewsListServlet 拿到值 放入作用于中 才能 去newsList.jsp页面
            response.sendRedirect("NewsListServlet");
        }
    }
    点击修改后 提交到的NewsUpdateServlet
     // 修改新闻
        public int updateNews(News news) {
            getConnection();
            // 之前 只是修改了 新闻标题 现在 全部都修改了
            String sql = "update  news_detail set  categoryId=?,title=?,content=?,author=?,summary=?,createDate=?"
                    + " where id=?";
            Object[] params = { news.getCategoryId(), news.getTitle(),
                    news.getContent(), news.getAuthor(), news.getSummary(),
                    news.getCreateDate(), news.getId() };
            int num = executeUpdate(sql, params);
            return num;
        }
    修改NewsDaoImpl中的修改方法

    =================实现新闻的删除===============================

    public class NewsDelServlet extends HttpServlet { // 删除指定的新闻
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response); // 默认执行doPost()
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("进入了NewsDelServlet ");
            NewsService service = new NewsServiceImpl();
            // 获取传递过来的id
            String id = request.getParameter("id");
            News news = service.findById(id);
            System.out.println(news); // 测试 查看news信息
            service.deleteNews(news); // 删除
            // 重定向到 新闻处理servlet
            response.sendRedirect("NewsListServlet");
        }
    
    }
    点击删除按钮后的NewsDelServlet

    ================验证用户登录后才能进入新闻详情界面=========================

    public class LoginServlet extends HttpServlet { // 处理登录请求的servlet
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response); // 交给 doPost()处理请求
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("进入了 LoginServlet");
            // 01.获取用户信息
            String userName = request.getParameter("userName");
            String password = request.getParameter("password");
            User user = new User(); // 把信息保存在 user中
            user.setPassword(password);
            user.setUserName(userName);
            // 02.从数据库取值
            UserService service = new UserServiceImpl();
            boolean flag = service.login(user);
            if (flag) {
                // 把用户信息放入 作用域 过滤器中需要判断
                request.getSession().setAttribute("user", user);
                // 重定向到 新闻列表servlet 如果直接到新闻界面 是没有值的!
                response.sendRedirect("NewsListServlet");
            } else {
                // 重定向到 新闻登录界面
                response.sendRedirect("login.jsp");
            }
        }
    
    }
    修改后的LoginServlet
    public class LoginFilter implements Filter {
    
        public void destroy() {
            System.out.println("LoginFilter在服务器关闭的时候 执行一次 销毁......");
        }
    
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            request.setCharacterEncoding("utf-8"); // 给所有的servlet设置编码格式
    
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            // 获取session中的用户
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            // 获取用户请求的路径
            String path = httpServletRequest.getRequestURI();
            /**
             * 判断用户url
             * 我们的登录界面login.jsp  是不能拦截的
             * 用户已经登录了               是不能拦截的
             */
            if (path.indexOf("login") > -1 || (user != null)) {
                chain.doFilter(request, response);
            } else {
                httpServletResponse.sendRedirect("login.jsp");
            }
    
        }
    
        public void init(FilterConfig filterConfig) throws ServletException {
            System.out.println("LoginFilter在服务器启动的时候 执行一次 初始化......");
        }
    
    }
    创建对应的LoginFilter过滤器

    把login.jsp页面中的form表单 action改成login! 同样的  在web.xml中的LoginServlet对应的mapping  url 页要改成  /login

     <!--
      web.xml文件 加载的顺序
       01. context-param  :所有servlet共享
       02.listener
       03.filter   如果有多个   按照  filterClass 加载的顺序
       04.servlet
       
       
       filter 可以配置很多!
           真正执行的顺序是什么?  按照filter-Mapping的顺序  执行!
           
      load-on-startup:  
      值没有设置,或者为负数的时候,都是在用户访问的时候 执行初始化操作!
      值为0或者大于0时,都是在服务器启动的时候初始化! 值越小 初始化越早!    
        -->
    /**
     * 使用注解可以替换 web.xml文件中的配置
     * 
     * 环境必须是java ee6版本
     * value="/LoginServlet"  必须加上/
     * urlPatterns={"/LoginServlet","login"}
     * value和urlPatterns 不能同时存在
     * 
     * 如果只有一个value属性可以省略
     * 比如@WebServlet("/LoginServlet") 也是正确的!
     * 等同于@WebServlet(value="/LoginServlet")
     */
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet 
    //多个初始化参数的配置
    @WebServlet(value="/LoginServlet",initParams={@WebInitParam(name="name",value="小黑"),
            @WebInitParam(name="age",value="50")})
    public class LoginServlet extends HttpServlet {
  • 相关阅读:
    【软件工程】软件测试目标定义 黑盒测试、白盒测试
    【计算机网络】互联网的组成(客户服务器、对等连接、电路交换、分组交换)
    【计算机网络】互联网概述
    文本域的宽度和高度应该用cols和rows来控制,还是 用width和height来控制
    javascript代码片段
    IE对象最后一个属性后不要加逗号,否则在IE7及以下版本中会报错
    检测IE浏览器方法
    Sublime Text 必备插件
    浅谈Javascript 中几种克隆(clone)方式
    JavaScript instanceof 运算符深入剖析
  • 原文地址:https://www.cnblogs.com/xtdxs/p/7094784.html
Copyright © 2020-2023  润新知