–Servlet 的优势与弊端
–JSP 的优势与弊端
–MVC 设计模式
–实例

?使用MVC实现学生信息的添加、显示
-----------------------------START-----------------------------------
? Servlet 的优势与弊端
–优势
?功能强大,可以调用任意的Java JDK API
?能够实现很多高级特征
?成熟
–弊端
?逻辑处理和内容展示很难分离
?开发效率低
–out.println(“”);
?维护成本高
? JSP 的优势与弊端
–优势
?可以直接嵌入静态HTML
?可以直接写代码
?开发效率高
–弊端
?如果直接在JSP页面中写代码
–程序可读性差
–维护困难
? MVC设计模式
–MVC设计模式早在面向对象语言Smalltalk-80中就被提出并在此后得到业界的广泛接受
–它包括三类对象
?模型(Model)对象
–是应用程序的主体部分
?视图(View)对象
–是应用程序中负责生成用户界面的部分
?控制器(Control)对象
–是根据用户的输入,控制用户界面数据显示及更新Model对象状态的部分
–MVC设计模式的好处
? MVC模式不仅实现了功能模块和显示模块的分离
?同时它还提高了应用系统的
–可维护性
–可扩展性
–可移植性
–组件的可复用性
–JSP 的两种实现模式
–具体实现
? 实例
–使用MVC实现学生信息的添加、显示
Datebase
StudentDao.java
StudentDaoImpl.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.StudentDao;    
import com.michael.util.ConnectionUtil;    
import com.michael.util.SQLConstants;    
import com.michael.vo.Student;

