数据库端MySQL
drop database if exists mydb;
create database mydb;
use mydb;
create table `t_user` (
`uid` int(11) primary key not null AUTO_INCREMENT,
`username` varchar(20),
`password` varchar(20),
`birthday` varchar(20),
`sex` varchar(5),
`address` varchar(50)
);
-- ----------------------------
-- Records of tuser
-- ----------------------------
insert into `t_user` values (1, '张三','111','2022-05-03', '男', '北京');
insert into `t_user` values (2, '李四','222','2022-05-19', '男', '广州');
insert into `t_user` values (3, '小红','333','2022-05-19', '女', '郑州');
insert into `t_user` values (4, '小美','444','2022-05-20', '女', '郑州');
select * from t_user;
select*from t_user where username='张三' and password='111';
#判断删除
drop table if exists `goods`;
#创建商品信息表
create table `goods`
(
goodsId int primary key auto_increment,
goodsName varchar(20),
price double,
stock int,
supplier varchar(50)
);
insert into `goods` values(1,'泡面',3.5,50,'康师傅');
insert into `goods` values(2,'牛奶',5.5,60,'蒙牛');
insert into `goods` values(3,'瓜子',6.5,30,'金鸽');
select * from `goods`;
select*from goods where goodsId=1
update goods set goodsName='香肠',price=8.8,stock=9,supplier='王中王' where goodsId=9;
delete from goods where goodsId=3;
select*from goods where goodsName like'%牛%'
一,项目步骤
1.创建项目
2.SSM框架代码
mybatis.xml框架
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- <settings>-->
<!-- <setting name="logImpl" value="log4j"/>-->
<!-- </settings>-->
</configuration>
spring.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--1.让spring框架管理com.wang包中的所有的对象,但是排除使用了Controller注解的类-->
<context:component-scan base-package="com.wang">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--2.让spring框架的jdbc管理数据库的连接-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!--3.配置SqlSessionFactoryBean,把SqlSessionFactory对象交给IOC管理他会自动创建sqlsession对象,会根据mapper接口再创建代理对象-->
<bean id="factoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!--4.配置扫描器,扫描mapper文件,让mybatis知道要创建什么接口的实现类-->
<bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.wang.dao"/>
</bean>
</beans>
springmvc.xml框架
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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/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">
<!--1.让springmvc框架值管理com.wang.controller-->
<context:component-scan base-package="com.wang.controller"/>
<!--2.配置视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--3.静态资源不拦截-->
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/img/**" location="/img/"/>
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean id="myInterceptor" class="com.wang.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<!--4.开启注解驱动:默认会加载视图映射器和视图适配器-->
<mvc:annotation-driven/>
</beans>
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">
<!--1.配置监听器,检测servlet容器创建的时候加载spring。xml-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!--2.配置核心控制器DispatcherServlet,创建的时候加载springmvc.xml-->
<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:springmvc.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>
<!--3.配置字符集过滤器,设置中文编码-->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3.前端代码
index.jsp页面
<%--
Created by IntelliJ IDEA.
User: xiaozhi926
Date: 2023/4/14
Time: 12:20
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<style>
.jumbotron{
text-align: center;
}
</style>
</head>
<body>
<div class="jumbotron">
<h1>欢迎用户使用</h1>
<p>SSM项目</p>
<p><a class="btn btn-primary btn-lg" href="login.jsp" role="button">点击登录</a></p>
</div>
</body>
</html>
login.jsp页面(登录页面)
<%--
Created by IntelliJ IDEA.
User: xiaozhi926
Date: 2023/4/17
Time: 10:24
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页</title>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<style>
.jumbotron{
text-align: center;
}
#id1{
margin: 0 auto;
width: 500px;
}
</style>
</head>
<body>
<div class="jumbotron">
<h1>欢迎${user.username}使用</h1>
<p>SSM项目</p>
</div>
<div id="id1">
<form class="form-horizontal" action="login" method="post">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">账号:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Email" name="username">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">密码:</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" placeholder="Password" name="password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">登录</button>
</div>
</div>
</form>
</div>
</body>
</html>
zhuye.jsp页面(主页面)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: xiaozhi926
Date: 2023/4/17
Time: 10:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>主页面</title>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<style>
.jumbotron{
text-align: center;
}
</style>
</head>
<body>
<div class="jumbotron">
<h2>欢迎来自${user.address}的${user.username}进入页面</h2>
<p>SSM项目</p>
</div>
<form action="seachGoods" method="post">
<input type="search" name="keyname">
<input type="submit" value="搜索">
</form>
<table class="table table-bordered">
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品数量</th>
<th>生产商</th>
<th>操作</th>
</tr>
<c:forEach var="goods" items="${goodsList}">
<tr>
<td>${goods.goodsId}</td>
<td>${goods.goodsName}</td>
<td>${goods.price}</td>
<td>${goods.stock}</td>
<td>${goods.supplier}</td>
<td>
<a href="delete?goodsId=${goods.goodsId}">删除</a>
<a href="findById?goodsId=${goods.goodsId}">修改</a>
</td>
</tr>
</c:forEach>
<a href="add.jsp">添加商品</a>
</table>
</body>
</html>
add.jsp页面(添加页面)
<%--
Created by IntelliJ IDEA.
User: xiaozhi926
Date: 2023/4/17
Time: 13:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加页</title>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<form action="insert" method="post">
<input type="text" name="goodsName" placeholder="商品名称"></br>
<input type="number" name="price" placeholder="商品价格" step="0.01"></br>
<input type="n" name="stock" placeholder="商品数量" step="1"></br>
<input type="text" name="supplier" placeholder="生产商"></br>
<input type="submit" value="提交">
</form>
</body>
</html>
update.jsp页面(修改页面)
<%--
Created by IntelliJ IDEA.
User: xiaozhi926
Date: 2023/4/17
Time: 18:33
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改</title>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<form action="updateGoods" method="post">
商品编号:<input type="number" name="goodsId" value="${goods.goodsId}"></br>
商品名称:<input type="text" name="goodsName" value="${goods.goodsName}"></br>
商品价格:<input type="number" name="price" value="${goods.price}" step="0.01"></br>
商品数量:<input type="number" name="stock" value="${goods.stock}"></br>
生产商:<input type="text" name="supplier" value="${goods.supplier}"></br>
<input type="submit" name="" value="提交"></br>
</form>
</body>
</html>
error.jsp页面(失败页面)
<%--
Created by IntelliJ IDEA.
User: xiaozhi926
Date: 2023/4/17
Time: 11:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>失败页面</title>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<style>
.alert-danger{
text-align: center;
}
</style>
</head>
<body>
<div class="alert alert-danger" role="alert"><h1>${msg}</h1></div>
</body>
</html>
4.后端代码
bean层(User和Goods)
package com.wang.bean;
public class User {
private Integer uid;
private String username;
private String password;
private String birthday;
private String sex;
private String address;
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday='" + birthday + '\'' +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
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 getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.wang.bean;
public class Goods {
private Integer goodsId;
private String goodsName;
private Double price;
private Integer stock;
private String supplier;
@Override
public String toString() {
return "Goods{" +
"goodsId=" + goodsId +
", goodsName='" + goodsName + '\'' +
", price=" + price +
", stock=" + stock +
", supplier='" + supplier + '\'' +
'}';
}
public Integer getGoodsId() {
return goodsId;
}
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
}
contorller层(控制层 GoodsContorller和UserContorller)
UserContorller类
package com.wang.controller;
import com.wang.bean.User;
import com.wang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
@Controller
@SessionAttributes({"user"})//把user升级到session域
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/login")
public ModelAndView login(User user){
ModelAndView mv=new ModelAndView();
User login = userService.login(user);
if (login!=null){
mv.addObject("user",login);
mv.setViewName("redirect:/findAll");
}else {
mv.addObject("msg","用户名或者密码错误");
mv.setViewName("error");
}
return mv;
}
}
GoodsContorller类
package com.wang.controller;
import com.wang.bean.Goods;
import com.wang.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@SessionAttributes({"goodsList"})
public class GoodsController {
@Autowired
GoodsService goodsService;
@RequestMapping("/findAll")
public ModelAndView findAll(){
ModelAndView mv=new ModelAndView();
List<Goods> goodsList=goodsService.findAll();
mv.addObject("goodsList",goodsList);
mv.setViewName("redirect:/zhuye.jsp");
return mv;
}
@RequestMapping("/insert")
public ModelAndView insert(Goods goods){
ModelAndView mv=new ModelAndView();
System.out.println(goods);
int n = goodsService.insert(goods);
if (n>0){
mv.setViewName("redirect:/findAll");
}else {
mv.addObject("msg","用户名或者密码错误");
mv.setViewName("error");
}
return mv;
}
@RequestMapping("/delete")
public ModelAndView delete(Goods goods){
ModelAndView mv=new ModelAndView();
int n = goodsService.delete(goods.getGoodsId());
if (n>0){
mv.setViewName("redirect:/findAll");
}else {
mv.addObject("msg","用户名或者密码错误");
mv.setViewName("error");
}
return mv;
}
@RequestMapping("/findById")
public ModelAndView findById(int goodsId){
ModelAndView mv=new ModelAndView();
Goods goods = goodsService.findById(goodsId);
System.out.println("findById..."+goods);
mv.addObject("goods",goods);
mv.setViewName("update");
return mv;
}
@RequestMapping("updateGoods")
public ModelAndView updateGoods(Goods goods){
ModelAndView mv=new ModelAndView();
int n = goodsService.update(goods);
if(n>0){
mv.setViewName("redirect:/findAll");
}else {
mv.addObject("msg","用户名或者密码错误");
mv.setViewName("error");
}
return mv;
}
@RequestMapping("/seachGoods")
public ModelAndView seachGoods(String keyname){
ModelAndView mv=new ModelAndView();
List<Goods> goodsList = goodsService.seach(keyname);
mv.addObject("goodsList",goodsList);
mv.setViewName("zhuye");
return mv;
}
}
dao层(数据访问层GoodsDao和UserDao)
UserDao接口
package com.wang.dao;
import com.wang.bean.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserDao {
@Select("select * from t_user where username=#{username} and password=#{password}")
User findByNameAndPwd(User user);
}
GoodsDao接口
package com.wang.dao;
import com.wang.bean.Goods;
import com.wang.bean.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface GoodsDao {
@Select("select * from goods")
List<Goods> selectAll();
@Insert("insert into goods(goodsName,price,stock,supplier) values(#{goodsName},#{price},#{stock},#{supplier})")
int add(Goods goods);
@Delete("delete from goods where goodsId=#{goodsId}")
int del(int goodsId);
@Select("select*from goods where goodsId=#{goodsId}")
Goods selectById(int goodsId);
@Update("update goods set goodsName=#{goodsName},price=#{price},stock=#{stock},supplier=#{supplier} where goodsId=#{goodsId}")
int update(Goods goods);
@Select("select*from goods where goodsName like concat('%',#{keyname},'%')")
List<Goods> seach(String keyname);
}
interceptor层(拦截器)
MyInterceptor类
package com.wang.interceptor;
import com.wang.bean.User;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String servletPath=request.getServletPath();
if (servletPath.equals("/login") || servletPath.equals("/index.jsp") || servletPath.equals("/login.jsp") || servletPath.equals("/update.jsp") || servletPath.equals("/error.jsp") || servletPath.equals("/add.jsp") || servletPath.equals("/insert") || servletPath.equals("/findById")){
return true;
}else {
User user= (User) request.getSession().getAttribute("user");
if (user!=null){
return true;
}else {
response.sendRedirect("login.jsp");
return false;
}
}
}
}
service层(服务层)
UserService接口
package com.wang.service;
import com.wang.bean.User;
import java.util.List;
public interface UserService {
User login(User user);
}
UserServiceImpl类
package com.wang.service.impl;
import com.wang.bean.User;
import com.wang.dao.UserDao;
import com.wang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
public User login(User user) {
return userDao.findByNameAndPwd(user);
}
}
GoodsService接口
package com.wang.service;
import com.wang.bean.Goods;
import com.wang.bean.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface GoodsService {
List<Goods> findAll();
int insert(Goods goods);
int delete(int goodsId);
Goods findById(int goodsId);
int update(Goods goods);
List<Goods> seach(String keyname);
}
GoodsServiceImpl类
package com.wang.service.impl;
import com.wang.bean.Goods;
import com.wang.dao.GoodsDao;
import com.wang.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GoodsServiceImpl implements GoodsService {
@Autowired
GoodsDao goodsDao;
@Override
public List<Goods> findAll() {
return goodsDao.selectAll();
}
@Override
public int insert(Goods goods) {
return goodsDao.add(goods);
}
@Override
public int delete(int goodsId) {
return goodsDao.del(goodsId);
}
@Override
public Goods findById(int goodsId) {
return goodsDao.selectById(goodsId);
}
@Override
public int update(Goods goods) {
return goodsDao.update(goods);
}
@Override
public List<Goods> seach(String keyname) {
return goodsDao.seach(keyname);
}
}
主页面效果展示: