简述:使用SSM框架,搭建一个简单的增删查改小项目。
目录
4、配置ApplicationContext-mybatis.xml配置文件
1、创建maven项目,在pom中导入依赖
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.22</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.1</version>
</dependency>
<!--spring 集成 web-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--数据池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--SqlSessionFactoryBean-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!--AOP-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.4</version>
</dependency>
<!--thymeleaf模板引擎-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
</dependencies>
<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>
2、创建如下层级目录
3、编写springmvc.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: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">
<!--扫包-->
<context:component-scan base-package="com.lc.controller"/>
<context:component-scan base-package="com.lc.service"/>
<!--用来提供Controller请求转发-->
<mvc:annotation-driven/>
<!--DispatcherServlet默认拦截所有请求,在这里设置不拦截静态资源-->
<mvc:default-servlet-handler/>
<!--静态资源路径映射-->
<!--<mvc:resources mapping="/*.html" location="/pages/"/>-->
<mvc:resources mapping="/*.js" location="/static/"/>
<!--<mvc:resources mapping="/**" location="/thymeleaf/**"/>-->
<!--设置默认打开界面-->
<mvc:view-controller path="/" view-name="/login"/>
<!-- 配置thymeleaf模板解析器-->
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver" id="templateResolver">
<property name="prefix" value="/thymeleaf"/>
<property name="suffix" value=".html"/>
<property name="characterEncoding" value="UTF-8"/>
<!-- 是否设置缓存-->
<property name="cacheable" value="false"/>
<!-- 模板的类型 -->
<property name="templateMode" value="HTML"/>
</bean>
<!--模板引擎-->
<bean id="engine" class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver"/>
</bean>
<bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver" id="resolver">
<property name="templateEngine" ref="engine"/>
<!--必须设置字符类型,不然中英文乱码-->
<property name="characterEncoding" value="UTF-8"/>
</bean>
</beans>
4、配置ApplicationContext-mybatis.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">
<!--加载jdbc文件-->
<context:property-placeholder location="classpath:properties/jdbc.properties"/>
<!--配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
</bean>
<!-- 配置自动扫描mybatis Mapper.java Mapper.xml -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描包 dao-->
<property name="basePackage" value="com.lc.dao" />
<!-- sqlSessionFactoryBeanName是批factory的名称 此处使用value,而不是ref -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
5、创建jdbc.properties数据库文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/stu?serverTimezone=UTC&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
6、编写web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!-- post方式提交乱码解决 begin -->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- post方式提交乱码解决 end -->
<!--springmvc begin-->
<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:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!--拦截所有后台资源请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--springmvc end-->
<!--spring 后端 begin-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--spring 后端 end-->
</web-app>
7、编写java代码
1、编写实体类(删除了get和set方法)
1、Pet类
public class Pet {
private Integer id;
private String name;
private String type;
private Integer health;
private Integer love;
private Date birthday;
}
2、编写PetOwner ,用于登录
public class PetOwner {
private int id;
private String name;
private String password;
private double money;
}
2、定义接口
1、PetDao接口
public interface PetDao {
public List<Pet> getListPet();
Pet getById(int id);
Integer insertPet(Pet pet);
Integer updatePet(Pet pet);
Integer deletePet(Integer id);
Pet findPet(String name);
}
2、PetOwner接口
public interface PetOwnerDao {
public String getPwd(String name);
}
3、编写service层
定义PetOwnerService接口
public interface PetOwnerService {
public boolean login(String name,String password);
public List<Pet> getAllPet();
public Pet getByID(int id);
//插入
public boolean insertPet(Pet pet);
//更新信息
public boolean updatePet(Pet pet);
boolean deletePet(Integer id);
Pet findPet(String name);
}
4、编写service实现类
@Service
public class PetOwnerServiceImpl implements PetOwnerService {
@Autowired
private PetOwnerDao petOwner;
@Autowired
private PetDao petDao;
@Override
public boolean login(String name, String password) {
String pwd = petOwner.getPwd(name);
if (password.equals(pwd) && !pwd.isEmpty() && pwd != null) return true;
return false;
}
@Override
public List<Pet> getAllPet() {
return petDao.getListPet();
}
@Override
public Pet getByID(int id) {
return petDao.getById(id);
}
@Override
public boolean insertPet(Pet pet) {
return petDao.insertPet(pet) > 0;
}
@Override
public boolean updatePet(Pet pet) {
return petDao.updatePet(pet) > 0;
}
@Override
public boolean deletePet(Integer id) {
return petDao.deletePet(id) > 0;
}
@Override
public Pet findPet(String name) {
return petDao.findPet(name);
}
}
5、编写controller层
@Controller
@RequestMapping("/pet")
public class PetController {
@Autowired
private PetOwnerService petOwnerService;
@RequestMapping("/login")
@ResponseBody
public BaseResult login(String username, String password){
boolean login = petOwnerService.login(username, password);
System.out.println("login:"+login);
if (login == true){
return BaseResult.success();
}
return BaseResult.error();
}
/**
* 查询所有宠物
* @param model
* @return
*/
@RequestMapping("/list")
public String getList(Model model){
List<Pet> allPet = petOwnerService.getAllPet();
model.addAttribute("allPet",allPet);
return "/list";
}
/**
* 跳转到宠物页面,并修改当前宠物信息
* @param id
* @param model
* @return
*/
@RequestMapping("/updatePet")
public String updatePet(Integer id,Model model){
model.addAttribute("pet",pet);
return "/updatePet";
}
/**
* 更新宠物信息,并保存
* @param id
* @param name
* @param type
* @param health
* @param love
* @param birthday
* @return
*/
@RequestMapping("/updatePetSave")
@ResponseBody
public BaseResult updatePetSave(Integer id,String name,String type,
Integer health,Integer love,Date birthday){
Pet pet = new Pet(id,name,type,health,love,birthday);
boolean b = petOwnerService.updatePet(pet);
if (true == true) return BaseResult.success();
return BaseResult.error();
}
/**
* 添加宠物
* @param id
* @param name
* @param type
* @param health
* @param love
* @param birthday
* @return
*/
@RequestMapping("/insertPet")
@ResponseBody
public BaseResult insertPet(Integer id,String name,String type,
Integer health,Integer love,Date birthday){
Pet pet = new Pet(id,name,type,health,love,birthday);
boolean b = petOwnerService.insertPet(pet);
if (true == true) return BaseResult.success();
return BaseResult.error();
}
/**
* 跳转到添加页面
* @return
*/
@RequestMapping("/addPet")
public String addPet(){
return "/addPet";
}
/**
* 删除操作
* @param id
* @return
*/
@RequestMapping("/deletePet")
@ResponseBody
public BaseResult deletePet(Integer id){
System.out.println("id:"+id);
boolean b = petOwnerService.deletePet(id);
if (b == true) return BaseResult.success();
return BaseResult.error();
}
@RequestMapping("/findByName")
public String findByName(String name, Model model){
Pet pet = petOwnerService.findPet(name);
System.out.println("PetName:"+pet.getName());
System.out.println("Pet:"+pet.getId());
model.addAttribute("findPet",pet);
return "/findlist";
}
}
6、编写公共返回类
public class BaseResult implements Serializable {
// 状态编码
private Integer code;
// 状态描述
private String message;
}
8、前端页面(使用thymeleaf模板)
1、登录页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>宠物商店</title>
<link rel="stylesheet" type="text/css" href="/static/css/login.css">
<script src="/static/jQuery-2.1.4.min.js"></script>
</head>
<body>
<div class="container">
<div class="login-wrapper">
<div class="header">宠物商店</div>
<div class="form-wrapper">
<input type="text" id="username" name="username" placeholder="账号" class="input-item">
<input type="password" id="password" name="password" placeholder="密码" class="input-item">
</div>
<div>
<button type="button" class="btn" onclick="login();">立即登陆</button>
</div>
</div>
</div>
<script>
function login() {
if ($('#username').val().trim().length==0||$('#username').val().trim()==''){
alert("用户名不能为空")
return false;
}
if ($('#password').val().trim().length==0||$('#password').val().trim()==''){
alert("密码不能为空")
return false;
}
$.ajax({
url: '/pet/login',
type: 'post',
dataType: 'json',
data: {
username : $('#username').val().trim(),
password : $('#password').val().trim()
},
success: function (result) {
console.log(result);
if (result.code == 200){
alert("登陆成功")
location.href = "/pet/list";
}
else{
alert("用户名或者密码错误!")
}
},
error: function (result) {
alert("亲,系统升级中")
}
})
}
</script>
</body>
</html>
2、列表页
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>宠物列表页</title>
<link rel="stylesheet" type="text/css" href="/static/css/list.style.css">
<script src="/static/jQuery-2.1.4.min.js"></script>
</head>
<body>
<div class="box">
<div class="header">宠物列表</div>
<form class="" report-submit="false" bindsubmit="" bindreset="">
<input type="text" id="searchPet" placeholder="搜索宠物">
<button type="button" class="btn" onclick="search();">搜索</button>
<button type="button" class="btn" onclick="addPet();">新增宠物</button>
<table>
<tr>
<th>id</th>
<th>宠物昵称</th>
<th>宠物类型</th>
<th>宠物健康值</th>
<th>宠物热爱值</th>
<th>宠物生日</th>
<th>操作</th>
</tr>
<tr th:each="pet:${allPet}">
<input type="hidden" id="petID" th:value="${pet.id}">
<td th:text="${pet.id}"/>
<td th:text="${pet.name}"/>
<td th:text="${pet.type}"/>
<td th:text="${pet.health}"/>
<td th:text="${pet.love}"/>
<td th:text="${pet.birthday}"/>
<td>
<a th:href="'updatePet?id='+${pet.id}">修改</a>
<!-- <a th:href="'deletePet?id='+${pet.id}">删除</a>-->
<a href="javascript:void(0)" th:onclick="|javascript : deletePet( '${ pet.id }' )|">删除</a>
</td>
</tr>
</table>
</form>
</div>
<script>
function search() {
console.log($('#searchPet').val())
var name = $('#searchPet').val();
if ($('#searchPet').val().trim().length==0||$('#searchPet').val().trim().length=='')
location.href="/pet/list";
else location.href="/pet/findByName?name="+$('#searchPet').val();
}
function deletePet(id) {
console.log(id)
$.ajax({
url: "/pet/deletePet",
type: 'post',
dataType: 'json',
data: {
id: id
},
success: function (result){
console.log(result)
if (result.code == 200){
alert("宠物信息删除成功")
}
else {
alert("宠物信息删除失败")
}
location.href = "/pet/list";
}
})
}
function addPet() {
location.href="/pet/addPet";
}
</script>
</body>
</html>
3、更新页
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>宠物信息修改页</title>
<link rel="stylesheet" type="text/css" href="/static/css/list.style.css">
<script src="/static/jQuery-2.1.4.min.js"></script>
</head>
<body>
<div class="box">
<div class="header">宠物信息修改</div>
<form id="PetFrom" th:object="${Pet}">
<input type="hidden" id="petId" th:value="${pet.id}"><br/>
宠物的昵称:<input type="text" id="petName" th:value="${pet.name}"><br/>
宠物的类型:<input type="text" id="petType" th:value="${pet.type}"><br/>
宠物健康值:<input type="text" id="petHealth" th:value="${pet.health}"><br/>
宠物热爱值:<input type="text" id="petLove" th:value="${pet.love}"><br/>
宠物的生日:<input type="text" id="petBirthday" th:value="${pet.birthday}"><br/>
</form>
<div>
<button type="button" class="btn" onclick="updatePetInfo();">立即修改</button>
<button id="close_btn" type="button" class="btn" onclick="cancelSave()">取消</button>
</div>
</div>
<script>
function updatePetInfo(){
// $('#username').val().t
console.log($('#petName').val())
console.log($('#petId').val())
$.ajax({
url: "/pet/updatePetSave",
type: 'post',
dataType: 'json',
data: {
id: $('#petId').val(),
name: $('#petName').val(),
type: $('#petType').val(),
health: $('#petHealth').val(),
love: $('#petLove').val(),
birthday: $('#petBirthday').val()
},
success: function (result){
console.log(result)
if (result.code == 200){
alert("宠物信息修改成功")
}
else {
alert("宠物信息修改失败")
}
location.href = "/pet/list";
},
error: function (){
}
})
}
function cancelSave() {
location.href = "/pet/list";
}
</script>
</body>
</html>
9、Mapper文件
1、petMapper.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.lc.petboot.dao.PetDao">
<select id="getListPet" resultType="com.lc.petboot.domain.Pet">
select * from pet
</select>
<select id="getById" resultType="com.lc.petboot.domain.Pet">
select * from pet where id = #{id}
</select>
<insert id="insertPet" parameterType="com.lc.petboot.domain.Pet">
insert into pet (name,type,health,love,birthday) values(#{name},#{type},#{health},#{love},#{birthday})
</insert>
<update id="updatePet" parameterType="com.lc.petboot.domain.Pet" >
update pet set name=#{name},type=#{type},health=#{health},love=#{love},birthday=#{birthday} where id = #{id}
</update>
<delete id="deletePet" parameterType="int">
delete from pet where id = #{id}
</delete>
<select id="findPet" parameterType="string" resultType="com.lc.petboot.domain.Pet">
select * from pet where name = #{name}
</select>
</mapper>
2、PetOwnerMapper文件
<?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.lc.petboot.dao.PetOwnerDao">
<select id="getPwd" resultType="string">
select password from petowner where name = #{name}
</select>
</mapper>