JDBC+Servlet+JSP整合开发之31-JSP项目实战

简介:
–编程思想 
?分层开发思想 
?面向接口编程思想
 
–设计模式 
? DAO设计模式 
? MVC设计模式
 
–实例 
?收藏管理
------------------------------Start-----------------------------------
? 编程思想 
–分层开发思想 
?软件的层次结构可以分为四层: 
–表现层 
–控制层 
–业务逻辑层 
–数据逻辑层(持久层)
 
–面向接口编程思想 
?在编程中将业务逻辑抽象出接口,以供上次调用 
?依赖抽象(接口),而非具体(接口实现)的编程思想,又称之为控制反转(Inversion of Control)
? 设计模式 
–DAO设计模式 
? DAO的全称是:Data Access Object,数据访问对象。 
? 使用DAO设计模式,来封装数据库持久层的所以操作(CRUD),使 低级的数据逻辑和高级的业务逻辑分离,达到解耦合的目的。 
–一个典型的DAO实现有如下的组件: 
? 一个 DAO 接口 
? 一个实现了 DAO 接口的具体类 
? 一个 DAO 工厂类 
? 数据传输对象(有时称为值对象) 
–以维护一个客户信息为例,具体组件如下所示: 
? CustomerDao 接口 
? Customer 值对象(VO) 
? CustomerDaoImpl(接口的具体实现类) 
? CustomerFactory(工厂类,实例化用)
? 编程思想和设计模式的具体应用 
–图示
image
? 实例 
–收藏管理 
?实例描述 
–本实例运用了分层开发思想、面向接口编程两种思想;和 
DAO、MVC设计模式来实现一个收藏管理程序 
–程序的主要功能是,把感兴趣的链接做维护,包括添加一个新 
的链接、删除一个链接、显示一个链接列表、修改链接等内容 
?用到的表 
–收藏表(LinkTbl)
image
? 实例 
–收藏管理 
?程序部分运行结果
image
image
LinkDao.java
image
LinkDaoImpl.java
package com.michael.dao.impl;    

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

import com.michael.dao.LinkDao;    
import com.michael.util.ConnectionUtil;    
import com.michael.util.SQLConstants;    
import com.michael.vo.Link;    

public  class LinkDaoImpl  implements LinkDao,SQLConstants{    

         public  void add(Link l) {    
                Connection conn =  new ConnectionUtil().openConnection();    
                 try {    
                        PreparedStatement pstmt = conn.prepareStatement(ADD_LINK_SQL);    
                        pstmt.setString(1, l.getName());    
                        pstmt.setString(2, l.getUrl());    
                        pstmt.executeUpdate();    
                }  catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                         try {    
                                conn.close();    
                        }  catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
        }    

         public  void delete(String[] ids) {    
                Connection conn =  new ConnectionUtil().openConnection();    
                 try {    
                        PreparedStatement pstmt = conn.prepareStatement(DELETE_LINK_SQL);    
                         if(ids!= null&&ids.length>0)    
                         for( int i=0;i<ids.length;i++){    
                                pstmt.setInt(1, Integer.parseInt(ids[i]));    
                                pstmt.executeUpdate();                                 
                        }    

                }  catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                         try {    
                                conn.close();    
                        }  catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
        }    

         public Link get( int id) {    
                Connection conn =  new ConnectionUtil().openConnection();    
                 try {    
                        PreparedStatement pstmt = conn.prepareStatement(GET_LINK_SQL);    
                        pstmt.setInt(1, id);    
                        ResultSet rs = pstmt.executeQuery();    
                         if(rs.next()){    
                                 //int id = rs.getInt(1);    
                                String name = rs.getString(2);    
                                String url = rs.getString(3);    
                                Link l =  new Link();    
                                l.setId(id);    
                                l.setName(name);    
                                l.setUrl(url);    
                                 return l;    
                        }    
                }  catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                         try {    
                                conn.close();    
                        }  catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
                 return  null;    
        }    

