SSM项目小例子
今天来搭建一个SSM项目的小例子简单练一练,那项目模板还是我们那个模板,就是我们在JavaWeb最后的小例子,那到SSM中我们如何实现,后面我们再看看springboot中如何实现
javaweb中项目例子:https://blog.csdn.net/hello_list/article/details/124734814
首先我们来搭建一个SSM项目,同时也是SSM项目整合哦!
web项目创建
环境:idea2019 、maven、jdk1.8
创建一个maven项目,直接next
现在还不是一个web项目
项目右键,选择这个
我们把web勾上
这样就是一个标准的web项目了,比起maven自建的我觉得好看,普普通通的maven项目看起来最顺眼
项目就就创建好了,我们运行下,运行之前我们放个login.jsp页面,随便在网上找了一个页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<style>
.loginForm {
/*边框高度*/
height: 350px;
/*边框宽度*/
width: 500px;
/*边框颜色*/
border: #4d4d4d solid 1px;
/*边框圆角*/
border-radius: 4px;
/*阴影 水平方向,竖直方向,模糊距离*/
box-shadow: 5px 5px 5px #4d4d4d;
/*上边界距离*/
margin-top: 300px;
/*左边界距离:自动*/
margin-left: auto;
/*右边界距离:自动*/
margin-right: auto;
/*用户名、密码间距*/
padding: 20px 40px;
}
/*将用户登录置于中间*/
.loginForm h2 {
text-align: center;
}
/*修改button属性*/
.button {
text-align: center;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="loginForm">
<h2>用户登录</h2>
<form>
<div class="form-group">
<label for="exampleInputEmail1">用户名</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="请输入用户名">
</div>
<div class="form-group">
<label for="exampleInputPassword1">密码</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="请输入密码">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> 同意
<a href="#"> xxx安全协议</a> 与 <a href="#"> xxx隐私协议</a>
</label>
</div>
<div class="button">
<input type="submit" class="btn btn-primary" value="登 录"/>
</div>
</form>
</div>
</body>
</html>
打包运行项目,手把手教你,
如果没有打包,自己打个包,我们看到没有lib目录,后面我们项目的依赖不一定会加进来,现在没有依赖,后面可能我们会需要自己建一个,可能你idea不一样,视情况而变
把我们的项目加进来
OK,启动成功
下面我们开始SSM整合,然后开始写例子
SSM整合
万事开头加入依赖:
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
一定要检查自己的依赖都加进来了
添加一个maven的过滤
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
首先我们搭建spring框架:
总配置文件applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
我们先spring整合mybatis
database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/huanying?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
mybatis的配置文件:mybatis-config.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>
<typeAliases>
<package name="com.xxx.pojo"/>
</typeAliases>
<mappers>
<package name="com.xxx.dao.mapper"/>
</mappers>
</configuration>
然后通过spring去接管一下:spring-dao
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置整合mybatis -->
<!-- 1.关联数据库文件 -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 2.数据库连接池 -->
<!--数据库连接池
dbcp 半自动化操作 不能自动连接
c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.xuerxiriji.dao"/>
</bean>
</beans>
我们再直接把service层搞定下:spring-service.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"
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">
<!-- 扫描service相关的bean -->
<context:component-scan base-package="com.xuexiriji.service" />
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
OK,接下来我们整合springMVC
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">
<!--DispatcherServlet-->
<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:applicationContext.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>
<!--encodingFilter-->
<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>
<!--Session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解驱动 -->
<mvc:annotation-driven />
<!-- 2.静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示ViewResolver视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 4.扫描web相关的bean -->
<!--其实像这样的扫描,我们完全可以配置一个总的直接就是com.xuexiriji但是我们既然想留下来mybatis和service和controller的层次感就这样 -->
<context:component-scan base-package="com.xuexiriji.controller" />
</beans>
最后都放到我们applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
我们可以看到,配置好的文件idea会自动识别spring小叶子
写了这么多配置文件,项目算是搭好了,但是还没有写代码,下面我们对一个表试试CRUD
表结构,没错啦就是我们在javaweb中的Good货物表
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for good
-- ----------------------------
DROP TABLE IF EXISTS `good`;
CREATE TABLE `good` (
`goodid` int(20) NOT NULL AUTO_INCREMENT,
`goodname` varchar(20) NOT NULL,
`surplus` int(20) NOT NULL,
`goodprice` int(20) NOT NULL,
PRIMARY KEY (`goodid`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of good
-- ----------------------------
INSERT INTO `good` VALUES ('1', '黑色森林', '2', '15');
INSERT INTO `good` VALUES ('2', '奶油蛋糕', '3', '13');
INSERT INTO `good` VALUES ('3', '水果蛋糕', '2', '11');
INSERT INTO `good` VALUES ('4', '冰淇凌蛋糕', '5', '13');
INSERT INTO `good` VALUES ('9', '牛奶蛋糕', '34', '9');
INSERT INTO `good` VALUES ('11', '肉松蛋糕', '13', '13');
INSERT INTO `good` VALUES ('12', '草莓蛋糕', '99', '23');
INSERT INTO `good` VALUES ('13', '苹果蛋糕', '32', '12');
INSERT INTO `good` VALUES ('14', '香蕉蛋糕', '32', '12');
INSERT INTO `good` VALUES ('15', '火龙果蛋糕', '43', '43');
INSERT INTO `good` VALUES ('16', '香橙蛋糕', '65', '31');
INSERT INTO `good` VALUES ('17', '苹果', '43', '54');
INSERT INTO `good` VALUES ('18', '菠萝', '32', '32');
INSERT INTO `good` VALUES ('19', '橙子', '435', '32');
INSERT INTO `good` VALUES ('20', '花椒', '43', '65');
INSERT INTO `good` VALUES ('21', '大蒜', '23', '54');
INSERT INTO `good` VALUES ('22', '鸡蛋', '32', '43');
INSERT INTO `good` VALUES ('23', '西红柿', '32', '43');
还有就是javaweb中的展示页面,因为都是jsp所以都一样,所以不改了
我们把index.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>学习日记</title>
</head>
<body>
<!--页面主要内容-->
<main class="ftdms-layout-content">
<div style="margin-bottom: 90px;">
<div class="row" style="margin-top: 15px;">
<div class="col-lg-12">
<div class="card">
<div class="card-toolbar clearfix">
<form class="pull-right search-bar" method="post" action="GoodGetSearchServlet" role="form">
<div class="input-group">
<input type="hidden" name="search_field" id="search-field"
value="title">
<input type="text" class="form-control col-lg-4" value="${keyword }" name="keyword" placeholder="请输入名称"/>
<div class="input-group-btn">
<button class="btn btn-default dropdown-toggle" id="search-btn" type="submit">
搜索
<!--<span class="caret"></span>-->
</button>
</div>
<!-- <ul class="dropdown-menu">
<li> <a tabindex="-1" href="javascript:void(0)" data-field="title">标题</a> </li>
<li> <a tabindex="-1" href="javascript:void(0)" data-field="cat_name">栏目</a> </li>
</ul>
-->
</div>
</form>
<div class="toolbar-btn-action">
<a class="btn btn-primary m-r-5 submenuitem"
href="goodinsert.jsp" data-id="link552" data-index="552">
新增</a>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th width="5"><label
class="ftdms-checkbox checkbox-primary"> <input
type="checkbox" id="check-all"><span></span>
</label></th>
<th>货物编号</th>
<th>货物名称</th>
<th>剩余数量</th>
<th>货物价格</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${goods}" var="good">
<tr>
<td>${good.goodId}</td>
<td>${good.goodName}</td>
<td>${good.surplus}</td>
<td>${good.goodPrice}</td>
<td><font class="text-success">正常</font></td>
<td>
<div class="btn-group">
<div class="toolbar-btn-action">
<a class="btn btn-success m-r-5 submenuitem" href="GoodGetByIdServlet?goodid=${good.goodId}" data-id="link553" data-index="553"><i class="ftsucai-edit-2">编辑</i></a>
<a class="btn btn-warning m-r-5 submenuitem" href="GoodDeleteByIdServlet?goodId=${good.goodId}" data-id="link554" data-index="554"><i class="ftsucai-edit-2">删除</i></a>
</div>
</div>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<ul class="pagination">
<li class="disabled"><span>«</span></li>
<li class="active"><span>1</span></li>
<li><a class="submenuitem" href="pages_data.html#2">2</a></li>
<li><a href="#3">3</a></li>
<li><a href="#4">4</a></li>
<li><a href="#5">5</a></li>
<li><a href="#1">6</a></li>
<li><a href="#1">7</a></li>
<li><a href="#1">8</a></li>
<li class="disabled"><span>...</span></li>
<li><a href="#">14452</a></li>
<li><a href="#">14453</a></li>
<li><a href="#">»</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</main>
<!--End 页面主要内容-->
<!-- 新 Bootstrap 核心 CSS 文件 -->
<link
href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet">
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script
src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(function() {
$('.search-bar .dropdown-menu a')
.click(
function() {
var field = $(this).data('field') || '';
$('#search-field').val(field);
$('#search-btn')
.html(
$(this).text()
+ ' <span class="caret"></span>');
});
});
</script>
</body>
</html>
一步步来,开始Good.java
package com.xuexiriji.pojo;
public class Good {
private int goodId;
private String goodName;
private int surplus;
private int goodPrice;
public int getGoodId() {
return goodId;
}
public void setGoodId(int goodId) {
this.goodId = goodId;
}
public String getGoodName() {
return goodName;
}
public void setGoodName(String goodName) {
this.goodName = goodName;
}
public int getSurplus() {
return surplus;
}
public void setSurplus(int surplus) {
this.surplus = surplus;
}
public int getGoodPrice() {
return goodPrice;
}
public void setGoodPrice(int goodPrice) {
this.goodPrice = goodPrice;
}
public Good(int goodId, String goodName, int surplus, int goodPrice) {
super();
this.goodId = goodId;
this.goodName = goodName;
this.surplus = surplus;
this.goodPrice = goodPrice;
}
public Good() {
super();
}
@Override
public String toString() {
return "Good [goodId=" + goodId + ", goodName=" + goodName + ", surplus=" + surplus + ", goodPrice=" + goodPrice
+ "]";
}
}
mapper接口:goodDao.java
package com.xuexiriji.dao;
import com.xuexiriji.pojo.Good;
import java.util.List;
public interface GoodDao {
public List<Good> selectAllGood();
}
GoodMapper.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="com.xuexiriji.dao.GoodDao">
<select id="selectAllGood" resultType="Good">
select * from good
</select>
</mapper>
service这里我就不面向接口了:GoodService
@Service
public class GoodService {
@Autowired
GoodDao GoodDao;
public List<Good> selectAllGood(){
return GoodDao.selectAllGood();
}
}
这里我们看好,只要是被spring接管的都是有小叶子的,而且点击都可以跳过去,如果你没有跳过去,那就是没接管,项目都不用运行,可以去找找错误了
GoodController
@Controller
public class GoodController {
@Autowired
GoodService goodService;
@RequestMapping("/selectAllGood")
public String selectAllGood(Model model){
List<Good> goods = goodService.selectAllGood();
model.addAttribute("goods",goods);
return "index";
}
}
我们一会儿从登录页面进,登录页面表单加上请求路径
启动我们的项目,一下去写这么多中间都没有测试,害,希望不要报错一大堆吧,没有报错启动成功:
果然不出我所料必须报错,说没有这个类,其实看到我就想到,还记得之前启动web项目时候说的吗,lib依赖可能不被加进去,所以我们还得重新打下包
这样这些包就有了
重新启动,欧克,成功启动
点击登录,报错:
这里肯定就是我们的mapper和接口有问题,看下我们的配置,应该是这样的,因为这次我们类名没有起的一直,那就不改了,添加一个mapper.xml记得来这里注册就行
Ok,测试搞定
还可以哈,我差不多,这是我第三次吧,整合这个,其实第一整合完,第二次也就是复制粘贴,这次差不多也是复制的第一次的,所以你自己整合好的一个项目,留好,可能这是你后面项目的基底。
小结
这里打算给大家整合做一个小例子的,今天就先整合到这里吧,等后面再给大家做出来,看到这里了,还不点个赞吗,留个关注也行呀,bye~