实验内容:
1、数据库设计
product表、count表:
用eclipse
2、创建javaweb项目:
3.、创建javabean类:
package Server;
import java.io.Serializable;
public class Product implements Serializable
{
private int id;
private String name;
private int price;
public Product(){}
public Product(String name)
{
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package Server;
public class Save
{
private int id;
private int total;
public Save(){}
public Save(int total)
{
this.total = total;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setTotal(int total) {
this.total = total;
}
public int getTotal() {
return total;
}
}
4、数据库操作类
package Server;
import java.sql.*;
public class Usesql
{
Connection con = null;//定义连接
Statement st = null;//定义statement
ResultSet result = null;//定义结果集
public static String driver;//定义驱动
public static String url;//定义URL
public static String user;//定义用户名
public static String password;//定义密码
public Connection getConn(){
try {
driver="com.mysql.jdbc.Driver";
url="jdbc:mysql://localhost:3306/lasttest";
user="root";
password="";
Class.forName(driver);
con = DriverManager.getConnection(url,user,password);//获取数据库连接
System.out.println("-------连接成功------");
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
return this.con;
}
public Usesql()
{
this.con=this.getConn();
//构造函数,默认加裁配置文件为jdbc.driver
}
// 执行数据库查询并返回查询结果
public ResultSet query(String sql)
{
try {
st = con.createStatement();//获取Statement
result = st.executeQuery(sql);//执行查询,返回结果集
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}
//执行数据库更新
public void update(String sql)
{
try {
st = con.createStatement();//获取Statement
st.executeUpdate(sql);
} catch (Exception e)
{
e.printStackTrace();
}
}
//关闭数据库连接
public void close(){
try{
if (result != null)result.close();
if (st != null)st.close();
if (con != null)con.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
5、JSP页面
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="Server.Save" %>
<jsp:useBean id="addp" class="Server.Save" scope="session"></jsp:useBean>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
</head>
<%
String flag = request.getParameter("flag");
if(flag!=null&&flag.equals("false"))
{
out.print("<script>alert('操作数据不能为空!');</script>");
}
%>
<body>
<center>
<h2>增加产品库存功能:</h2>
<form action=addservlet method="post" id="form1">
<!-- 调用addservlet增加servlet -->
产品名称:<input type="text" name="productname" id ="productname"> <br>
增加库存数量: <input type="text" name="productcount" id="productcount"><br>
<input type="submit" value="增加商品库存量"> <br>
</form>
<h2>查询产品信息功能:</h2>
<form action="checkservlet" method="post" id="check">
<!-- 调用checkservlet查询servlet -->
产品名称:<input type="text" name="remandname" id="checkname"><br>
<input type="submit" value="按名字查询产品库存信息"> <br>
</form>
<form action="getallservlet" method="post">
<!-- 调用查询所有信息servlet -->
<input type="submit" value="查询所有产品信息">
</form>
</center>
<jsp:setProperty property="total" name="addp" param="productcount"/>
<script type="text/javascript">
// js验证输入不能为空
document.getElementById("productname").onblur = function ()
{
var a = document.getElementById("productname").value;
if(a==null)
{
alert("产品名称不能为空,请输入产品名称!");
return false;
}
return true;
}
document.getElementById("productcount").onblur = function()
{
var b = document.getElementById("productcount").value;
if(b==null)
{
alert("增加库存不能为空,请输入增加库存量!");
return false;
}
return true;
}
</script>
</body>
</html>
show.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<%
%>
<body>
<center>
ID:<%=session.getAttribute("id") %><br>
名称:<%=session.getAttribute("name") %><br>
价格:<%=session.getAttribute("price") %><br>
库存:<%=session.getAttribute("total") %><br>
<a href="index.jsp">返回首页</a>
</center>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="Server.Save" %>
<jsp:useBean id="addp" class="Server.Save" scope="session"></jsp:useBean>
<!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>Insert title here</title>
</head>
<%
String flag = request.getParameter("flag");
String message = " ";
if(flag!=null&&flag.equals("success"))
{
message = "成功增加库存!";
}
else if(flag!=null&&flag.equals("false"))
{
message = "增加失败,请重新操作!";
}
%>
<body>
<center>
<%=message %><br>
已成功增加库存量为:<%=session.getAttribute("total") %>
<a href="index.jsp">返回首页</a>
</center>
</body>
</html>
6、Servlet代码
增加库存addservlet
package Servlet;
import java.io.IOException;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import Server.Product;
import Server.Save;
import Server.Usesql;
public class addservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String context = request.getContextPath();//获取相对路径
//把数据set到javabean类中
Product product = new Product(new String(request.getParameter("productname").getBytes("iso-8859-1"),"utf-8"));
Save product_save = new Save(Integer.parseInt(request.getParameter("productcount")));
//再通过javabean类对象取出值
String name = product.getName();
Integer total = product_save.getTotal();//要增加的库存量
//与下面两句直接取出数据等同
//String name = new String(request.getParameter("productname").getBytes("iso-8859-1"),"utf-8");
//Integer total = Integer.parseInt(request.getParameter("productcount"));
System.out.println(name);
System.out.println(total);
Usesql usesql = new Usesql();//获取数据库连接
String sql = "select id from product where Name='"+name+"'";//判断数据库中是否有该产品名的SQL语句
ResultSet rs = usesql.query(sql);//执行上述语句,返回结果集
try {
//判断是否成立,即rs是否有值,有则继续执行
while(rs.next())
{
int id;
//取出该产品id
id = rs.getInt("Id");
System.out.println(id);
//通过id查询库存表count中的库存量Total的SQL语句
String sql1 = "select Total from count where id= '"+id+"'";
ResultSet rs1 = usesql.query(sql1);//执行语句,返回结果集
//判断是否成立,即rs1是否有值,有则继续执行
while(rs1.next())
{
int ototal = rs1.getInt("Total");//取出增加前的库存量Total
System.out.println(ototal);
//定义新库存量 = 原库存+增加量
int newtotal = total + ototal;
//执行更新语句更新库存量
String sql2 = "update count set Total ='"+newtotal+"'where Id = '"+id+"' ";
usesql.update(sql2);
HttpSession session = request.getSession();
//放到session中以传递数据
session.setAttribute("total", total);
//关闭数据库连接
usesql.close();
response.sendRedirect(context+"/success.jsp?flag=success");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
查询产品信息checkservlet
package Servlet;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import Server.Product;
import Server.Usesql;
public class checkservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String context = request.getContextPath();//获取相对路径
Product product = new Product(new String(request.getParameter("remandname").getBytes("iso-8859-1"),"utf-8"));
String checkname = product.getName();
//等同于下列语句
//String checkname = new String(request.getParameter("remandname").getBytes("iso-8859-1"),"utf-8");
if(checkname==null||checkname.equals("")||checkname.equals(" "))
{
response.sendRedirect(context+"/index.jsp?flag=false");
}
Usesql usesql = new Usesql();
String sql = "select Name from product where name = '"+checkname+"'";
ResultSet rs = usesql.query(sql);
try {
if(rs.next())
{
//查询的名称与数据库中名称匹配
String sql1 = "select* from product where Name='"+checkname+"'";
ResultSet rs1 = usesql.query(sql1);
//如果数据库中有该产品则往下执行
while(rs1.next())
{
//获取ID、Name、Price数据
int id = rs1.getInt("Id");
System.out.println(id);
HttpSession session = request.getSession();
//session的setAttribute方法传递数据
session.setAttribute("id", rs1.getInt("Id"));
session.setAttribute("name",rs1.getString("Name"));
session.setAttribute("price", rs1.getInt("Price"));
//获取库存数据
String sql2 = "select Total from count where Id = '"+id+"'";
ResultSet rs2 = usesql.query(sql2);
while(rs2.next())
{
int total = rs2.getInt("Total");
session.setAttribute("total", total);
}
response.sendRedirect(context+"/show.jsp");
}
}
} catch (SQLException e) {
//e.printStackTrace();
}
}
}
获取全部信息getallservlet
package Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Server.Usesql;
/**
* Servlet implementation class getallservlet
*/
public class getallservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Usesql usesql = new Usesql();
String context = request.getContextPath();
String sql = "select * from product";
ResultSet rs = usesql.query(sql);
String sql1 = "select Total from count";
ResultSet rs1 =usesql.query(sql1);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println("<HEAD><TITLE>列出产品信息</TITLE></HEAD>");
out.println("<BODY>");
out.println("<center><h4>产品信息列表</h4>");
out.println("<table border=\"1\" width=\"45%\" cellpadding=\"2\" cellspacing=\"1\">");
out.println("<tr>");
out.println("<td>选择</td>");
out.println("<td>ID</td>");
out.println("<td>NAME</td>");
out.println("<td>PRICE</td>");
//out.println("<td>库存量</td>");
out.println("</tr>");
try {
while(rs.next())
{
int id = rs.getInt("Id");
String name = rs.getString("Name");
int price = rs.getInt("Price");
//int total = rs1.getInt("Total");
out.println("<tr>");
out.println("<td><input type=\"checkbox\" name=\"checkgroup\" value=\""+id+"\"></td>");
out.println("<td>"+id+"</td>");
out.println("<td>"+name+"</td>");
out.println("<td>"+price+"</td>");
//out.println("<td>"+total+"</td>");
out.println("</tr>");
}
} catch (SQLException e) {
e.printStackTrace();
}
out.println("</table>");
out.println("<a href='index.jsp'>返回首页</a>");
out.println("</center>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
out.close();
usesql.close();//关闭数据库连接
}
}