         public List list() {    
                Connection conn =  new ConnectionUtil().openConnection();    
                 try {    
                        Statement stmt = conn.createStatement();    
                        ResultSet rs = stmt.executeQuery(QUERY_LINK_SQL);    
                        List list =  new ArrayList();    
                         while(rs.next()){    
                                 int id = rs.getInt(1);    
                                String name = rs.getString(2);    
                                String url = rs.getString(3);    
                                Link l =  new Link();    
                                l.setId(id);    
                                l.setName(name);    
                                l.setUrl(url);    
                                list.add(l);    
                        }    
                         return list;    
                }  catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                         try {    
                                conn.close();    
                        }  catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
                 return  null;    
        }    

         public  void update(Link l) {    
                Connection conn =  new ConnectionUtil().openConnection();    
                 try {    
                        PreparedStatement pstmt = conn.prepareStatement(UPDATE_LINK_SQL);    
                        pstmt.setString(1, l.getName());    
                        pstmt.setString(2, l.getUrl());    
                        pstmt.setInt(3, l.getId());    
                        pstmt.executeUpdate();    
                }  catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                         try {    
                                conn.close();    
                        }  catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
        }    


LinkServlet.java
package com.michael.servlet;    

import java.io.IOException;    
import java.util.List;    

import javax.servlet.ServletException;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;    

import com.michael.dao.LinkDao;    
import com.michael.dao.impl.LinkDaoImpl;    
import com.michael.vo.Link;    

public  class LinkServlet  extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public LinkServlet() {    
                 super();    
        }    

         /**    
         * Destruction of the servlet. <br>    
         */
    
         public  void destroy() {    
                 super.destroy();  // Just puts "destroy" string in log    
                 // Put your code here    
        }    

         /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doGet(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                doPost(request,response);    
        }    

         /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to post.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doPost(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    
                String methodName = request.getParameter( "methodName");    

                 if (methodName !=  null && methodName.equals( "add")) {    
                        add(request, response);    
                }  else  if (methodName !=  null && methodName.equals( "query")) {    
                        query(request, response);    

                }  else  if (methodName !=  null && methodName.equals( "delete")) {    

                        delete(request, response);    
                }  else  if (methodName !=  null && methodName.equals( "forward")) {    

                        forward(request, response);    
                }  else  if (methodName !=  null && methodName.equals( "update")) {    

                        update(request, response);    
                }  else {    
                         return;    
                }    
                 /*    
                //响应用户请求    
                String name = request.getParameter("name");    
                String url = request.getParameter("url");    
                //调用后台逻辑    
                LinkDao dao = new LinkDaoImpl();    
                Link l = new Link();    
                l.setName(name);    
                l.setUrl(url);    
                dao.add(l);    
                List list = dao.list();    
                request.setAttribute("LinkList", list);    
                //转发    
                request.getRequestDispatcher("/link.jsp").forward(request, response);    
                */
    
        }    
         public  void add(HttpServletRequest request, HttpServletResponse response)    
                 throws ServletException, IOException {    

                 //响应用户请求    
                String name = request.getParameter( "name");    
                String url = request.getParameter( "url");    
                 //调用后台逻辑    
                LinkDao dao =  new LinkDaoImpl();    
                Link l =  new Link();    
                l.setName(name);    
                l.setUrl(url);    
                dao.add(l);    
                query(request,response);    
        }    
         public  void query(HttpServletRequest request, HttpServletResponse response)    
                 throws ServletException, IOException {    
                 //调用后台逻辑    
                LinkDao dao =  new LinkDaoImpl();    
                List list = dao.list();    
                request.setAttribute( "LinkList", list);    
                 //转发    
                request.getRequestDispatcher( "/link.jsp").forward(request, response);    
        }    
         public  void delete(HttpServletRequest request, HttpServletResponse response)    
                 throws ServletException, IOException {    
                 //调用后台逻辑    
                LinkDao dao =  new LinkDaoImpl();    
                String[] ids = request.getParameterValues( "ids");    
                dao.delete(ids);    
                query(request,response);    
        }    
         public  void forward(HttpServletRequest request, HttpServletResponse response)    
                 throws ServletException, IOException {    
                 //调用后台逻辑    
                String id = request.getParameter( "id");    
                LinkDao dao =  new LinkDaoImpl();    
                Link link = dao.get(Integer.parseInt(id));    
                request.setAttribute( "link", link);    
                request.getRequestDispatcher( "/editLink.jsp").forward(request, response);    
        }    
         public  void update(HttpServletRequest request, HttpServletResponse response)    
                 throws ServletException, IOException {    
                 //响应用户请求    
                String id = request.getParameter( "id");    
                String name = request.getParameter( "name");    
                String url = request.getParameter( "url");    
                 //调用后台逻辑    
                LinkDao dao =  new LinkDaoImpl();    
                Link l =  new Link();    
                l.setId(Integer.parseInt(id));    
                l.setName(name);    
                l.setUrl(url);    
                dao.update(l);    
                query(request,response);    
}    

