Web课设总结

图书添加

创建Web项目,通过JDBC实现图书信息添加功能。

(1)在数据库中创建图书信息表tb-books

(2)创建名称为Book的类,用于封装图书对象信息。关键代码如下:

package com.lyq.bean;

public class Book {

// 编号

private int id;

// 图书名称

private String name;

// 价格

private double price;

// 数量

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)创建index.jsp页面,用于放置添加图书信息所需的表单,该表单提交到AddBook.jsp页面进行处理。关键代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/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;

}

return true;

}

}

</script>

</head>

<body>

<form action="AddBook.jsp" method="post" onsubmit="return 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">数 量:</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>

</body>

</html>

(4)创建AddBook.jsp页面,用于对添加图书信息请求进行处理,该页面通过JDBC所提交的图书信息数据写入数据库中。关键代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/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>添加结果</title>

</head>

<body>

<jsp:useBean id="book" class="com.lyq.bean.Book"></jsp:useBean>

<jsp:setProperty property="*" name="book"/>

<%

try {

// 加载数据库驱动,注册到驱动管理器

Class.forName("com.mysql.jdbc.Driver");

// 数据库连接字符串

String url = "jdbc:mysql://localhost:3306/db_database10";

// 数据库用户名

String username = "root";

// 数据库密码

String password = "111";

// 创建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个参数赋值

ps.setString(1, book.getName());

System.out.println("name:"+book.getName());

// 对SQL语句中的第2个参数赋值

ps.setDouble(2, book.getPrice());

// 对SQL语句中的第3个参数赋值

ps.setInt(3,book.getBookCount());

// 对SQL语句中的第4个参数赋值

ps.setString(4, book.getAuthor());

// 执行更新操作,返回所影响的行数

int row = ps.executeUpdate();

// 判断是否更新成功

if(row > 0){

// 更新成输出信息

out.print("成功添加了 " + row + "条数据!");

}

// 关闭PreparedStatement,释放资源

ps.close();

// 关闭Connection,释放资源

conn.close();

} catch (Exception e) {

out.print("图书信息添加失败!");

e.printStackTrace();

}

%>

<br>

<a href="index.jsp">返回</a>

</body>

</html>

信息分页查询

通过MySQL数据库提供的分页机制,实现商品信息的分页查询功能,将分页数据显示在JSP页面中(20%)

(1)创建名称为Product的类,用于封装商品信息,该类是商品信息的JavaBean。关键代码如下:

package com.lyq.bean;

/**

* 商品

*

*/

public class Product {

public static final int PAGE_SIZE = 2;

// 编号

private int id;

// 名称

private String name;

// 价格

private double price;

// 数量

private int num;

// 单位

private String unit;

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 getNum() {

return num;

}

public void setNum(int num) {

this.num = num;

}

public String getUnit() {

return unit;

}

public void setUnit(String unit) {

this.unit = unit;

}

}

(2)创建名称为BookDao类,主要用于封装商品对象的数据库相关操作。在ProductDao类中,首先编写GetConnection()方法,用于创建数据库连接Connection对象,其关键代码如下:

package com.lyq.bean;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;

/**

* 商品数据库操作

*/

public class BookDao {

/**

* 获取数据库连接

* @return Connection对象

*/

public Connection getConnection(){

// 数据库连接

Connection conn = null;

try {

// 加载数据库驱动,注册到驱动管理器

Class.forName("com.mysql.jdbc.Driver");

// 数据库连接字符串

String url = "jdbc:mysql://localhost:3306/db_database10"; // 数据库用户名

String username = "root";

// 数据库密码

String password = "111";

// 创建Connection连接

conn = DriverManager.getConnection(url,username,password); } catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}

// 返回数据库连接

return conn;

}

/**

* 分页查询所有商品信息

* @param page 页数

* @return List<Product>

*/

