JAVA-EE简单实例——Servlet

10 篇文章 0 订阅
2 篇文章 0 订阅

首先实现前后端交互有三种方式:

前后交互有3种实现: J2EE, SSMSpringboot

本文就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");
%>
<!DOCTYPE html>
<html>
<head>
<style>

input[type=text],input[type=password],select{
  width: 50%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}
input[type=submit] {
  width: 55%;
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
input[type=submit]:hover {
  background-color: #45a049;
}
div{
	margin-top:200px;
	margin-left: 500px;
}
h1{
	margin-left:230px;
	
}
body{
	background-image:url('image/123.jpg');
	background-repeat: no-repeat;
	background-size:100% 100%;
	background-attachment: fixed;
}
</style>
<meta charset="UTF-8">
<title>星呈商城购物界面</title>
</head>
<body>
<div >
	            <h1>淘宝登录</h1>
	<form action="LoginServlet" method="post" >
    	<b>账号</b>: <input type="text" name="name"> <br>
    	<b>密码</b>: <input type="password" name="password"> <br>
    <input type="submit" value="登录"><span>${message}</span>
	</form>
</div>
</body>
</html>

数据库用的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<Product> products = new ArrayList<Product>();
	//获取jdbc
	Jdbc jdbc=new Jdbc();
	Connection connection=jdbc.getConnection();
	//查询ListProduct
	public List<Product> 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<Product> products=new ArrayList<Product>();
		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"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>商品界面</title>
<style>
	body{
	background-image:url('image/3.jpg');
	background-repeat: no-repeat;
	background-size:100% 100%;
	background-attachment: fixed;
}
div{

}
</style>
</head>
<h1 align='center'><b>星呈商城</b></h1>
<body>	
  <div align="center">
    当前用户: ${user.name}
    <span><a href="ListOrderItem.jsp">购物车</a></span>
  </div> 
	<table align='center' border='1' cellspacing='0'>
		<tr>
			<td>id</td>
			<td>名称</td>
			<td>价格</td>
			<td>购买</td>
		</tr>
		<c:forEach items="${products}" var="product">		
		<tr>
			<td>${product.id}</td>
			<td>${product.name}</td>
			<td>${product.price}</td>
			<td>
				<form action="AddOrderItem" method="post">             
                                       数量<input type="text" value="1" name="num">
           		     <input type="hidden" name="pid" value="${product.id}">
            	     <input type="submit" value="购买">
          	     </form>
			</td>
		</tr>
		</c:forEach>
	</table>
</body>
</html>

同样,在数据库端添加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<OrderItem> ois=(List<OrderItem>)request.getSession().getAttribute("ois");
		if (null==ois) {
			ois=new ArrayList<OrderItem>();
			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<OrderItem> ois=(List<OrderItem>) 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"%>
<!DOCTYPE html>
<html>
<style>
	span{
		position:absolute;
		top:110px;
		left:900px;
	}
</style>
<head>
<meta charset="UTF-8">
<title>购物车界面</title>
</head>
<body>
	<h1 align="center" >购物车</h1>
<table align='center' border='1' cellspacing='0'>
    <tr>
        <td>商品名称</td>
        <td>单价</td>
        <td>数量</td>
        <td>小计</td>
        <td>删除</td>
    </tr>
 
    <c:forEach items="${ois}" var="oi" varStatus="st">
        <tr>
            <td>${oi.product.name}</td>
            <td>${oi.product.price}</td>
            <td>${oi.num}</td>
            <td>${oi.product.price*oi.num}</td>
            <td><a href="DeleteProductServlet?id=${st.index}">删除</a></td>
        </tr>
    </c:forEach>
    <span><a href="ProductListServlet">继续购物</a></span>
</table>
	
</body>
</html>

订单页面效果图:

ok,至此一个简单地J2EE购物车实例完毕。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值