         /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occurs    
         */
    
         public  void init()  throws ServletException {    
                 // Put your code here    
        }    


ConnectionUtil.java
package com.michael.util;    

import java.sql.Connection;    
import java.sql.DriverManager;    
import java.util.Properties;    

public  class ConnectionUtil {    

         /**    
         * @param args    
         */
    
         public  static  void main(String[] args) {    
                ConnectionUtil cu =  new ConnectionUtil();    
                System.out.println(cu.openConnection());    
        }    
         public Connection openConnection() {    
                String url = "";    
                String driver = "";    
                String user = "";    
                String password = "";    
                Properties prop =  new Properties();    
                 try {    
                        prop.load( this.getClass().getClassLoader().getResourceAsStream( "DBConfig.properties"));    
                        driver = prop.getProperty( "driver");    
                        url = prop.getProperty( "url");    
                        user = prop.getProperty( "user");    
                        password = prop.getProperty( "password");    
                        Class.forName(driver);    
                        Connection conn = DriverManager.getConnection(    
                                        url, user, password);    
                         return conn;    
                }  catch (Exception e) {    
                        e.printStackTrace();    
                }    
                 return  null;    
        }    
         public Connection getConnection(String driver, String url, String user,    
                        String password) {    
                 // Class.forName()    
                 try {    
                        Class.forName(driver);    
                         // DriverManager get connection    
                        Connection conn = DriverManager.getConnection(url, user, password);    
                         return conn;    
                }  catch (Exception e) {    
                        e.printStackTrace();    
                }    
                 return  null;    
        }    

         public Connection getConnection() {    
                 // Class.forName()    
                 try {    
                        Class.forName( "com.mysql.jdbc.Driver");    
                         // DriverManager get connection    
                        Connection conn = DriverManager.getConnection(    
                                         "jdbc:mysql://localhost:3306/jsp_db", "root", "963963");    
                        return conn;    
                } catch (Exception e) {    
                        e.printStackTrace();    
                }    
                return null;    
        }    


SQLConstants.java
image
Link.java
image
DBConfig.properties
image
link.jsp
<%@ page language= "java"  import= "java.util.*" pageEncoding= "gbk"%>    
<%@ taglib uri= "http://java.sun.com/jsp/jstl/core" prefix="redking"%>    
<%    
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>My JSP 'link.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">    
        <!--    
        <link rel="stylesheet" type="text/css" href="styles.css">    
        -->    

