你的位置:首页 > Java教程

[Java教程]JSP 新闻发布会


---恢复内容开始---

首先 新闻发布会结合了JSP里的Servlet和request对象,response对象还有使用session对象和cookie对象跟踪用户信息等等。。。。。

 

 

列表

 

登陆

这是在Servlet里面写的 LoginServlet 登陆方法

 1 private ServletRequest session; 2   public void doGet(HttpServletRequest request, HttpServletResponse response) 3       throws ServletException, IOException { 4     doPost(request, response); 5   } 6   public void doPost(HttpServletRequest request, HttpServletResponse response) 7       throws ServletException, IOException { 8      9         try {10           BaseDao dd=new BaseDao();11           String uname=request.getParameter("uname");12           String upwd=request.getParameter("upwd");13               String sql="select * from user where userName=? and userPwd=?";14               Object [] prams={uname,upwd};15                    ResultSet flag=dd.executeSelect(sql, prams);16           if(flag.next())17           {18             HttpSession session=request.getSession();19             session.setAttribute("unamesession", uname);20             Cookie cookie=new Cookie("unamesession",uname);21             cookie.setMaxAge(60*60*24);22             response.addCookie(cookie);23             //out.print("<script type='text/javascript'>"+"alert('成功登陆!')");24             request.getRequestDispatcher("/newspages/admin.jsp").forward(request, response);25           }26           else27           { 28             response.sendRedirect("/index.jsp");29           }30         } catch (SQLException e) {31           e.printStackTrace();32         }33   }

这是在jsp主页面上写的跳转

1  <form action="LoginServlet" method="doPost">2    <label> 登录名 </label>3    <input type="text" name="uname" value="" class="login_input" />4    <label> 密&#160;&#160;码 </label>5    <input type="password" name="upwd" value="" class="login_input" />6    <input type="submit" class="login_sub" value="登录" />7    <label id="error"> </label>8    <img src="images/friend_logo.gif" alt="Google" id="friend_logo" />9   </form>




登陆完跳转

接下来是  添加

 

这是在impl包里的NewsDaoimpl.java获取所有返回的方法

 

1   //添加2   public boolean Add(News news) {3     String sql="INSERT INTO news ( ntid ,ntitle ,nauthor ,ncreatedate ,npicpath ,ncontent ,nmodifydate ,nsummary ) VALUES (?,?,?,?,?,?,?,?)";4     Object [] prams={news.getNtid(),news.getNtitle(),news.getNauthor(),news.getNcreatedate(),news.getNpicpath(),news.getNcontent(),news.getNmodifydate(),news.getNsummary()};5     boolean flag=executeUpdate(sql,prams);6     closeAll();7     return flag;8   }

 

这个是添加的Servlet类

 1 public class AddServlet extends HttpServlet { 2   public AddServlet() { 3     super(); 4   } 5   public void destroy() { 6     super.destroy();  7      8   } 9   public void doGet(HttpServletRequest request, HttpServletResponse response)10       throws ServletException, IOException {11       doPost(request,response);12   }13   public void doPost(HttpServletRequest request, HttpServletResponse response)14       throws ServletException, IOException {15         if(request.getMethod().equals("GET"))16         {17           request.getRequestDispatcher("newspages/news_add.jsp").forward(request, response);18         }19         else20         {21           String path=request.getContextPath();22           String Basepath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/";23           request.setCharacterEncoding("UTF-8");24           response.setContentType("text/html;charset=UTF-8");25           HttpSession session=request.getSession();26           boolean flag=false;27           try {28             List<News> list=(List<News>) FormUtil.assembleObjectList(request, News.class);29             News news= list.get(0);30             31             news.setNtid(request.getParameter("ntid"));32             news.setNtitle(request.getParameter("ntitle"));33             news.setNauthor(request.getParameter("nauthor"));34             news.setNcreatedate(request.getParameter("nsummaryTime"));35             news.setNpicpath(request.getParameter("file"));36             news.setNcontent(request.getParameter("ncontent"));37             NewsDaoimpl dao=new NewsDaoimpl();38             flag=dao.Add(news);39           } catch (NoSuchFieldException e) {40             // TODO Auto-generated catch block41             e.printStackTrace();42           } catch (Exception e) {43             // TODO Auto-generated catch block44             e.printStackTrace();45           }46           if(flag)47           {48             response.sendRedirect(path+"/newspages/admin.jsp");49           }50           else51           {52             request.getRequestDispatcher("/index.jsp").forward(request, response);53           }54         }55   }56 57 }

View Code

 

接下来这个是添加的jsp

 1 <form action="<%=request.getContextPath()%>/AddServlet" method="post"> 2    <p> 3     <label> 主题 </label> 4     <select name="ntid"> 5     <%-- 6     <c:forEach var="item" items="${typelist} }"> 7     <option value="1"> 8      9       ${item.ntname}10    11     </option>12     </c:forEach>13     --%>14     15     16      <option value="1">选择</option>17      <option value='1'> 国内 </option>18      <option value='2'> 国际 </option>19      <option value='3'> 军事 </option>20      <option value='4'> 体育 </option>21      <option value='5'> 娱乐 </option>22      <option value='6'> 社会 </option>23      <option value='7'> 财经 </option>24      <option value='8'> 科技 </option>25      <option value='9'> 健康 </option>26      <option value='10'> 汽车 </option>27      <option value='11'> 教育 </option>28      <option value='12'> 房产 </option>29      <option value='13'> 家居 </option>30      <option value='14'> 旅游 </option>31      <option value='15'> 文化 </option>32      <option value='16'> 其他 </option>33      </select>34    </p>35    <p>36     <label> 标题 </label>37     <input name="ntitle" type="text" class="opt_input" />38    </p>39    <p>40     <label> 作者 </label>41     <input name="nauthor" type="text" class="opt_input" />42    </p>43    <p>44     <label> 时间 </label>45     <%--<textarea name="nsummary" cols="40" rows="3"></textarea>--%>46     <input id="meeting" type="date" value="2015-11-10" name="nsummaryTime"/>47    </p>48    <p>49     <label> 内容 </label>50     <textarea name="ncontent" cols="70" rows="10"></textarea>51    </p>52    <p>53     <label> 上传图片 </label>54     55     <input name="file" type="file" class="opt_input" />56    </p>57    <input name="action" type="hidden" value="addnews"/>58    <input type="submit" value="提交" class="opt_sub" action="NewsAddServlet" method="doPost" />59    <input type="reset" value="重置" class="opt_sub" />60   </form>

View Code

 

添加主题

 

这是在impl包里的NewsDaoimpl.java获取所有返回的方法

1 //添加主题2     @Override3     public boolean Addtype(Type type) {4         String sql="INSERT INTO TYPE(ntname) VALUES(?)";5         Object [] prams={type.getNtname()};6         boolean flag=executeUpdate(sql, prams);7         closeAll();8       return flag;9     }

这是添加主题的Servlet类

 1 public class TypezhuAddServlet extends HttpServlet { 2  3   public void doGet(HttpServletRequest request, HttpServletResponse response) 4       throws ServletException, IOException { 5     doPost(request,response); 6   } 7  8  9   public void doPost(HttpServletRequest request, HttpServletResponse response)10       throws ServletException, IOException {11       if(request.getMethod().equals("GET"))12       {13         request.getRequestDispatcher("newspages/news_add.jsp").forward(request, response);14       }15       else16       {17         String path=request.getContextPath();18         request.setCharacterEncoding("UTF-8");19         boolean flag=false;20         try {21           List<Type> list=(List<Type>) FormUtil.assembleObjectList(request, Type.class);22           Type type=list.get(0);23           type.setNtname(request.getParameter("ntname"));24           NewsDaoimpl dao=new NewsDaoimpl();25           flag=dao.Addtype(type);26         } catch (NoSuchFieldException e) {27           e.printStackTrace();28         } catch (Exception e) {29           e.printStackTrace();30         }31         if(flag)32         {33           response.sendRedirect(path+"/newspages/admin.jsp");34         }35         else36         {37           request.getRequestDispatcher("/index.jsp").forward(request, response);38         }39       }40   }41 42 }

View Code

添加主题的jsp

 1 <div id="opt_area"> 2   <h1 id="opt_type"> 添加主题: </h1> 3   <form action="<%=request.getContextPath()%>/TypezhuAddServlet" method="post" onsubmit="return check()"> 4    5    <p> 6     <label> 主题名称 </label> 7     <input name="ntname" type="text" class="opt_input" id="tname"/> 8    </p> 9    <input name="action" type="hidden" value="addtopic"/>10    <input type="submit" value="提交" class="opt_sub" />11    <input type="reset" value="重置" class="opt_sub" />12   </form>13  </div>14 </div>

View Code

 

动态加载新闻主题和新闻分页

这是在impl包里的NewsDaoimpl.java获取所有返回的方法

 1   //分页查询 2   public List<News> selectNews() { 3     QueryRunner query=new QueryRunner(); 4      5       String sql="SELECT * FROM news WHERE nid LIMIT 3"; 6       List<News> list=null; 7       try { 8         list = query.query(getConnection(), sql,new BeanListHandler<News>(News.class)); 9       } catch (SQLException e) {10         e.printStackTrace();11       }12     return list;13   }14   /*15    * 根据新闻类型编号查询新闻16   */17   public List<News> selectNewsByTypeid(int tid) {18     QueryRunner query=new QueryRunner();19     String sql="select * from news where ntid=?";20     List<News> list=null;21     try {22       list = query.query(getConnection(), sql, new BeanListHandler<News>(News.class),tid);23     } catch (SQLException e) {24       e.printStackTrace();25     }26     return list;27   }

View Code

这是分页和动态主题的Servlet

 1 public class TypeServlet extends HttpServlet { 2   public void doGet(HttpServletRequest request, HttpServletResponse response) 3       throws ServletException, IOException { 4     doPost(request,response); 5   } 6   public void doPost(HttpServletRequest request, HttpServletResponse response) 7       throws ServletException, IOException { 8       NewsDaoimpl dao=new NewsDaoimpl(); 9       List<Type> list = dao.type();10       request.setAttribute("typelist",list);11       12       String date= request.getParameter("tid");13       if(date!=null && date.equals(""))14       {15         int tid=Integer.parseInt(date);16         NewsDaoimpl newsdao=new NewsDaoimpl();17         List<News> listdao=newsdao.selectNewsByTypeid(tid);18         request.setAttribute("newslist", listdao);19       }20       else21       {22         NewsDaoimpl topdao=new NewsDaoimpl();23         List<News> newslist=topdao.selectNews();24         request.setAttribute("newslist", newslist);25       }26       27       28       request.getRequestDispatcher("/index.jsp").forward(request, response);29   }30 31 }

View Code

主页的jsp

 1 <div class="main"> 2   <div class="class_type"> <img src="images/class_type.gif" alt="新闻中心" /> </div> 3   <div class="content"> 4    <ul class="class_date"> 5     <li id='class_month'> 6      7     <c:forEach var="item" items="${typelist}"> 8     <a style="color:pink;" href='${pageContext.request.contextPath}/TypeServlet?tid=${item.ntid}'> 9     ${item.ntname}10     </a>11     </c:forEach>12     </li>13    </ul>14    <ul class="classlist">15    <c:forEach var="item" items="${newslist}">16      <li><a href='newspages/news_read.jsp'>${item.ntitle }</a><span>${item.ncreatedate }</span></li>17    </c:forEach>18     <p align="right"> 当前页数:[1/2]&nbsp; <a href="#">下一页</a> <a href="#">末页</a> </p>19    </ul>20   </div>

View Code