首先实现前后端交互有三种方式:
前后交互有3种实现: J2EE, SSM 和 Springboot。
本文就J2EE的方式来实例化。
项目效果:淘宝登录界面、购物车界面(主要实现前端、Servlet、数据库三者交互)。
项目结构图:
建好项目后导入需要用到的jar包放入WEB-INF下的lib包里。
首先,我们写一个登录界面效果如图(忽略我前端水平。23333)
user类
package bean;
public class User {
public int id;
public String name;
public String password;
public User() {
super();
}
public User(int id, String name, String password) {
super();
this.id = id;
this.name = name;
this.password = password;
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
userDAO:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import bean.User;
import jdbc.Jdbc;
public class UserDAO {
//参数
User user=new User();
//获取jdbc
Jdbc jdbc=new Jdbc();
Connection connection=jdbc.getConnection();
//登录验证--账户正确否
public User getUser(String name,String password) {
try {
String sql="select * from user where name = ? and password=?";
PreparedStatement ps=connection.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
ResultSet rs=ps.executeQuery();
while(rs.next()) {
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
}
ps.close();
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
}
jdbc:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Jdbc {
//全局变量
Connection connection=null;
public Connection getConnection() {
//jdbc
try {
Class.forName("com.mysql.jdbc.Driver");
String user ="root";
String password="admin";
String url="jdbc:mysql://127.0.0.1:3306/cart?characterEncoding=UTF-8";
connection=DriverManager.getConnection(url,user,password);
if (connection != null) {
System.out.println("conn: "+connection);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
//测试
public static void main(String[] args) {
Jdbc jdbc=new Jdbc();
jdbc.getConnection();
}
}
LoginServlet:
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.User;
import dao.UserDAO;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
//参数
UserDAO userDAO =new UserDAO();
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//编码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//获取form表单数据
String name=request.getParameter("name");
String password=request.getParameter("password");
User user =userDAO.getUser(name, password);
if (user.name!=null||user.password!=null) {
request.getSession().setAttribute("user", user);
request.getRequestDispatcher("ProductListServlet").forward(request, response);
}else {
request.getSession().setAttribute("message", "密码错误");
response.sendRedirect("Login.jsp");
}
}
/**
* @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);
}
}
前端Login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String message=(String)session.getAttribute("message");
%>
星呈商城购物界面
淘宝登录
数据库用的mysql,简单的编一个user表即可。
到这儿一个简单的登录页面就写好了,登录可设置验证,验证通过则进入购物页面,反之跳转登录页面并报错。
接下来则是购物页面的编写了。
product类:
package bean;
public class Product {
public int id;
public String name;
public float price;
public Product(int id, String name, float price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public Product() {
super();
}
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
productDao:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import bean.Product;
import jdbc.Jdbc;
public class ProductDAO {
//全局变量
List products = new ArrayList();
//获取jdbc
Jdbc jdbc=new Jdbc();
Connection connection=jdbc.getConnection();
//查询ListProduct
public List ListProduct() {
try {
String sql="select * from product order by id desc";
PreparedStatement ps=connection.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
while (rs.next()) {
Product product =new Product();
int id = rs.getInt(1);
String name = rs.getString(2);
float price = rs.getFloat(3);
product.setId(id);
product.setName(name);
product.setPrice(price);
products.add(product);
}
ps.close();
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return products;
}
public static void main(String[] args) {
ProductDAO productDAO =new ProductDAO();
System.out.println(productDAO.ListProduct());
}
}
productListServlet:
package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.Product;
import dao.ProductDAO;
/**
* Servlet implementation class ProductListServlet
*/
@WebServlet("/ProductListServlet")
public class ProductListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ProductListServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//成员变量
List products=new ArrayList();
ProductDAO productDAO=new ProductDAO();
//查询list
products=productDAO.ListProduct();
request.setAttribute("products", products);
request.getRequestDispatcher("ListProducts.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);
}
}
ListProducts.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
商品界面
星呈商城
当前用户: ${user.name}
购物车
id
名称
价格
购买
${product.id}
${product.name}
${product.price}
同样,在数据库端添加product表即可:
登录跳转页面成功效果;(同样忽略我的前端水平)
到这儿购物页面也写完了,接下来就是购物车页面了
购物车页面即订单页面(可拓展为多订单项)
orderItem类:
package bean;
public class OrderItem {
private int id;
private Product product;
private int num;
public OrderItem() {
super();
}
public OrderItem(int id, Product product, int num) {
super();
this.id = id;
this.product = product;
this.num = num;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
订单页面的增加:
AddProductDAO:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import bean.Product;
import jdbc.Jdbc;
public class AddProductDAO {
//全局参数
Product product=new Product();
//获取jdbc
Jdbc jdbc=new Jdbc();
Connection connection=jdbc.getConnection();
public Product getProduct(int id) {
try {
String sql="select * from product where id=?";
PreparedStatement ps=connection.prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs=ps.executeQuery();
while(rs.next()) {
product.setId(rs.getInt(1));
product.setName(rs.getString(2));
product.setPrice(rs.getFloat(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return product;
}
}
AddOrderItem:
package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.OrderItem;
import bean.Product;
import dao.AddProductDAO;
/**
* Servlet implementation class AddOrderItem
*/
@WebServlet("/AddOrderItem")
public class AddOrderItem extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddOrderItem() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//参数
OrderItem oi=new OrderItem();
int num=Integer.parseInt(request.getParameter("num"));
int pid=Integer.parseInt(request.getParameter("pid"));
Product product=new AddProductDAO().getProduct(pid);
oi.setId(pid);
oi.setProduct(product);
oi.setNum(num);
@SuppressWarnings("unchecked")
List ois=(List)request.getSession().getAttribute("ois");
if (null==ois) {
ois=new ArrayList();
request.getSession().setAttribute("ois",ois);
}
boolean found = false;
for (OrderItem orderItem : ois) {
if (orderItem.getProduct().getId() == oi.getProduct().getId()) {
orderItem.setNum(orderItem.getNum() + oi.getNum());
found = true;
break;
}
}
if (!found) {
ois.add(oi);
}
response.sendRedirect("ListOrderItem.jsp");
}
/**
* @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);
}
}
订单页面的删除:
DeleteProductDAO
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import jdbc.Jdbc;
public class DeleteProductDAO {
//参数
//获取jdbc
Jdbc jdbc=new Jdbc();
Connection connection=jdbc.getConnection();
public void DeleteProduct(int id) {
String sql="delete from product where id=?";
try {
PreparedStatement ps=connection.prepareStatement(sql);
ps.setInt(1, id);
ps.execute();
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
DeleteProductServlet
package servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.OrderItem;
/**
* Servlet implementation class DeleteProductServlet
*/
@WebServlet("/DeleteProductServlet")
public class DeleteProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DeleteProductServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取参数
int id=Integer.parseInt(request.getParameter("id"));
@SuppressWarnings("unchecked")
List ois=(List) request.getSession().getAttribute("ois");
ois.remove(id);
request.getRequestDispatcher("ListOrderItem.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);
}
}
前端页面:
ListOrderItem.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
购物车界面
购物车
商品名称
单价
数量
小计
删除
${oi.product.name}
${oi.product.price}
${oi.num}
${oi.product.price*oi.num}
删除
继续购物
订单页面效果图:
ok,至此一个简单地J2EE购物车实例完毕。