一、JSP和Servlet的簡單介紹
1、Servlet和JSP簡介:
Java開發(fā)Web應用程序時用到的技術(shù)主要有兩種,即Servlet和JSP,Servlet是在服務器端執(zhí)行的Java程序,一個被稱為Servlet容器的程序(其實就是服務器) 負責執(zhí)行Java程序,而JSP(Java Server Page)則是一個頁面, 由JSP容器負責執(zhí)行.
2、Servlet和JSP的區(qū)別:
Servlet以Java程序為主, 輸出HTML代碼時需要使用out.println函數(shù),也就是說Java中內(nèi)嵌HTML; 而JSP則以HTML頁面為主,需要寫Java代碼時則在頁面中直接插入Java代碼, 即HTML中內(nèi)嵌Java.
3、MVC模型
MVC模型就是將數(shù)據(jù)、邏輯處理、用戶界面分離的一種方法
1)、M(Model, 模型):用于數(shù)據(jù)處理、邏輯處理
2)、V(View,視圖):用于顯示用戶界面
3)、C(Controller,控制器):根據(jù)客戶端的請求控制邏輯走向和畫面
而在Java中,MVC這三個部分則分別對應于 JavaBeans、JSP和Servlet
1)、M = JavaBeans:用于傳遞數(shù)據(jù),擁有與數(shù)據(jù)相關(guān)的邏輯處理
2)、V = JSP:從Model接收數(shù)據(jù)并生成HTML
3)、C = Servlet:接收HTTP請求并控制Model和View
4、jdbc連接,可參考文章:點擊打開鏈接
二、代碼演示,實現(xiàn)了book的添加刪除和修改功能
1、環(huán)境的配置
myeclipse+tomcat+MySQL
2、Book中bean類
package example.bean.book;
public class Book {
// 編號
private int id;
// 圖書名稱
private String name;
// 價格
private double price;
// 數(shù)量
private int bookCount;
// 作者
private String author;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getBookCount() {
return bookCount;
}
public void setBookCount(int bookCount) {
this.bookCount = bookCount;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
3、Servlet類
1)、FindServlet.java
package example.servlet.book;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import example.bean.book.Book;
/**
* Servlet implementation class FindServlet
*/
public class FindServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
// 加載數(shù)據(jù)庫驅(qū)動,注冊到驅(qū)動管理器
Class.forName("com.mysql.jdbc.Driver");
// 數(shù)據(jù)庫連接字符串
String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=truecharacterEncoding=utf-8";
// 數(shù)據(jù)庫用戶名
String username = "root";
// 數(shù)據(jù)庫密碼
String password = "";
// 創(chuàng)建Connection連接
Connection conn = DriverManager.getConnection(url, username,
password);
// 添加圖書信息的SQL語句
String sql = "select * from tb_books";
// 獲取Statement
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ListBook> list = new ArrayListBook>();
while (resultSet.next()) {
Book book = new Book();
book.setId(resultSet.getInt("id"));
book.setName(resultSet.getString("name"));
book.setPrice(resultSet.getDouble("price"));
book.setBookCount(resultSet.getInt("bookCount"));
book.setAuthor(resultSet.getString("author"));
list.add(book);
}
request.setAttribute("list", list);
resultSet.close();
statement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("book_list.jsp")
.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
2)、UpdateServlet.java類
package example.servlet.book;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class UpdateServlet
*/
public class UpdateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int id = Integer.valueOf(request.getParameter("id"));
int bookCount = Integer.valueOf(request.getParameter("bookCount"));
try {
// 加載數(shù)據(jù)庫驅(qū)動,注冊到驅(qū)動管理器
Class.forName("com.mysql.jdbc.Driver");
// 數(shù)據(jù)庫連接字符串
String url = "jdbc:mysql://localhost:3306/db_book";
// 數(shù)據(jù)庫用戶名
String username = "root";
// 數(shù)據(jù)庫密碼
String password = "";
// 創(chuàng)建Connection連接
Connection conn = DriverManager.getConnection(url, username,
password);
// 更新SQL語句
String sql = "update tb_books set bookcount=? where id=?";
// 獲取PreparedStatement
PreparedStatement ps = conn.prepareStatement(sql);
// 對SQL語句中的第一個參數(shù)賦值
ps.setInt(1, bookCount);
// 對SQL語句中的第二個參數(shù)賦值
ps.setInt(2, id);
// 執(zhí)行更新操作
ps.executeUpdate();
// 關(guān)閉PreparedStatement
ps.close();
// 關(guān)閉Connection
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
// 重定向到FindServlet
response.sendRedirect("FindServlet");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
3)、DeleteServlet類
package example.servlet.book;
import java.io.IOException;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import example.dao.book.BookJdbcDao;
import example.dao.book.ConnectionFactory;
/**
* Servlet implementation class DeleteServlet
*/
public class DeleteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int id = Integer.valueOf(request.getParameter("id"));
try {
// // 加載數(shù)據(jù)庫驅(qū)動,注冊到驅(qū)動管理器
// Class.forName("com.mysql.jdbc.Driver");
// // 數(shù)據(jù)庫連接字符串
// String url = "jdbc:mysql://localhost:3306/db_book";
// // 數(shù)據(jù)庫用戶名
// String username = "root";
// // 數(shù)據(jù)庫密碼
// String password = "";
// // 創(chuàng)建Connection連接
// Connection conn = DriverManager.getConnection(url, username,
// password);
// // 刪除圖書信息的SQL語句
// String sql = "delete from tb_books where id=?";
// // 獲取PreparedStatement
// PreparedStatement ps = conn.prepareStatement(sql);
// // 對SQL語句中的第一個占位符賦值
// ps.setInt(1, id);
// // 執(zhí)行更新操作
// ps.executeUpdate();
// // 關(guān)閉PreparedStatement
// ps.close();
// // 關(guān)閉Connection
// conn.close();
BookJdbcDao bookDao=new BookJdbcDao();
Connection conn=ConnectionFactory.getInstance().getConnection();
bookDao.delete(conn,id);
} catch (Exception e) {
e.printStackTrace();
}
// 重定向到FindServlet
response.sendRedirect("FindServlet");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
4、servlet訪問url映射配置:
由于客戶端是通過URL地址訪問web服務器中的資源,所以Servlet程序若想被外界訪問,必須把servlet程序映射到一個URL地址上,這個工作在web.xml文件中使用servlet>元素和servlet-mapping>元素完成,servlet>元素用于注冊Servlet,它包含有兩個主要的子元素:servlet-name>和servlet-class>,分別用于設置Servlet的注冊名稱和Servlet的完整類名。
一個servlet-mapping>元素用于映射一個已注冊的Servlet的一個對外訪問路徑,它包含有兩個子元素:servlet-name>和url-pattern>,分別用于指定Servlet的注冊名稱和Servlet的對外訪問路徑.另外:同一個Servlet可以被映射到多個URL上,即多個servlet-mapping>元素的servlet-name>子元素的設置值可以是同一個Servlet的注冊名.
eg:上例中的web.xml
?xml version="1.0" encoding="UTF-8"?>
web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
display-name>JdbcConnection/display-name>
welcome-file-list>
welcome-file>index.html/welcome-file>
welcome-file>index.htm/welcome-file>
welcome-file>index.jsp/welcome-file>
welcome-file>default.html/welcome-file>
welcome-file>default.htm/welcome-file>
welcome-file>default.jsp/welcome-file>
/welcome-file-list>
servlet>
description>/description>
display-name>FindServlet/display-name>
servlet-name>FindServlet/servlet-name>
servlet-class>example.servlet.book.FindServlet/servlet-class>
/servlet>
servlet-mapping>
servlet-name>FindServlet/servlet-name>
url-pattern>/FindServlet/url-pattern>
/servlet-mapping>
servlet>
description>/description>
display-name>UpdateServlet/display-name>
servlet-name>UpdateServlet/servlet-name>
servlet-class>example.servlet.book.UpdateServlet/servlet-class>
/servlet>
servlet-mapping>
servlet-name>UpdateServlet/servlet-name>
url-pattern>/UpdateServlet/url-pattern>
/servlet-mapping>
servlet>
description>/description>
display-name>DeleteServlet/display-name>
servlet-name>DeleteServlet/servlet-name>
servlet-class>example.servlet.book.DeleteServlet/servlet-class>
/servlet>
servlet-mapping>
servlet-name>DeleteServlet/servlet-name>
url-pattern>/DeleteServlet/url-pattern>
/servlet-mapping>
/web-app>
5、jsp頁面
1)、index.jsp web頁面主界面
%@page import="java.sql.SQLException"%>
%@page import="java.sql.DriverManager"%>
%@page import="java.sql.Connection"%>
%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
html>
head>
meta http-equiv="Content-Type" content="text/html; charset=utf-8">
title>添加圖書信息/title>
script type="text/javascript">
function check(form) {
with (form) {
if (name.value == "") {
alert("圖書名稱不能為空");
return false;
}
if (price.value == "") {
alert("圖書價格不能為空");
return false;
}
if (author.value == "") {
alert("作者不能為空");
return false;
}
}
}
/script>
/head>
body>
form action="addbook.jsp" method="post" onsubmit="check(this)">
table align="center" width="450">
tr>
td align="center" colspan="2">
h2>添加圖書信息/h2>
hr>
/td>
/tr>
tr>
td align="right">圖書名稱:/td>
td>input type="text" name="name">/td>
/tr>
tr>
td align="right">價 格:/td>
td>input type="text" name="price">/td>
/tr>
tr>
td align="right">數(shù) 量:/td>
td>input type="text" name="bookCount" />/td>
/tr>
tr>
td align="right">作 者:/td>
td>input type="text" name="author" />/td>
/tr>
tr>
td align="center" colspan="2">input type="submit" value="添 加">
/td>
/tr>
/table>
/form>
h2 align="center">
a href="FindServlet">查詢圖書信息/a>
/h2>
/body>
/html>
2)、addbook.jsp 添加書籍成功或者失敗后的顯示頁面
%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
%@page import="java.sql.Connection"%>
%@page import="java.sql.DriverManager"%>
%@page import="java.sql.PreparedStatement"%>
html>
head>
meta http-equiv="Content-Type" content="text/html; charset=utf-8">
title>添加結(jié)果/title>
/head>
body>
%
request.setCharacterEncoding("utf-8");
%>
jsp:useBean id="book" class="example.bean.book.Book">/jsp:useBean>
jsp:setProperty property="*" name="book" />
%
try {
// 加載數(shù)據(jù)庫驅(qū)動,注冊到驅(qū)動管理器
Class.forName("com.mysql.jdbc.Driver");
// 數(shù)據(jù)庫連接字符串
String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=truecharacterEncoding=utf-8";
// 數(shù)據(jù)庫用戶名
String username = "root";
// 數(shù)據(jù)庫密碼
String password = "";
// 創(chuàng)建Connection連接
Connection conn = DriverManager.getConnection(url, username,
password);
// 添加圖書信息的SQL語句
String sql = "insert into tb_books(name,price,bookCount,author) values(?,?,?,?)";
// 獲取PreparedStatement
PreparedStatement ps = conn.prepareStatement(sql);
// 對SQL語句中的第1個參數(shù)賦值
ps.setString(1, book.getName());
// 對SQL語句中的第2個參數(shù)賦值
ps.setDouble(2, book.getPrice());
// 對SQL語句中的第3個參數(shù)賦值
ps.setInt(3, book.getBookCount());
// 對SQL語句中的第4個參數(shù)賦值
ps.setString(4, book.getAuthor());
// 執(zhí)行更新操作,返回所影響的行數(shù)
int row = ps.executeUpdate();
// 判斷是否更新成功
if (row > 0) {
// 更新成輸出信息
out.print("成功添加了 " + row + "條數(shù)據(jù)!");
}
// 關(guān)閉PreparedStatement,釋放資源
ps.close();
// 關(guān)閉Connection,釋放資源
conn.close();
} catch (Exception e) {
out.print("圖書信息添加失?。?);
e.printStackTrace();
}
%>
br>
a href="index.jsp">返回/a>
/body>
/html>
3)、book_list.jsp 查找所有書籍信息的顯示頁面,以表格方式顯示
!--%@page import="sun.awt.SunHints.Value"%>-->
%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
%@page import="java.util.List"%>
%@page import="example.bean.book.Book"%>
html>
head>
meta http-equiv="Content-Type" content="text/html; charset=utf-8">
title>所有圖書信息/title>
style type="text/css">
td {
font-size: 12px;
}
h2 {
margin: 0px
}
/style>
script type="text/javascript">
function check(form) {
with (form) {
if (bookCount.value == "") {
alert("請輸入更新數(shù)量!");
return false;
}
if (isNaN(bookCount.value)) {
alert("格式錯誤!");
return false;
}
return true;
}
}
/script>
/head>
body>
table align="center" width="450" border="1" height="180"
bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1">
tr bgcolor="white">
td align="center" colspan="7">
h2>所有圖書信息/h2>
/td>
/tr>
tr align="center" bgcolor="#e1ffc1">
td>b>ID/b>/td>
td>b>圖書名稱/b>/td>
td>b>價格/b>/td>
td>b>數(shù)量/b>/td>
td>b>作者/b>/td>
td>b>修改/b>/td>
td>b>刪除/b>/td>
/tr>
%
// 獲取圖書信息集合
ListBook> list = (ListBook>) request.getAttribute("list");
// 判斷集合是否有效
if (list == null || list.size() 1) {
out.print("沒有數(shù)據(jù)!");
} else {
// 遍歷圖書集合中的數(shù)據(jù)
for (Book book : list) {
%>
tr align="center" bgcolor="white">
td>%=book.getId()%>/td>
td>%=book.getName()%>/td>
td>%=book.getPrice()%>/td>
td>%=book.getBookCount()%>/td>
td>%=book.getAuthor()%>/td>
td >
form style="align:center; background-color: gray" action="UpdateServlet" method="post"
onsubmit="return check(this);">
input type="hidden" name="id" value="%=book.getId()%>"> input
type="text" name="bookCount" size="3">
input type="submit" value="修改數(shù)量">
/form>
/td>
td>
a href="DeleteServlet?id=%=book.getId()%>">刪除/a>
/td>
/tr>
%
}
}
%>
/table>
h2 align="center">
a href="index.jsp">返回添加圖書信息頁面/a>
/h2>
/body>
/html>
6、jdbc簡單的封裝
1)、ConnectionFactory.java工廠類
package example.dao.book;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionFactory {
private String driverClassName = "com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=truecharacterEncoding=utf-8";
private String userName = "root";
private String password = "";
private static ConnectionFactory connectionFactory=null;
private ConnectionFactory() {
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException
{
return DriverManager.getConnection(url, userName, password);
}
public static ConnectionFactory getInstance()
{
if (null==connectionFactory) {
connectionFactory=new ConnectionFactory();
}
return connectionFactory;
}
}
2)、BookJdbcDao.java數(shù)據(jù)庫操作封裝類
package example.dao.book;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import example.bean.book.Book;
public class BookJdbcDao {
private PreparedStatement ptmt = null;
private ResultSet rs = null;
public BookJdbcDao() {
}
public void findAll(Connection conn) throws SQLException
{
//to do
}
public void delete(Connection conn, int id) throws SQLException
{
String sql = "delete from tb_books where id=?";
try{
ptmt = conn.prepareStatement(sql);
// 對SQL語句中的第一個占位符賦值
ptmt.setInt(1, id);
// 執(zhí)行更新操作
ptmt.executeUpdate();
}finally{
if (null!=ptmt) {
ptmt.close();
}
if (null!=conn) {
conn.close();
}
}
}
public void update(Connection conn, int id ,int bookcount) throws SQLException
{
//to do
}
}
源代碼下載鏈接
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- Java連接 JDBC基礎(chǔ)知識(操作數(shù)據(jù)庫:增刪改查)
- 詳解Java數(shù)據(jù)庫連接JDBC基礎(chǔ)知識(操作數(shù)據(jù)庫:增刪改查)
- Java基礎(chǔ)開發(fā)之JDBC操作數(shù)據(jù)庫增刪改查,分頁查詢實例詳解
- springboot使用JdbcTemplate完成對數(shù)據(jù)庫的增刪改查功能
- java jdbc連接mysql數(shù)據(jù)庫實現(xiàn)增刪改查操作
- JDBC實現(xiàn)數(shù)據(jù)庫增刪改查功能