    </head>    
    <body>    
        <form name="f1" id="f1" action="<%=path %>/servlet/LinkServlet?methodName=add" method="post">    
            <table border="0">    
                <tr>    
                    <td>Name:</td>    
                    <td><input type="text" name="name" ></td>    
                </tr>    
                <tr>    
                    <td>Url:</td>    
                    <td><input type="text" name="url"></td>    
                </tr>    
                <tr>    
                    <td colspan="2" align="center"><input type="submit" value="Add"></td>    
                </tr>    
            </table>    
        </form>    
        <hr/>    
        <form name="f2" action="<%=path %>/servlet/LinkServlet?methodName=delete" method="post">    
        <table>    
                <tr><th>ID</th><th>Name</th><th>URL</th><th>Edit</th><th>Delete</th></tr>    
                <redking:forEach var="1" items="${LinkList}">    
                        <tr>    
                                <td>${l.id }</td>    
                                <td>${l.name }</td>    
                                <td>${l.url }</td>    
                                <td><a href="<%=path %>/servlet/LinkServlet?methodName=forward&id=${l.id }">Edit</a></td>    
                                <td><input type="checkbox" name="ids" value="${l.id }"/></td>    
                        </tr>    
                </redking:forEach>    
                <tr>    
                        <td>    
                                <input type="submit" value="Delete"/>    
                        </td>    
                </tr>    
        </table>    
        </form>    
    </body>    
</html> 
editLink.jsp
<%@ page language= "java"  import= "java.util.*" pageEncoding= "gbk"%>    
<%@ taglib uri= "http://java.sun.com/jsp/jstl/core" prefix="redking"%>    
<%    
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>My JSP 'link.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">    
        <!--    
        <link rel="stylesheet" type="text/css" href="styles.css">    
        -->    

    </head>    
    <body>    
        <form name="f1" id="f1" action="<%=path %>/servlet/LinkServlet?methodName=update" method="post">    
            <table border="0">    
            <input type="hidden" name="id" value="${link.id }">    
                <tr>    
                    <td>Name:</td>    
                    <td><input type="text" name="name" value="${link.name }"></td>    
                </tr>    
                <tr>    
                    <td>Url:</td>    
                    <td><input type="text" name="url" value="${link.url }"></td>    
                </tr>    
                <tr>    
                    <td colspan="2" align="center"><input type="submit" value="Update"></td>    
                </tr>    
            </table>    
        </form>    
    </body>    
</html>






本文转自redking51CTO博客,原文链接: http://blog.51cto.com/redking/316455 ,如需转载请自行联系原作者
相关文章
|
2天前
|
Java
排课系统【JSP+Servlet+JavaBean】(Java课设)
排课系统【JSP+Servlet+JavaBean】(Java课设)
13 5
|
2天前
|
Java
仓库管理系统【JSP+Servlet+JavaBean】(Java课设)
仓库管理系统【JSP+Servlet+JavaBean】(Java课设)
9 1
|
2天前
|
Java
校园帮【JSP+Servlet+JavaBean】(Java课设)
校园帮【JSP+Servlet+JavaBean】(Java课设)
6 1
|
2天前
|
Java
新闻发布系统【JSP+Servlet+JavaBean】(Java课设)
新闻发布系统【JSP+Servlet+JavaBean】(Java课设)
9 2
|
2天前
|
Java
学院管理系统【JSP+Servlet+JavaBean】(Java课设)
学院管理系统【JSP+Servlet+JavaBean】(Java课设)
13 3
学院管理系统【JSP+Servlet+JavaBean】(Java课设)
|
2天前
|
Java
学校人员管理系统【JSP+Servlet+JavaBean】(Java课设)
学校人员管理系统【JSP+Servlet+JavaBean】(Java课设)
7 2
|
2天前
|
Java
学校教师管理系统【JSP+Servlet+JavaBean】(Java课设)
学校教师管理系统【JSP+Servlet+JavaBean】(Java课设)
11 2
|
2天前
|
Java
学生信息管理系统【JSP+Servlet+JavaBean】(Java课设)
学生信息管理系统【JSP+Servlet+JavaBean】(Java课设)
10 1
|
2天前
|
Java
图书信息管理系统【JSP+Servlet+JavaBean】(Java课设)
图书信息管理系统【JSP+Servlet+JavaBean】(Java课设)
6 0
|
2天前
|
Java
个人信息管理系统【JSP+Servlet+JavaBean】(Java课设)
个人信息管理系统【JSP+Servlet+JavaBean】(Java课设)
7 0