博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JDBC+Servlet+JSP整合开发之30-JDBC、Servlet、JSP的MVC
阅读量:6927 次
发布时间:2019-06-27

本文共 8515 字,大约阅读时间需要 28 分钟。

–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    

        }    



本文转自redking51CTO博客,原文链接:
http://blog.51cto.com/redking/316441
,如需转载请自行联系原作者
你可能感兴趣的文章
扫盲 Linux:如何选择发行版
查看>>
色版黑莓Bold9900已经登岸香港市场
查看>>
报表服务入门(实验3)配置虚拟目录
查看>>
联合类型(union type )
查看>>
一图胜千言 -- SQL Server 监控
查看>>
Exchange-Exchange Server内部版本号和发行日期
查看>>
大数据实践总结分享
查看>>
VMware Workstation and Hyper-V are not compatible. Remove the ...
查看>>
mysql慢查询日志学习
查看>>
ADT学苑
查看>>
Android Studio 学习笔记 - 开发环境的架设
查看>>
Powershell从office365上 删除日历记录
查看>>
CentOS 6.4 Linux vsftpd shell管理系统脚本完整版
查看>>
Nginx之模块处理流程
查看>>
Android应用程序请求SurfaceFlinger服务渲染Surface的过程分析
查看>>
VMCloud见面礼——VMCloud博客迁移全记录
查看>>
三种算法转换色彩灰阶
查看>>
Skype for Business 2015 快速入门手册 v1.1
查看>>
微软私有云分享(R2)25集成WSUS
查看>>
批量删除2012年9月份以前的表
查看>>