public List<Product> find(int page){

// 创建List

List<Product> list = new ArrayList<Product>();

// 获取数据库连接

Connection conn = getConnection();

// 分页查询的SQL语句

String sql = "select * from tb_product order by id desc limit ?,?"; try {

// 获取PreparedStatement

PreparedStatement ps = conn.prepareStatement(sql);

// 对SQL语句中的第1个参数赋值

ps.setInt(1, (page - 1) * Product.PAGE_SIZE);

// 对SQL语句中的第2个参数赋值

ps.setInt(2, Product.PAGE_SIZE);

// 执行查询操作

ResultSet rs = ps.executeQuery();

// 光标向后移动,并判断是否有效 while(rs.next()){ // 实例化Product Product p = new Product(); // 对id属性赋值 p.setId(rs.getInt("id")); // 对name属性赋值 p.setName(rs.getString("name")); // 对num属性赋值 p.setNum(rs.getInt("num")); // 对price属性赋值 p.setPrice(rs.getDouble("price")); // 对unit属性赋值 p.setUnit(rs.getString("unit")); // 将Product添加到List集合中 list.add(p); } // 关闭ResultSet rs.close(); // 关闭PreparedStatement ps.close(); // 关闭Connection conn.close(); } catch (SQLException e) { e.printStackTrace(); } return list; } /** * 查询总记录数 * @return 总记录数 */ public int findCount(){ // 总记录数 int count = 0; // 获取数据库连接 Connection conn = getConnection(); // 查询总记录数SQL语句 String sql = "select count(*) from tb_product"; try { // 创建Statement Statement stmt = conn.createStatement(); // 查询并获取ResultSet ResultSet rs = stmt.executeQuery(sql); // 光标向后移动,并判断是否有效 if(rs.next()){ // 对总记录数赋值 count = rs.getInt(1); } // 关闭ResultSet

rs.close();

// 关闭Connection

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

// 返回总记录数

return count;

}

}

(3)创建名称为FindServlet的类,该类是分页查询商品信息的Servlet对象。在FindServlet类中重写doGet()方法,对分页请求进行处理,其关键代码如下: package com.lyq.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.lyq.bean.Product;

import com.lyq.bean.BookDao;

/**

* Servlet implementation class FindServlet

*/

public class FindServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// 当前页码

int currPage = 1;

// 判断传递页码是否有效

if(request.getParameter("page") != null){

// 对当前页码赋值

currPage = Integer.parseInt(request.getParameter("page")); }

// 实例化ProductDao

BookDao dao = new BookDao();

// 查询所有商品信息

List<Product> list = dao.find(currPage);

// 将list放置到request之中

request.setAttribute("list", list);

// 总页数

int pages ;

// 查询总记录数

int count = dao.findCount();

// 计算总页数

if(count % Product.PAGE_SIZE == 0){

// 对总页数赋值

pages = count / Product.PAGE_SIZE;

}else{

// 对总页数赋值

pages = count / Product.PAGE_SIZE + 1;

}

// 实例化StringBuffer

StringBuffer sb = new StringBuffer();

// 通过循环构建分页条

for(int i=1; i <= pages; i++){

// 判断是否为当前页

if(i == currPage){

// 构建分页条

sb.append("『" + i + "』");

}else{

// 构建分页条

sb.append("<a href='FindServlet?page=" + i + "'>" + i + "</a>"); }

// 构建分页条

sb.append(" ");

}

// 将分页条的字符串放置到request之中

request.setAttribute("bar", sb.toString());

// 转发到product_list.jsp页面

request.getRequestDispatcher("product_list.jsp").forward(request, response);

}

}

(4)创建product_list.jsp页面,该页面通过获取查询结果集List与分页条来分页显示商品信息数据,其关键代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">

<%@page import="java.util.List"%>

<%@page import="com.lyq.bean.Product"%><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>

</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="5">

<h2>所有商品信息</h2>

</td>

</tr>

<tr align="center" bgcolor="#e1ffc1" >

<td><b>ID</b></td>

<td><b>商品名称</b></td>

<td><b>价格</b></td>

<td><b>数量</b></td>

<td><b>单位</b></td>

</tr>

<%

List<Product> list = (List<Product>)request.getAttribute("list"); for(Product p : list){

%>

<tr align="center" bgcolor="white">

<td><%=p.getId()%></td>

<td><%=p.getName()%></td>

<td><%=p.getPrice()%></td>

<td><%=p.getNum()%></td>

<td><%=p.getUnit()%></td>

</tr>

<%

}

%>

<tr>

<td align="center" colspan="5" bgcolor="white">

<%=request.getAttribute("bar")%>

</td>

</tr>

</table>

</body>

</html>

(5)编写程序中的主页面index.jsp,在该页面中编写分页查询商品信息的超链接,指向FindServlet。其关键代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>主页</title>

</head>

<body>

<a href="FindServlet">查看所有商品信息</a>

</body>

</html>

注册页面设计

(1)新建Web项目,新建reguser1.jsp页面,主要用于注册页面的显示,将该表单提交到reguser2.jsp页面进行处理。主要代码如下:

<%@page language = "java" import ="java.util.*" pageEncoding = "gb2312"%> <script language="javascript">

function check(){

var b=/^[A-Za-z][A-Za-z0-9_]{5,19}$/;

if(!b.test(document.getElementById("user_name").value))

{

alert("用户名非法");

return false;

}

}

</script>

<!DOCTYPE HTML PUBLIC"-//WOC//DTD HTML 4.01 Transitinal//EN">

<html>

<head>

<title>

注册页面

</title>

</head>

<body>

<center>

<h1 style="font-size:100px">新用户注册</h1>

</center>

<center><h2 style="font-size:50px; width:950px"align="left"> 请准确填写您的个人信息,以便我们更好地为您服务,Thanks!

</h2>

</center>

<center>

<form method ="post"action="reg"name="form1"onsubmit="return check()" style="height: 2400px; width: 1000px; ">

<table align="center"border="0" cellpadding = "20"

cellpadding="0"width="100%">

<tbody>

<tr>

<td colspan="2"style="font-size:50px">注册信息(注:带*号为必填项)</td>

</tr>

<tr>

<td width="326"height="68"style="font-size:50px">用户名:</td>

<td width="326"headers="68"style="font-size:50px"><input type="username" name="username"id="user_name" size=20 style="font-size:40px">

<span style="color:red;font-size:2px">*</span></td>

</tr>

<tr>

<td width="112"height="34"style="font-size:50px">密码:</td>

<td width="326"headers="34"><input

name="password1"type="password"style="font-size:40px">

<span style="color:red;font-size:2px">&nbsp*</span></td>

</tr>

<tr>

<td width="112"height="34"style="font-size:50px">密码确认:</td> <td width="326"headers="34"><input

name="password2"type="password"style="font-size:40px">

<span style="color:red;font-size:2px">&nbsp*</span></td>

</tr>

<td height="56"colspan="4"> <center>

<input name="submit"type="submit"value="提交"style="font-size:40px"> <input name="reset"type="reset"value="重写

"style="font-size:40px"></center>

</td>

</tr>

</tbody>

</table>

</form></center>

</body>

</html>

(2)创建名为reguser2.jsp页面,该页面主要用于显示从reguser1.jsp提交过来的注册信息,主要代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>

<%

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 'reguser2.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>

<h></br></h>

<center>

<h1 style="font-size:100px">欢迎您!您已成功注册成为本站会员!</h1>

</center>

<h2></br></br></h2>

<table width="50%"height="500"align="center"border="1">

<tr><td height="27"colspan="2"align="center"><font size="50">你的注册信息</font></td>

</tr>

<tr>

<td width="36%"height="43"><div align="left"style="font-size:50px">您的用户名:</div></td>

<td

width="64"align="center"style="font-size:50"><%=request.getAttribute("username")%></td>

</tr>

</table>

<h3></br>

</br></br></h3>

<center><input type="button" value="退出"

onClick="window.location.href='reguser1.jsp'" style="height: 65px; width: 124px;font-size:50;">

</body>

</html>

(3)创建名为servlet的serlet文件,主要代码如下:

(4)package servlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class RegServlet extends HttpServlet {

/**

* Constructor of the object.

*/

public RegServlet() {

super();

}

/**

* Destruction of the servlet. <br>

*/

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

public void doDelete(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

// Put your code here

}

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

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("<HTML>");

out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");

out.println(" <BODY>");

out.print(" This is ");

out.print(this.getClass());

out.println(", using the GET method");

out.println(" </BODY>");

out.println("</HTML>");

out.flush();

out.close();

}

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

String username=request.getParameter("username");

request.setAttribute("username",username);

RequestDispatcher

dispatcher=request.getRequestDispatcher("reguser2.jsp");

dispatcher.forward(request, response);

}

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

// Put your code here

}

public String getServletInfo() {

return "This is my default servlet created by Eclipse";

}

public void init() throws ServletException {

// Put your code here

}

}

相关推荐