基于XML配置方式SSM框架西蒙购物网
2023-12-24 15:51:26
文章目录
- 一、网站功能需求
- 二、网站设计思路
- 三、网站运行效果
- 四、网站实现步骤
- (一)创建数据库与表
- (二)创建Maven项目 - SSMSimonShop
- (三)在pom.xml文件里添加相关依赖
- (四)创建日志属性文件 - log4j.properties
- (五)创建数据库配置属性文件 - jdbc.properties
- (六)给项目添加Web功能
- (七)配置Tomcat服务器
- (八)创建实体类
- (九)创建映射器接口
- (十)创建服务类
- (十一)创建控制器
- (十二)创建映射器配置文件
- (十三)创建Spring配置文件 - spring-config.xml
- (十四)创建Spring MVC配置文件 - spring-mvc-config.xml
- (十五)编辑Web部署描述文件 - web.xml
- (十六)准备图片资源
- (十七)创建样式文件 - main.css
- (十八)创建脚本文件 - check.js
- (十九)创建页面
- (二十)启动服务器,查看效果
- (二十一)待完成功能
- 五、利用Bootstrap框架改进网站界面
一、网站功能需求
1、只有注册用户成功登录之后才可查看商品类别,查看商品,选购商品,生成订单、查看订单。
2、只有管理员才有权限进入购物网后台管理(用户管理+类别管理+商品管理+订单管理)
二、网站设计思路
1、设计模式
分层架构:展现层(JSP)<——>控制层(Controller)<——>业务层(Service)<——>数据映射层(Mapper)<——>数据库(DB)
2、网站前台
(1)登录——显示商品类别——显示某类商品信息——查看购物车——生成订单——支付
(2)注册<——>登录
3、网站后台
(1)用户管理(查看用户、添加用户、修改用户、删除用户)
(2)类别管理(查看类别、添加类别、修改类别、删除类别)
(3)商品管理(查看商品、添加商品、修改商品、删除商品)
(4)订单管理(查看订单、删除订单)
4、购物流程图
三、网站运行效果
- 操作演示
- 登录页面
- 显示商品类别页面
- 显示商品与购物页面
- 生成订单页面
- 显示订单页面
- 后台管理主页面
- 查看用户页面
四、网站实现步骤
(一)创建数据库与表
1、创建数据库 - simonshop
2、创建用户表 - t_user
- 创建用户表结构
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(20) DEFAULT NULL,
`telephone` varchar(11) DEFAULT NULL,
`register_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`popedom` int(11) DEFAULT NULL COMMENT '0:管理员;1:普通用户',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
- 在用户表里插入记录
INSERT INTO `t_user` VALUES ('1', 'admin', '12345', '15734345678', '2016-12-02 08:40:35', '0');
INSERT INTO `t_user` VALUES ('2', '郑晓红', '11111', '13956567889', '2016-12-20 09:51:43', '1');
INSERT INTO `t_user` VALUES ('3', '温志军', '22222', '13956678907', '2016-12-20 09:52:36', '1');
INSERT INTO `t_user` VALUES ('4', '涂文艳', '33333', '15890905678', '2016-12-05 09:52:56', '1');
3、创建商品类别表 - t_category
- 创建商品类别表结构
CREATE TABLE `t_category` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '商品类别标识符',
`name` varchar(100) NOT NULL COMMENT '商品类别名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
- 在商品类别表里插入记录
4、创建商品表 - t_product
- 创建商品表结构
CREATE TABLE `t_product` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '商品标识符',
`name` varchar(200) NOT NULL COMMENT '商品名称',
`price` double DEFAULT NULL COMMENT '商品单价',
`add_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`category_id` int(11) DEFAULT NULL COMMENT '商品类别标识符',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
- 在商品表里插入记录
INSERT INTO `t_product` VALUES ('1', '容声电冰箱', '2000', '2016-12-20 09:54:41', '1');
INSERT INTO `t_product` VALUES ('2', '松下电视', '5000', '2016-12-20 09:54:35', '1');
INSERT INTO `t_product` VALUES ('3', '红岩墨水', '3', '2016-12-20 09:56:05', '3');
INSERT INTO `t_product` VALUES ('4', '海尔洗衣机', '1000', '2016-11-30 08:58:09', '1');
INSERT INTO `t_product` VALUES ('5', '新宇电饭煲', '1200', '2016-12-20 09:55:11', '1');
INSERT INTO `t_product` VALUES ('6', '英雄微波炉', '600', '2016-12-20 09:55:39', '1');
INSERT INTO `t_product` VALUES ('7', '红双喜席梦思', '700', '2016-11-28 08:59:38', '2');
INSERT INTO `t_product` VALUES ('8', '旺仔牛奶糖', '24.4', '2016-12-20 10:00:11', '4');
INSERT INTO `t_product` VALUES ('9', '西蒙枕头', '100', '2016-12-20 09:56:57', '2');
INSERT INTO `t_product` VALUES ('10', '甜甜毛毯', '400', '2016-12-20 09:57:26', '2');
INSERT INTO `t_product` VALUES ('11', '永久钢笔', '50', '2016-12-20 09:57:30', '3');
INSERT INTO `t_product` VALUES ('12', '硬面抄笔记本', '5', '2016-12-20 09:57:53', '3');
INSERT INTO `t_product` VALUES ('13', '晨光橡皮擦', '0.5', '2016-11-30 09:02:40', '3');
INSERT INTO `t_product` VALUES ('14', '美的空调', '3000', '2016-11-03 09:03:02', '1');
INSERT INTO `t_product` VALUES ('15', '迷你深海鱼肠', '14.4', '2016-12-02 10:01:14', '4');
5、创建订单表 - t_order
- 创建订单表结构
CREATE TABLE `t_order` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '订单标识符',
`username` varchar(20) DEFAULT NULL COMMENT '用户名',
`telephone` varchar(11) DEFAULT NULL COMMENT '电话号码',
`total_price` double DEFAULT NULL COMMENT '总金额',
`delivery_address` varchar(50) DEFAULT NULL COMMENT '送货地址',
`order_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '下单时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
- 在订单表里插入记录
INSERT INTO `t_order` VALUES ('1', '郑晓红', '13956567889', '2000', '泸职院信息工程系', '2016-12-25 17:12:36');
INSERT INTO `t_order` VALUES ('2', '温志军', '13956678907', '1000', '泸职院机械工程系', '2016-12-02 17:12:17');
(二)创建Maven项目 - SSMSimonShop
(三)在pom.xml文件里添加相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.hw.shop</groupId>
<artifactId>SSMSimonShop</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<!-- spring.version -->
<spring.version>5.2.9.RELEASE</spring.version>
</properties>
<dependencies>
<!--Spring核心-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring Bean-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring容器-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring数据库支持-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--数据库驱动工具包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--数据库连接池框架-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.24</version>
</dependency>
<!--持久层框架-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--提供MyBatis与Spring整合的支持-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!--日志框架-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--Spring AOP-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!--AspectJ支持-->
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
<scope>runtime</scope>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!--Spring Web-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--JSP标准标签库-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
(四)创建日志属性文件 - log4j.properties
log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
(五)创建数据库配置属性文件 - jdbc.properties
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/simonshop?useSSL=false
jdbc.username = root
jdbc.password = root
- 说明:jdbc.url有时可能还需设置编码和时区
(六)给项目添加Web功能
- 打开项目结构窗口,按照演示进行操作
(七)配置Tomcat服务器
- 单击工具栏上的【Add Configuration…】,按照演示进行操作
(八)创建实体类
1、创建用户实体类 - User
- 创建net.hw.shop.bean包,在包里创建User类
package net.hw.shop.bean;
import java.util.Date;
/**
* 功能:用户实体类
* 作者:华卫
* 日期:2020年10月02日
*/
public class User {
private int id;
private String username;
private String password;
private String telephone;
private Date registerTime;
private int popedom;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
public int getPopedom() {
return popedom;
}
public void setPopedom(int popedom) {
this.popedom = popedom;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", telephone='" + telephone + '\'' +
", registerTime=" + registerTime +
", popedom=" + popedom +
'}';
}
}
2、创建类别实体类 - Category
- 在net.hw.shop.bean包里创建Category类
package net.hw.shop.bean;
/**
* 功能:类别实体类
* 作者:华卫
* 日期:2020年10月02日
*/
public class Category {
private int id;
private String name;
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;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
3、创建商品实体类 - Product
- 在net.hw.shop.bean包里创建Product类
package net.hw.shop.bean;
import java.util.Date;
/**
* 功能:商品实体类
* 作者:华卫
* 日期:2020年10月02日
*/
public class Product {
private int id;
private String name;
private double price;
private Date addTime;
private int categoryId;
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 Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", addTime=" + addTime +
", categoryId=" + categoryId +
'}';
}
}
4、创建订单实体类 - Order
- 在net.hw.shop.bean包里创建Order类
package net.hw.shop.bean;
import java.util.Date;
/**
* 功能:订单实体类
* 作者:华卫
* 日期:2020年10月02日
*/
public class Order {
private int id;
private String username;
private String telephone;
private double totalPrice;
private String deliveryAddress;
private Date orderTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
public String getDeliveryAddress() {
return deliveryAddress;
}
public void setDeliveryAddress(String deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
public Date getOrderTime() {
return orderTime;
}
public void setOrderTime(Date orderTime) {
this.orderTime = orderTime;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", username='" + username + '\'' +
", telephone='" + telephone + '\'' +
", totalPrice=" + totalPrice +
", deliveryAddress='" + deliveryAddress + '\'' +
", orderTime=" + orderTime +
'}';
}
}
(九)创建映射器接口
1、创建用户映射器接口 - UserMapper
- 创建net.hw.shop.mapper包,在包里创建UserMapper接口
package net.hw.shop.mapper;
import net.hw.shop.bean.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 功能:用户映射器接口
* 作者:华卫
* 日期:2020年10月02日
*/
@Repository
public interface UserMapper {
// 插入用户
int insert(User user);
// 按标识符删除用户
int deleteById(int id);
// 更新用户
int update(User user);
// 按标识符查询用户
User findById(int id);
// 按用户名查询用户
List<User> findByUsername(String username);
// 查询全部用户
List<User> findAll();
// 用户登录
User login(@Param("username") String username, @Param("password") String password);
}
2、创建类别映射器接口 - CategoryMapper
- 在net.hw.shop.mapper包里创建CategoryMapper接口
package net.hw.shop.mapper;
import net.hw.shop.bean.Category;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 功能:类别映射器接口
* 作者:华卫
* 日期:2020年10月02日
*/
@Repository
public interface CategoryMapper {
// 插入类别
int insert(Category category);
// 按标识符删除类别
int deleteById(int id);
// 更新类别
int update(Category category);
// 按标识符查询类别
Category findById(int id);
// 查询全部类别
List<Category> findAll();
}
3、创建商品映射器接口 - ProductMapper
- 在net.hw.shop.mapper包里创建ProductMapper接口
package net.hw.shop.mapper;
import net.hw.shop.bean.Product;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 功能:商品映射器接口
* 作者:华卫
* 日期:2020年10月02日
*/
@Repository
public interface ProductMapper {
// 插入商品
int insert(Product product);
// 按标识符删除商品
int deleteById(int id);
// 更新商品
int update(Product product);
// 按标识符查询商品
Product findById(int id);
// 按类别查询商品
List<Product> findByCategoryId(int categoryId);
// 查询全部商品
List<Product> findAll();
}
4、创建订单映射器接口 - OrderMapper
- 在net.hw.shop.mapper包里创建OrderMapper接口
package net.hw.shop.mapper;
import net.hw.shop.bean.Order;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 功能:订单映射器接口
* 作者:华卫
* 日期:2020年10月02日
*/
@Repository
public interface OrderMapper {
// 插入订单
int insert(Order order);
// 按标识符删除订单
int deleteById(int id);
// 更新订单
int update(Order order);
// 按标识符查询订单
Order findById(int id);
// 查询全部订单
List<Order> findAll();
}
(十)创建服务类
1、创建用户服务类 - UserService
- 在net.hw.shop包里创建service子包,然后在子包里创建UserService类
package net.hw.shop.service;
import net.hw.shop.bean.User;
import net.hw.shop.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 功能:用户服务类
* 作者:华卫
* 日期:2020年10月02日
*/
@Service
@Transactional
public class UserService {
@Autowired
private UserMapper userMapper;
public int addUser(User user) {
// 避免注册相同用户名
if (findUsersByUsername(user.getUsername()).size() == 0) {
return userMapper.insert(user);
} else {
return 0;
}
}
public int deleteUserById(int id) {
return userMapper.deleteById(id);
}
public int updateUser(User user) {
return userMapper.update(user);
}
public User findUserById(int id) {
return userMapper.findById(id);
}
public List<User> findUsersByUsername(String username) {
return userMapper.findByUsername(username);
}
public List<User> findAllUsers() {
return userMapper.findAll();
}
public User login(String username, String password) {
return userMapper.login(username, password);
}
}
2、创建类别服务类 - CategoryService
- 在net.hw.shop.service包里创建CategoryService类
package net.hw.shop.service;
import net.hw.shop.bean.Category;
import net.hw.shop.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 功能:
* 作者:华卫
* 日期:2020年10月02日
*/
@Service
@Transactional
public class CategoryService {
@Autowired
private CategoryMapper categoryMapper;
public int addCategory(Category category) {
return categoryMapper.insert(category);
}
public int deleteCategoryById(int id) {
return categoryMapper.deleteById(id);
}
public int updateCategory(Category category) {
return categoryMapper.update(category);
}
public Category findCategoryById(int id) {
return categoryMapper.findById(id);
}
public List<Category> findAllCategories() {
return categoryMapper.findAll();
}
}
3、创建商品服务类 - ProductService
- 在net.hw.shop.service包里创建ProductService类
package net.hw.shop.service;
import net.hw.shop.bean.Product;
import net.hw.shop.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 功能:商品服务类
* 作者:华卫
* 日期:2020年10月02日
*/
@Service
@Transactional
public class ProductService {
@Autowired
private ProductMapper productMapper;
public int addProduct(Product product) {
return productMapper.insert(product);
}
public int deleteProductById(int id) {
return productMapper.deleteById(id);
}
public int updateProduct(Product product) {
return productMapper.update(product);
}
public Product findProductById(int id) {
return productMapper.findById(id);
}
public List<Product> findProductsByCategoryId(int categoryId) {
return productMapper.findByCategoryId(categoryId);
}
public List<Product> findAllProducts() {
return productMapper.findAll();
}
}
4、创建订单服务类 - OrderService
- 在net.hw.shop.service包里创建OrderService类
package net.hw.shop.service;
import net.hw.shop.bean.Order;
import net.hw.shop.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 功能:订单服务类
* 作者:华卫
* 日期:2020年10月02日
*/
@Service
@Transactional
public class OrderService {
@Autowired
private OrderMapper orderMapper;
public int addOrder(Order order) {
return orderMapper.insert(order);
}
public int deleteOrderById(int id) {
return orderMapper.deleteById(id);
}
public int updateOrder(Order order) {
return orderMapper.update(order);
}
public Order findOrderById(int id) {
return orderMapper.findById(id);
}
public List<Order> findAllOrders() {
return orderMapper.findAll();
}
}
(十一)创建控制器
1、创建用户控制器 - UserController
- 在net.hw.shop包里创建webmvc子包,然后在子包里创建UserController类
package net.hw.shop.webmvc;
import net.hw.shop.bean.Category;
import net.hw.shop.bean.User;
import net.hw.shop.service.CategoryService;
import net.hw.shop.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.List;
/**
* 功能:用户控制器
* 作者:华卫
* 日期:2020年10月02日
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@Resource
private CategoryService categoryService;
@RequestMapping("/login")
public String login(@RequestParam("username")String username,
@RequestParam("password") String password,
HttpSession session) {
// 调用用户服务对象的登录方法
User user = userService.login(username, password);
// 判断是否登录成功
if (user != null) {
session.setAttribute("username", username);
session.removeAttribute("loginMsg");
// 判断用户的角色
if (user.getPopedom() == 0) {
// 映射到后台管理页面
return "backend/management";
} else {
List<Category> categories = categoryService.findAllCategories();
session.setAttribute("categories", categories);
// 映射到前台显示商品类别页面
return "frontend/showCategory";
}
} else {
session.setAttribute("loginMsg", "用户名或密码错误!");
return "frontend/login";
}
}
@RequestMapping("/register")
public String register(@RequestParam("username")String username,
@RequestParam("password") String password,
@RequestParam("telephone") String telephone,
HttpSession session) {
// 设置注册时间(时间戳对象)
Timestamp registerTime = new Timestamp(System.currentTimeMillis());
// 设置用户为普通用户
int popedom = 1;
// 创建用户对象
User user = new User();
// 设置用户对象信息
user.setUsername(username);
user.setPassword(password);
user.setTelephone(telephone);
user.setRegisterTime(registerTime);
user.setPopedom(popedom);
// 调用UserService对象添加用户方法
int count = userService.addUser(user);
// 判断是否注册成功
if (count > 0) {
session.setAttribute("registerMsg", "恭喜,注册成功!");
// 映射到登录页面
return "frontend/login";
} else {
session.setAttribute("registerMsg", "遗憾,注册失败!");
// 映射到前台注册页面
return "frontend/register";
}
}
@RequestMapping("/showUser")
public String showUser(HttpSession session) {
List<User> users = userService.findAllUsers();
session.setAttribute("users", users);
// 映射到后台显示用户页面
return "backend/showUser";
}
@RequestMapping("/logout")
public String logout(HttpSession session) {
// 删除会话属性
session.removeAttribute("username");
// 结束会话
session.invalidate();
// 映射到前台登录页面
return "frontend/login";
}
}
2、创建类别控制器 - CategoryController
- 在net.hw.shop.webmvc包里创建CategoryController
package net.hw.shop.webmvc;
import net.hw.shop.bean.Category;
import net.hw.shop.service.CategoryService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
* 功能:类别控制器
* 作者:华卫
* 日期:2020年10月02日
*/
@Controller
@RequestMapping("/category")
public class CategoryController {
@Resource
private CategoryService categoryService;
@RequestMapping("/showCategory")
public String showCategory(HttpSession session) {
List<Category> categories = categoryService.findAllCategories();
session.setAttribute("categories", categories);
return "frontend/showCategory";
}
}
3、创建商品控制器 - ProductController
- 在net.hw.shop.webmvc包里创建ProductControllerl类
package net.hw.shop.webmvc;
import net.hw.shop.bean.Product;
import net.hw.shop.service.CategoryService;
import net.hw.shop.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
/**
* 功能:商品控制器
* 作者:华卫
* 日期:2020年10月02日
*/
@Controller
@RequestMapping("/product")
public class ProductController {
@Resource
private ProductService productService;
@Resource
private CategoryService categoryService;
@RequestMapping("/showProduct")
public String showProduct(@RequestParam("categoryId") int categoryId,
HttpSession session) {
List<Product> products = productService.findProductsByCategoryId(categoryId);
String categoryName = categoryService.findCategoryById(categoryId).getName();
if (products.size() > 0) {
session.setAttribute("categoryName", categoryName);
session.setAttribute("products", products);
return "frontend/showProduct";
} else {
return "frontend/showCategory";
}
}
@RequestMapping("/operateCart")
public String operateCart(
@RequestParam("operation") String operation,
@RequestParam("id") int id,
HttpSession session) {
// 从session里获取购物车(键:商品标识符;值:购买数量)
LinkedHashMap<Integer, Integer> cart = (LinkedHashMap<Integer, Integer>) session.getAttribute("cart");
// 判断购物车是否为空
if (cart == null) {
// 创建购物车
cart = new LinkedHashMap<Integer, Integer>();
// 将购物车保存到session里,便于用户在不同页面访问购物车
session.setAttribute("cart", cart);
}
if (operation.equals("add")) {
// 将商品添加到购物车
if (cart.containsKey(id)) { // 该商品已购买过
// 购买数量增加1
cart.put(id, cart.get(id) + 1);
} else { // 该商品未曾购买
// 购买数量设置为1
cart.put(id, 1);
}
} else if (operation.equals("delete")) {
// 将商品从购物车删除
if (cart.get(id) > 1) {
// 购买数量减少1
cart.put(id, cart.get(id) - 1);
} else {
// 从购物车里删除该商品
cart.remove(id);
}
}
// 获取该商品的类别标识符
int categoryId = productService.findProductById(id).getCategoryId();
// 判断购物车是否为空
if (cart != null) {
// 定义购物表
List<HashMap<String, Object>> shoppingTable = new ArrayList<HashMap<String, Object>>();
// 购物总金额
double totalPrice = 0.0;
// 遍历购物车
for (Integer p_id : cart.keySet()) {
// 获取商品对象
Product product = productService.findProductById(p_id);
// 生成购物表记录
HashMap<String, Object> shoppingItem = new HashMap<String, Object>();
shoppingItem.put("id", product.getId());
shoppingItem.put("name", product.getName());
shoppingItem.put("price", product.getPrice());
shoppingItem.put("amount", cart.get(p_id));
shoppingItem.put("sum", product.getPrice() * cart.get(p_id));
// 将购物表记录添加到购物表中
shoppingTable.add(shoppingItem);
// 累加购买总金额
totalPrice = totalPrice + (Double) shoppingItem.get("sum");
}
// 将购物表和购买总金额保存到session里
session.setAttribute("shoppingTable", shoppingTable);
session.setAttribute("totalPrice", totalPrice);
}
List<Product> products = productService.findProductsByCategoryId(categoryId);
String categoryName = categoryService.findCategoryById(categoryId).getName();
session.setAttribute("categoryId", categoryId);
session.setAttribute("categoryName", categoryName);
session.setAttribute("products", products);
return "frontend/showProduct";
}
}
4、创建订单控制器 - OrderController
- 在net.hw.shop.webmvc包里创建OrderController类
package net.hw.shop.webmvc;
import net.hw.shop.bean.Order;
import net.hw.shop.service.OrderService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
/**
* 功能:订单控制器
* 作者:华卫
* 日期:2020年10月02日
*/
@Controller
@RequestMapping("/order")
public class OrderController {
@Resource
private OrderService orderService;
@RequestMapping("/makeOrder")
public String makeOrder(@RequestParam("username") String username,
@RequestParam("telephone") String telephone,
@RequestParam("totalPrice") double totalPrice,
@RequestParam("deliveryAddress") String deliveryAddress,
HttpSession session) {
Order order = new Order();
order.setUsername(username);
order.setTelephone(telephone);
order.setTotalPrice(totalPrice);
order.setDeliveryAddress(deliveryAddress);
order.setOrderTime(new Date());
int count = orderService.addOrder(order);
if (count > 0) {
List<Order> orders = orderService.findAllOrders();
Order lastOrder = orders.get(orders.size()-1);
session.setAttribute("lastOrder", lastOrder);
return "frontend/showOrder";
} else {
return "frontend/showCategory";
}
}
@RequestMapping("pay")
public String pay(HttpSession session) {
session.removeAttribute("cart");
session.removeAttribute("shoppingTable");
session.removeAttribute("totalPrice");
return "frontend/showCategory";
}
@RequestMapping("/toMakeOrder")
public String toMakeOrder(@RequestParam("totalPrice") double totalPrice,
HttpSession session) {
if (totalPrice == 0.00) {
session.setAttribute("orderMsg", "您还未购物呢!请您选购商品!");
return "frontend/showProduct";
} else {
return "frontend/makeOrder";
}
}
}
(十二)创建映射器配置文件
1、创建用户映射器配置文件 - UserMapper.xml
- 在resources里创建mapper子目录,然后在子目录里创建UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.hw.shop.mapper.UserMapper">
<resultMap id="userMap" type="net.hw.shop.bean.User">
<result property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="telephone" column="telephone"/>
<result property="registerTime" javaType="java.util.Date" column="register_time" jdbcType="TIMESTAMP"/>
<result property="popedom" column="popedom"/>
</resultMap>
<insert id="insert" parameterType="net.hw.shop.bean.User" keyProperty="id" useGeneratedKeys="true">
INSERT INTO t_user (username, password, telephone, register_time, popedom)
VALUES (#{username}, #{password}, #{telephone}, #{registerTime}, #{popedom});
</insert>
<update id="update" parameterType="net.hw.shop.bean.User">
UPDATE t_user SET username = #{username}, password = #{password},
telephone = #{telephone}, register_time = #{registerTime}, popedom = #{popedom}
WHERE id = #{id};
</update>
<delete id="deleteById" parameterType="int">
DELETE from t_user WHERE id = #{id};
</delete>
<select id="findAll" resultMap="userMap">
SELECT * FROM t_user;
</select>
<select id="findById" parameterType="int" resultMap="userMap">
SELECT * FROM t_user WHERE id = #{id};
</select>
<select id="findByUsername" parameterType="string" resultMap="userMap">
SELECT * FROM t_user WHERE username LIKE CONCAT(#{username},'%')
</select>
<select id="login" resultMap="userMap">
SELECT * FROM t_user WHERE username = #{username} AND password = #{password};
</select>
</mapper>
2、创建类别映射器配置文件 - CategoryMapper.xml
- 在resources/mapper目录里创建CategoryMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.hw.shop.mapper.CategoryMapper">
<select id="findById" parameterType="int" resultType="net.hw.shop.bean.Category">
SELECT * FROM t_category WHERE id = #{id}
</select>
<select id="findAll" resultType="net.hw.shop.bean.Category">
SELECT * FROM t_category;
</select>
<insert id="insert" parameterType="net.hw.shop.bean.Category" keyProperty="id" useGeneratedKeys="true">
INSERT INTO t_user (name) VALUES (#{name});
</insert>
<update id="update" parameterType="net.hw.shop.bean.Category">
UPDATE t_category SET name = #{name} WHERE id = #{id};
</update>
<delete id="deleteById" parameterType="int">
DELETE from t_category WHERE id = #{id};
</delete>
</mapper>
3、创建商品映射器配置文件 - ProductMapper.xml
- 在resources/mapper目录里创建ProductMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.hw.shop.mapper.ProductMapper">
<resultMap id="productMap" type="net.hw.shop.bean.Product">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="price" column="price"/>
<result property="addTime" column="add_time"/>
<result property="categoryId" column="category_id"/>
</resultMap>
<select id="findAll" resultMap="productMap">
SELECT * FROM t_product;
</select>
<select id="findByCategoryId" parameterType="int" resultMap="productMap">
SELECT * FROM t_product WHERE category_id = #{categoryId};
</select>
<select id="findById" parameterType="int" resultMap="productMap">
SELECT * FROM t_product WHERE id = #{id};
</select>
<insert id="insert" parameterType="net.hw.shop.bean.Product" keyProperty="id" useGeneratedKeys="true">
INSERT INTO t_product (name, price, add_time, category_id)
VALUES (#{name}, #{price}, #{addTime}, #{categoryId});
</insert>
<update id="update" parameterType="net.hw.shop.bean.Product">
UPDATE t_product SET name = #{name}, price = #{price},
add_time = #{addTime}, category_id = #{categoryId} WHERE id = #{id};
</update>
<delete id="deleteById" parameterType="int">
DELETE from t_product WHERE id = #{id};
</delete>
</mapper>
4、创建订单映射器配置文件 - OrderMapper.xml
- 在resources/mapper目录里创建OrderMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.hw.shop.mapper.OrderMapper">
<resultMap id="orderMap" type="net.hw.shop.bean.Order">
<result property="id" column="id"/>
<result property="username" column="username"/>
<result property="telephone" column="telephone"/>
<result property="totalPrice" column="total_price"/>
<result property="deliveryAddress" column="delivery_address"/>
<result property="orderTime" column="order_time"/>
</resultMap>
<select id="findAll" resultMap="orderMap">
SELECT * FROM t_order;
</select>
<select id="findById" parameterType="int" resultMap="orderMap">
SELECT * FROM t_order WHERE id = #{id};
</select>
<insert id="insert" parameterType="net.hw.shop.bean.Order" keyProperty="id" useGeneratedKeys="true">
INSERT INTO t_order (username, telephone, total_price, delivery_address, order_time)
VALUES (#{username}, #{telephone}, #{totalPrice}, #{deliveryAddress}, #{orderTime});
</insert>
<update id="update" parameterType="net.hw.shop.bean.Order">
UPDATE t_order SET username = #{username}, telephone = #{telephone},
total_price = #{totalPrice}, delivery_address = #{deliveryAddress},
order_time = #{orderTime} WHERE id = #{id};
</update>
<delete id="deleteById" parameterType="int">
DELETE from t_order WHERE id = #{id};
</delete>
</mapper>
(十三)创建Spring配置文件 - spring-config.xml
- 在resources里创建config子目录,然后在子目录里创建spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--组件扫描-->
<context:component-scan base-package="net.hw.shop"/>
<!--读取jdbc属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 定义数据源Bean,使用阿里开源Druid数据源实现 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="10"/>
<property name="minIdle" value="10"/>
<property name="maxActive" value="200"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="6000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
<property name="validationQuery" value="SELECT 'x'"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="false"/>
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="100"/>
<!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
<property name="filters" value="stat"/>
</bean>
<!--定义MyBatis的SqlSessionFactory-->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--使用MapperScannerConfigurer查找类路径下映射器并自动将其实例化为MapperFactoryBean-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="net.hw.shop.mapper" />
</bean>
<!--定义事务管理器-->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 -->
<tx:annotation-driven transaction-manager="txManager" />
<!--定义事务管理通知-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--声明式事务通知器,需要在pom.xml里添加基于AspectJ的AOP支持-->
<aop:config>
<aop:pointcut id="mypt" expression="execution(public * net.hw.shop.service..*.*(..))"/>
<:advisor advice-ref="txAdvice" pointcut-ref="mypt"/>
</aop:config>
</beans>
(十四)创建Spring MVC配置文件 - spring-mvc-config.xml
- 在resources/config目录里创建spring-mvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--处理对静态资源的请求-->
<mvc:resources mapping="/css/**" location="/WEB-INF/css/"/>
<mvc:resources mapping="/scripts/**" location="/WEB-INF/scripts/"/>
<mvc:resources mapping="/images/**" location="/WEB-INF/images/"/>
<!--采用注解驱动-->
<mvc:annotation-driven/>
<!--定义视图控制器-->
<mvc:view-controller path="toLeft" view-name="backend/left" />
<mvc:view-controller path="toTop" view-name="backend/top" />
<mvc:view-controller path="toMain" view-name="backend/main" />
<mvc:view-controller path="todo" view-name="backend/todo" />
<mvc:view-controller path="user/toRegister" view-name="frontend/register" />
<mvc:view-controller path="user/toLogin" view-name="frontend/login" />
<!--扫描添加Controller注解的类-->
<context:component-scan base-package="net.hw.shop.webmvc"/>
<!--定义内部资源视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/views/"
p:suffix=".jsp"/>
<!-- 扫描业务组件,让spring不扫描带有@Service注解的类(留在spring-config.xml中扫描@Service注解的类),防止事务失效 -->
<context:component-scan base-package="net.hw.shop">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
</beans>
(十五)编辑Web部署描述文件 - web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>simonshop</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/views/frontend/login.jsp</welcome-file>
</welcome-file-list>
<!--Spring监听器,让Spring随Web项目启动而初始化-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定Spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-config.xml</param-value>
</context-param>
<!--配置Spring前端控制器,通过初始化参数设置读取控制器配置文件-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--设置字符编码过滤器-->
<filter>
<filter-name>Character Encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
(十六)准备图片资源
-
案例所用图片资源
-
在WEB-INF里创建images目录,用来存放图片资源
(十七)创建样式文件 - main.css
- 在WEB-INF里创建css子目录,然后在子目录里创建main.css
/* 样式 */
body {
margin:0px;
text-align:center;
background:url("../images/frontBack.jpg") no-repeat;
background-size:100%
}
table {
margin: 0 auto;
font-size:14px;
color:#333333;
border-width: 1px;
border-color: khaki;
border-collapse: collapse;
}
table th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: gainsboro;
background-color: honeydew;
}
table td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: gainsboro;
background-color: #ffffff;
}
/*登录页面样式*/
.login {
width:400px;
height: 340px;
background-color: honeydew;
border: solid 2px darkgrey;
left:50%;
top: 50%;
position: absolute;
margin: -170px 0 0 -200px;
}
.login .websiteTitle, .title {
border: solid 1px floralwhite;
}
/*注册页面样式*/
.register {
width:400px;
height: 350px;
background-color: honeydew;
border: solid 2px darkgrey;
left:50%;
top: 50%;
position: absolute;
margin: -175px 0 0 -200px;
}
/*显示类别页面样式*/
.showCategory {
width:400px;
height: 350px;
background-color: honeydew;
border: solid 2px darkgrey;
left:50%;
top: 50%;
position: absolute;
margin: -150px 0 0 -200px;
}
/*生成订单页面样式*/
.makeOrder {
width:400px;
height: 400px;
background-color: honeydew;
border: solid 2px darkgrey;
left:50%;
top: 50%;
position: absolute;
margin: -200px 0 0 -200px;
}
/*显示订单页面样式*/
.showOrder {
width:400px;
height: 400px;
background-color: honeydew;
border: solid 2px darkgrey;
left:50%;
top: 50%;
position: absolute;
margin: -200px 0 0 -200px;
}
(十八)创建脚本文件 - check.js
- 在WEB-INF里创建scripts子目录,然后在子目录里创建check.js
/**
* 检验登录表单
*
* @returns {Boolean}
*/
function checkLoginForm() {
// 获取用户名文本框
var username = document.getElementById("username");
// 获取密码文本框
var password = document.getElementById("password");
// 非空校验
if (username.value == "") {
alert("用户名不能为空!");
// 让用户名文本框获得焦点
username.focus();
return false;
}
if (password.value == "") {
alert("密码不能为空!");
// 让密码文本框获得焦点
password.focus();
return false;
}
return true; // 表明可以提交数据到服务器端
}
/**
* 检验注册表单
* @returns {Boolean}
*/
function checkRegisterForm() {
// 获取用户名文本框
var username = document.getElementById("username");
// 获取密码文本框
var password = document.getElementById("password");
// 获取手机号码文本框
var telephone = document.getElementById("telephone");
// 非空校验
if (username.value == "") {
alert("用户名不能为空!");
// 让用户名文本框获得焦点
username.focus();
return false;
}
if (password.value == "") {
alert("密码不能为空!");
// 让密码文本框获得焦点
password.focus();
return false;
}
// 检验手机号码
var patrn = "/^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\d{8}$/";
if (!patrn.test(telephone)) {
alert("非法手机号!");
// 让手机号码文本框获得焦点
telephone.focus();
return false;
}
return true; // 表明可以提交数据到服务器端
}
(十九)创建页面
1、创建目录结构
- 在WEB-INF里创建views目录,然后在里面创建frontend和backend两个子目录
2、前台页面
(1)创建登录页面 - login.jsp
- 在views/frontend里创建login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>用户登录</title>
<base href="${basePath}">
<script src="scripts/check.js" type="text/javascript"></script>
<link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="login">
<div class="websiteTitle">
<h1>西蒙购物网</h1>
</div>
<div class="title">
<h3>用户登录</h3>
</div>
<div class="main">
<form id="frmLogin" action="user/login" method="post">
<table>
<tr>
<td align="center">账号</td>
<td><input id="username" type="text" name="username"/></td>
</tr>
<tr>
<td align="center">密码</td>
<td><input id="password" type="password" name="password"/></td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" value="登录" onclick="return checkLoginForm();"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
</div>
<div class="footer">
<p>如果你不是本站用户,单击<a href="user/toRegister">此处</a>注册。</p>
</div>
</div>
<c:if test="${registerMsg!=null}">
<script type="text/javascript">alert("${registerMsg}")</script>
<c:remove var="registerMsg"/>
</c:if>
<c:if test="${loginMsg!=null}">
<script type="text/javascript">alert("${loginMsg}")</script>
<c:remove var="loginMsg"/>
</c:if>
</body>
</html>
(2)创建注册页面 - register.jsp
- 在views/frontend里创建register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>用户注册</title>
<base href="${basePath}">
<link href="css/main.css" rel="stylesheet" type="text/css"/>
<script src="scripts/check.js" type="text/javascript"></script>
</head>
<body>
<div class="register">
<div class="websiteTitle">
<h1>西蒙购物网</h1>
</div>
<div class="title">
<h3>用户注册</h3>
</div>
<div class="main">
<form action="user/register" method="post">
<table>
<tr>
<td>账号</td>
<td><input id="username" type="text" name="username"/></td>
</tr>
<tr>
<td>密码</td>
<td><input id="password" type="password" name="password"/></td>
</tr>
<tr>
<td align="center">电话</td>
<td><input id="telephone" type="text" name="telephone"/></td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" value="注册" onclick="return checkRegisterForm();"/>
<input type="reset" value="重置"/></td>
</tr>
</table>
</form>
</div>
<div class="footer">
<p><a href="user/toLogin">切换到登录页面</a></p>
</div>
</div>
<c:if test="${registerMsg!=null}">
<script type="text/javascript">alert("${registerMsg}")</script>
<c:set var="registerMsg" value=""/>
</c:if>
</body>
</html>
(3)创建显示类别页面 - showCategory.jsp
- 在views/frontend里创建showCategory.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>显示商品类别</title>
<base href="${basePath}">
<link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="showCategory">
<div class="websiteTitle">
<h1>西蒙购物网</h1>
</div>
<div>
登录用户:<span style="color: red;">${username}</span>
<c:forEach var="i" begin="1" end="5">
</c:forEach>
<a href="user/logout">注销</a>
</div>
<div class="title">
<h3>商品类别</h3>
</div>
<div class="main">
<table>
<tr>
<th>类别编号</th>
<th>商品类别</th>
</tr>
<c:forEach var="category" items="${categories}">
<tr align='center'>
<td>${category.id}</td>
<td width="150">
<a href="product/showProduct?categoryId=${category.id}">${category.name}</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
</body>
</html>
(4)创建显示商品页面 - showProduct.jsp
- 在views/frontend里创建showProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>显示商品信息</title>
<base href="${basePath}">
<link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>西蒙购物网</h1>
<hr width="700px">
登录用户:<span style="color: red;">${username}</span>
<c:forEach var="i" begin="1" end="5">
</c:forEach>
<a href="user/logout">注销</a></td>
<hr width="700px">
欢迎选购【<span style="color: blue; font-weight: bold;">${categoryName}</span>】类商品
<hr width="700px">
<table border="0">
<c:forEach varStatus="status" var="product" items="${products}">
<c:if test="${status.count%5==0}">
<tr>
</c:if>
<td>
<table border="0">
<tr><img src="images/product${product.id}.jpg" width="60px" height="60px"></tr>
<tr>
<td><b>商品编号:</b></td>
<td>${product.id}</td>
</tr>
<tr>
<td><b>商品名称:</b></td>
<td>${product.name}</td>
</tr>
<tr>
<td><b>销售价格:</b></td>
<td>${product.price}</td>
</tr>
<tr>
<td><b>上架时间:</b></td>
<td><fmt:formatDate value="${product.addTime}" pattern="yyyy-MM-dd"/></td>
</tr>
<tr>
<td><b>用户操作:</b></td>
<td><a href="product/operateCart?id=${product.id}&operation=add">加入购物车</a></td>
</tr>
</table>
</td>
<c:if test="${status.count%4==0}">
</tr>
</c:if>
</c:forEach>
</table>
<hr width="700px">
<a href="category/showCategory">返回商品类别页面</a>
<hr width="700px">
<jsp:include page="showCart.jsp"/>
</body>
</html>
(5)创建显示购物车页面 - showCart.jsp
- 在views/frontend里创建showCart.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>显示购物车</title>
<base href="${basePath}">
</head>
<body>
<h3>${username}的购物车</h3>
<table>
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>销售价格</th>
<th>购买数量</th>
<th>合计金额</th>
<th>用户操作</th>
</tr>
<c:forEach var="shoppingItem" items="${shoppingTable}">
<tr>
<td>${shoppingItem.id}</td>
<td>${shoppingItem.name}</td>
<td>¥${shoppingItem.price}</td>
<td>${shoppingItem.amount}</td>
<td>¥${shoppingItem.sum}</td>
<td><a href="product/operateCart?id=${shoppingItem.id}&operation=delete">删除</a></td>
</tr>
</c:forEach>
<tr>
<th>总金额</th>
<td></td>
<td></td>
<td></td>
<c:choose>
<c:when test="${totalPrice==null}">
<th style="color: red">¥0.00</th>
</c:when>
<c:otherwise>
<th style="color: red">¥${totalPrice}</th>
</c:otherwise>
</c:choose>
<td></td>
</tr>
</table>
<hr width="800px">
<c:choose>
<c:when test="${totalPrice==null}">
<a href="order/toMakeOrder?totalPrice=0.00">生成订单</a>
</c:when>
<c:otherwise>
<a href="order/toMakeOrder?totalPrice=${totalPrice}">生成订单</a>
</c:otherwise>
</c:choose>
<c:if test="${orderMsg!=null}">
<script type="text/javascript">alert("${orderMsg}")</script>
<c:remove var="orderMsg"/>
</c:if>
</body>
</html>
(6)创建生成订单页面 - makeOrder.jsp
- 在views/frontend里创建makeOrder.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>生成订单</title>
<base href="${basePath}">
<link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="makeOrder">
<div class="websiteTitle">
<h1>西蒙购物网</h1>
</div>
<div>
登录用户:<span style="color: red;">${username}</span>
<c:forEach var="i" begin="1" end="5">
</c:forEach>
<a href="user/logout">注销</a>
</div>
<div class="title">
<h3>生成订单</h3>
</div>
<div class="main">
<form action="order/makeOrder" method="post">
<table>
<tr>
<td>用户名</td>
<td><input type="text" name="username" readonly="readonly"
value="${username}"/></td>
</tr>
<tr>
<td>联系电话</td>
<td><input type="text" name="telephone"/></td>
</tr>
<tr>
<td>总金额</td>
<td><input type="text" name="totalPrice" readonly="readonly"
value="${totalPrice}"/></td>
</tr>
<tr>
<td>送货地址</td>
<td><input type="text" name="deliveryAddress"/></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="生成订单"/> <input
type="reset" value="重置"/></td>
</tr>
</table>
</form>
</div>
<div class="footer">
<p><a href="category/showCategory">返回商品类别页面</a></p>
</div>
</div>
</body>
</html>
(7)创建显示订单页面 - showOrder.jsp
- 在views/frontend里创建showOrder.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>显示订单</title>
<base href="${basePath}">
<link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="showOrder">
<div class="websiteTitle">
<h1>西蒙购物网</h1>
</div>
<div>
登录用户:<span style="color: red;">${username}</span>
<c:forEach var="i" begin="1" end="5">
</c:forEach>
<a href="user/logout">注销</a>
</div>
<div class="title">
<h3>生成订单</h3>
</div>
<div class="main">
<table border="1" cellspacing="0">
<tr>
<th>订单编号</th>
<td>${lastOrder.id}</td>
</tr>
<tr>
<th>用户名</th>
<td>${lastOrder.username}</td>
</tr>
<tr>
<th>联系电话</th>
<td>${lastOrder.telephone}</td>
</tr>
<tr>
<th>总金额</th>
<td>${lastOrder.totalPrice}</td>
</tr>
<tr>
<th>送货地址</th>
<td>${lastOrder.deliveryAddress}</td>
</tr>
</table>
</div>
<div class="footer">
<p><a href="order/pay" onclick="alert('${lastOrder.username},支付成功!')">支付</a></p>
</div>
</div>
</body>
</html>
3、后台页面
(1)创建后台管理主页面 - management.jsp
- 在views/backend里创建management.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>西蒙购物网站后台管理</title>
<base href="${basePath}">
</head>
<frameset rows="30%,70%" cols="*">
<frame src="toTop" name="top_frame" scrolling="no">
<frameset rows="*" cols="25%,75%">
<frame src="toLeft" name="left_frame" scrolling="yes">
<frame src="toMain" name="main_frame" scrolling="yes">
</frameset>
</frameset>
</html>
(2)创建后台管理主页面左面板 - left.jsp
- 在views/backend里创建left.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>后台管理左面板</title>
<base href="${basePath}">
<link rel="stylesheet" type="text/css">
<script type="text/javascript">
function show(id) {
var obj = document.getElementById('c_' + id);
if (obj.style.display == 'block') {
obj.style.display = 'none';
} else {
obj.style.display = 'block';
}
}
</script>
</head>
<body>
<table cellSpacing=0 cellPadding=0 width='100%' border=0>
<tbody>
<tr>
<td class=catemenu> <a
style='CURSOR: pointer' onclick=show(1)><img src="images/folder.png">用户管理</a>
</td>
</tr>
<tbody id=c_1>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a
href="user/showUser" target="main_frame">查看用户</a></td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">添加用户</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">更新用户</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">删除用户</a>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class=catemenu> <a
style='CURSOR: pointer' onclick=show(2)><img src="images/folder.png">
类别管理</a></td>
</tr>
<tbody id=c_2 style='DISPLAY: none'>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">查看类别</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">添加类别</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">更新类别</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">删除类别</a>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class=catemenu> <a
style='CURSOR: pointer' onclick=show(3)><img src="images/folder.png">
商品管理</a></td>
</tr>
<tbody id=c_3 style='DISPLAY: none'>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">查看商品</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">添加商品</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">更新商品</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">删除商品</a>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class=catemenu> <a
style='CURSOR: pointer' onclick=show(4)><img src="images/folder.png">
订单管理</a></td>
</tr>
<tbody id=c_4 style='DISPLAY: none'>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">查看订单</a>
</td>
</tr>
<tr>
<td class=bar2 height=20> <img src="images/file.png"> <a href="todo" target="main_frame">删除订单</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
(3)创建后台管理主页面顶面板top.jsp
- 在views/backend里创建top.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>后台管理顶面板</title>
<base href="${basePath}">
</head>
<body style="margin:0px">
<img src="images/title.png" width="100%" height="100%">
</body>
</html>
(4)创建后台管理主页面主面板main.jsp
- 在views/backend里创建main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>后台管理主面板</title>
<base href="${basePath}">
</head>
<body>
<img src="images/mainBack.gif" width="100%" height="100%"/>
</body>
</html>
(5)创建查看用户页面showUser.jsp
- 在views/backend里创建showUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<!DOCTYPE html>
<html>
<head>
<title>显示用户信息</title>
<base href="${basePath}">
<link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<hr>
<table width="90%" border="0px">
<tr>
<td align="left">登录用户:<span style="color: red;">${username}</span></td>
<td align="right"><a href="user/logout" target="_parent">注销</a></td>
</tr>
</table>
<hr>
<h3>用户列表</h3>
<hr>
<table border="1" width="90%" cellspacing="0">
<tr>
<th>编号</th>
<th>用户名</th>
<th>密码</th>
<th>电话</th>
<th>注册时间</th>
<th>权限</th>
</tr>
<c:forEach var="user" items="${users}">
<tr align="center">
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
<td>${user.telephone}</td>
<td><fmt:formatDate value="${user.registerTime}" pattern="yyyy-MM-dd hh:mm:ss"/></td>
<td>
<c:choose>
<c:when test="${user.popedom==0}">
管理员
</c:when>
<c:otherwise>
普通用户
</c:otherwise>
</c:choose>
</td>
</tr>
</c:forEach>
</table>
<hr>
</body>
</html>
(6)创建待做页面todo.jsp
- 在views/backend里创建todo.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>待做页面</title>
</head>
<body>
<h1 style="text-align: center">抱歉,页面正在维护中……</h1>
</body>
</html>
(二十)启动服务器,查看效果
(二十一)待完成功能
- 后台管理模块,只完成了查看用户功能,其余功能,等待有兴趣的同学自行完成。
五、利用Bootstrap框架改进网站界面
文章来源:https://blog.csdn.net/howard2005/article/details/135181993
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!