public class StudentDaoImpl implements StudentDao,SQLConstants {

public void add(Student stu) {    
                Connection conn = new ConnectionUtil().openConnection();    
                //String sql = "insert into StudentTbl(name,age,email) values(?,?,?)";    
                try {    
                        PreparedStatement pstmt = conn.prepareStatement(ADD_STUDENT_SQL);    
                        pstmt.setString(1, stu.getName());    
                        pstmt.setInt(2, stu.getAge());    
                        pstmt.setString(3, stu.getEmail());    
                        pstmt.executeUpdate();    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                }finally{    
                        try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
        }

public List listStudent() {    
                Connection conn = new ConnectionUtil().openConnection();    
                //String sql = "insert into StudentTbl(name,age,email) values(?,?,?)";    
                try {    
                        Statement stmt = conn.createStatement();    
                        ResultSet rs = stmt.executeQuery(QUERY_STUDENT_SQL);    
                        List list = new ArrayList();    
                        while(rs.next()){    
                                int id = rs.getInt(1);    
                                String name = rs.getString(2);    
                                int age = rs.getInt(3);    
                                String email = rs.getString(4);    
                                Student stu = new Student();    
                                stu.setId(id);    
                                stu.setName(name);    
                                stu.setAge(age);    
                                stu.setEmail(email);    
                                list.add(stu);    
                        }    
                        return list;    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                }finally{    
                        try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
                return null;    
        }

}

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
DBConfig.properties
Student.java
StudentDaoImplTest.java
下面进行单元测试
数据库添加成功!
下面继续哈~
stu.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 'stu.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/StuServlet?methodName=add" method="post">    
            <table border="0">    
                <tr>    
                    <td>姓名:</td>    
                    <td><input type="text" name="name"></td>    
                </tr>    
                <tr>    
                    <td>年龄:</td>    
                    <td><input type="text" name="age"></td>    
                </tr>    
                <tr>    
                    <td>电邮:</td>    
                    <td><input type="text" name="email"></td>    
                </tr>    
                <tr>    
                    <td colspan="2" align="center"><input type="submit" value="添加"></td>    
                </tr>    
            </table>    
        </form>    
        <hr>    
        <table>    
                <tr><th>ID</th><th>Name</th><th>Age</th><th>Email</th></tr>    
                <redking:forEach>    
                        <tr>    
                                <td>${s.id }</td>    
                                <td>${s.name }</td>    
                                <td>${s.age }</td>    
                                <td>${s.email }</td>    
                        </tr>    
                </redking:forEach>    
        </table>    
    </body>    
</html>

StuServlet.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.StudentDao;    
import com.michael.dao.impl.StudentDaoImpl;    
import com.michael.vo.Student;

public class StuServlet extends HttpServlet {

/**    
         * Constructor of the object.    
         */    
        public StuServlet() {    
                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{    
                        query(request,response);    
                }    
                /*    
                //响应用户请求    
                String name = request.getParameter("name");    
                String age = request.getParameter("age");    
                String email = request.getParameter("email");    
                //调用后台逻辑    
                StudentDao dao = new StudentDaoImpl();    
                Student stu = new Student();    
                stu.setName(name);    
                stu.setAge(new Integer(age));    
                stu.setEmail(email);    
                dao.add(stu);    
                List list = dao.listStudent();    
                request.setAttribute("StuList", list);    
                //数据处理后跳转    
                request.getRequestDispatcher("/stu.jsp").forward(request,response);    
                */    
        }    
        public void add(HttpServletRequest request, HttpServletResponse response)    
                        throws ServletException, IOException {    
                //响应用户请求    
                String name = request.getParameter("name");    
                String age = request.getParameter("age");    
                String email = request.getParameter("email");    
                //调用后台逻辑    
                StudentDao dao = new StudentDaoImpl();    
                Student stu = new Student();    
                stu.setName(name);    
                stu.setAge(new Integer(age));    
                stu.setEmail(email);    
                dao.add(stu);    
                query(request,response);    
        }

public void query(HttpServletRequest request, HttpServletResponse response)    
                        throws ServletException, IOException {

//调用后台逻辑    
                StudentDao dao = new StudentDaoImpl();    
                List list = dao.listStudent();    
                request.setAttribute("StuList", list);    
                // 跳转    
                request.getRequestDispatcher("/stu.jsp").forward(request, response);    
        }    
        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occurs    
         */    
        public void init() throws ServletException {    
                // Put your code here    
        }

}

------------------------------END-------------------------------------

转载于:https://blog.51cto.com/redking/316441

JDBC+Servlet+JSP整合开发之30-JDBC、Servlet、JSP的MVC相关推荐

  1. Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之06.JDBC PreparedStatement

    –PreparedStatement –为占位符"?"赋值 –使用PreparedStatement动态执行SQL语句 ####################Michael分割线 ...

  2. Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之14.Servlet请求头信息

    –典型的请求头信息 –读取HTTP请求头 –使用表格显示所有请求头信息 –理解各种请求头的含义 –区分不同的浏览器类型 ##############Michael分割线################ ...

  3. JDBC+Servlet+JSP整合开发之25.JSP动作元素

    –jsp:useBean –jsp:setProperty –jsp:getProperty –jsp:forward –jsp:include –jsp:param –实例 ?计算器 ------- ...

  4. Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之12.Servlet基础(2)

    –提交表单的方法 • get • post –Servlet 生命周期 –使用Servlet 输出HTML页面 –获得Servlet初始化参数 –页面导航 • 请求重定向 –response.send ...

  5. Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之10.Web_工程结构

    –简介 –Web应用程序的思想 –Web应用程序的目的 –Web工程结构 –web.xml 文件 –实例 • 创建一个简单的web应用程序 • 部署到tomcat中来运行 ############## ...

  6. JDBC+Servlet+JSP整合开发之22.JSP简介

    –对JSP的需求 –JSP的结构 –JSP的好处 –JSP实例 ?创建一个简单的JSP页面 ########################################### ? JSP –JSP ...

  7. Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之13.Form表单处理(1)

    –Form 表单简介 –创建并提交表单 –使用Servlet处理表单 • 读取单个请求参数 • 读取多个表单 • 读取所有参数名称 –实例 • 注册会员 ###############Michael分 ...

  8. JDBC+Servlet+JSP整合开发之26.JSP内建对象

    –使用内建对象的目的  –内建对象  –out 内建对象  –request 内建对象  –response 对象  –session 内建对象  –pageContext 内建对象  –applic ...

  9. JDBC+Servlet+JSP整合开发之29-JSP表达式语言(EL)

    –EL 简介  –EL的应用场合  –EL 的基本语法  –EL中的算术运算符  –EL中的关系运算符  –EL中的逻辑运算符 ------------------------------START- ...

最新文章

  1. 模式6--ReadWriteLock
  2. python免费课程讲解-Python快速入门免费课程
  3. C#调用DLL文件时参数对应表
  4. Andorid之bitmap里面的压缩总结
  5. dubbo-快速入门-分布式RPC框架Apache Dubbo
  6. qt创建右键菜单,显示在鼠标点击处
  7. 使用Azure Data Factory优雅的迁移SQL Server 2000 DTS包
  8. wampserver橙色如何变成绿色_绿色配什么颜色好看 家居绿色配色小技巧-装修攻略...
  9. SAP License:从SAP顾问面试看职场
  10. GDAL库中WFS服务中含有中文不能获取数据的问题
  11. 架构模式: API网关
  12. u8系统怎么连接服务器,u8客户端如何连接服务器
  13. Java图书管理系统登陆界面
  14. Android强制系统横屏的原理和实现
  15. 3.7 App.vue-常用配置【uni-app教程uniapp教程(黄菊华-跨平台开发系列教程)】
  16. 《当程序员的那些狗日日子》四
  17. php图形验证码验证,php图片验证码代码
  18. 第五期:写一篇高水平的工程类英文论文(SCI/EI)_图和表(Figure and Table)【论文写作】
  19. AIR - 网页系统回到桌面应用
  20. Simple Factory

热门文章

  1. 我在学习springboot和vue前后台连接时碰到的问题记录!(跨域问题)
  2. 2021年春季学期-信号与系统-第十次作业参考答案-第一小题
  3. 固态铝电解电容与液态铝电解电容
  4. N-MOS 2N7002晶体管
  5. 同一MODBUS读写多(两)个BH32角度传感器
  6. c# 获取所有的进程的cpu使用率_Linux CPU使用率很高,但为啥却找不到高CPU的进程
  7. windows sftp工具_将SSH服务器映射成Windows网络驱动器
  8. mysql mysqlhotcopy_MySQL备份之mysqlhotcopy与注意事项
  9. java 判断时间合法_java 中 Date 类型快判断日期是否合法.
  10. python操作sqlserver如何判断删除的数据不存在_Python MongoDB 插入数据时已存在则不执行,不存在则插入的解决方法...