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 ,如需转载请自行联系原作者
相关文章
|
27天前
|
Java 容器
【学习笔记】Jsp与Servlet技术
【学习笔记】Jsp与Servlet技术
60 0
|
3月前
|
SQL Java 数据库
jsp中使用Servlet查询SQLSERVER数据库中的表的信息,并且打印在屏幕上
该博客文章介绍了在JSP应用中使用Servlet查询SQL Server数据库的表信息,并通过JavaBean封装图书信息,将查询结果展示在Web页面上的方法。
jsp中使用Servlet查询SQLSERVER数据库中的表的信息,并且打印在屏幕上
|
3月前
|
供应链 前端开发 Java
JSP+servlet+mybatis+layui服装库存管理系统(大三上学期课程设计)
这篇文章通过一个服装库存管理系统的实例,展示了在Spring Boot项目中使用Ajax、JSON、layui、MVC架构和iframe等技术,涵盖了注册登录、权限管理、用户管理、库存管理等功能,并提供了系统运行环境和技术要求的详细说明。
JSP+servlet+mybatis+layui服装库存管理系统(大三上学期课程设计)
|
3月前
|
前端开发 安全 Java
在Java服务器端开发的浩瀚宇宙中,Servlet与JSP犹如两颗璀璨的明星,它们联袂登场,共同编织出动态网站的绚丽篇章。
在Java服务器端开发的浩瀚宇宙中,Servlet与JSP犹如两颗璀璨的明星,它们联袂登场,共同编织出动态网站的绚丽篇章。
27 0
|
4月前
|
XML Java 数据格式
jsp和servlet有什么区别?
总的来说,JSP和Servlet都是创建动态Web应用程序的重要工具,但它们的使用依赖于特定的需求和上下文。
37 0
|
4月前
|
XML Java 数据格式
jsp和servlet有什么区别?
总的来说,JSP和Servlet都是创建动态Web应用程序的重要工具,但它们的使用依赖于特定的需求和上下文。
39 0
|
3月前
|
缓存 安全 Java
Java服务器端技术:Servlet与JSP的集成与扩展
Java服务器端技术:Servlet与JSP的集成与扩展
32 3
|
3月前
|
存储 缓存 前端开发
Servlet与JSP在Java Web应用中的性能调优策略
Servlet与JSP在Java Web应用中的性能调优策略
31 1
|
3月前
|
存储 Java 关系型数据库
基于Servlet和JSP的Java Web应用开发指南
基于Servlet和JSP的Java Web应用开发指南
37 0
|
5月前
|
自然语言处理 前端开发 Java
Servlet与JSP:Java Web开发的基石技术详解
【6月更文挑战第23天】Java Web的Servlet与JSP是动态网页的核心。Servlet是服务器端的Java应用,处理HTTP请求并响应;JSP则是结合HTML与Java代码的页面,用于动态内容生成。Servlet通过生命周期方法如`init()`、`service()`和`destroy()`工作,而JSP在执行时编译成Servlet。两者在MVC架构中分工,Servlet处理逻辑,JSP展示数据。尽管有Spring MVC等框架,Servlet和JSP仍是理解Web开发基础的关键。
100 12