1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > JDBC+Servlet+JSP整合开发之30-JDBC Servlet JSP的MVC

JDBC+Servlet+JSP整合开发之30-JDBC Servlet JSP的MVC

时间:2018-12-20 06:41:19

相关推荐

JDBC+Servlet+JSP整合开发之30-JDBC Servlet JSP的MVC

–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实现学生信息的添加、显示DatebaseStudentDao.javaStudentDaoImpl.javapackage 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.javapackage 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.javaDBConfig.propertiesStudent.javaStudentDaoImplTest.java下面进行单元测试 数据库添加成功! 下面继续哈~stu.jsp<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>

<%@ taglib uri="/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.javapackage 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-------------------------------------

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。