SSM整合而成的简单书籍管理项目
SSM整合而成的简单书籍管理项目
前言
记录自己网上学习的项目
一、具体步骤
1.首先配置pom.xml文件,导入相关的jar包
代码如下(示例):
<groupId>org.example</groupId>
<artifactId>SSMBuild</artifactId>
<version>1.0-SNAPSHOT</version>
<!--导入包-->
<dependencies>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</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>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</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项目都会有一个resources目录来存放我们所有的资源配置文件,
但是我们往往在项目中不仅仅会把所有的资源配置文件都放在resources中,同时我
们也有可能放在项目中的其他位置,那么默认的maven项目构建编译时就不会把我们其
他目录下的资源配置文件导出到target目录中,就会导致我们的资源配置文件读取失败,
从而导致我们的项目报错出现异常,比如说尤其我们在使用MyBatis框架时,
往往Mapper.xml配置文件都会放在dao包中和dao接口类放在一起的,那么执行程序的时候,
其中的xml配置文件就一定会读取失败,不会生成到maven的target目录中,所以我们要在项目
的pom.xml文件中进行设置,并且我建议大家,每新建一个maven项目,就把该设置导入pom.xml文件中,以防不测!!!-->
<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>
</project>
2.然后是配置mybatis层,因为spring-mybatis整合了所有可以一块写。
mybatis-config.xml中写很少一部分代码,大部分交给spring-dao来实现配置
(前提是已经导入了相关的包)。
代码如下(示例):
<!--关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!--配置c3p0连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="dataSourceName" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/hc/dao/*.xml"/>
</bean>
<!--配置dao接口扫描包,动态的实现dao接口注入到spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.hc.dao"/>
</bean>
</beans>
下面是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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--扫描service下面的包-->
<context:component-scan base-package="com.hc.service"/>
<!--将所有业务类注入到spring中可以通过配置或者注解实现-->
<bean id="BookServiceImpl" class="com.hc.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--配置事务切入-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.hc.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
这里需要注意的是事务切入是配置了com.hc.dao包下所有和数据库的操作,因为修改完数据库之后需要提交事务,这里AOP切入来实现。(配置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: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
https://www.springframework.org/schema/context/spring-context.xsd">
<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--扫描包controller-->
<context:component-scan base-package="com.hc.controller"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
这里是mvc层的配置,配置了注解驱动,后面的controller就可以由注解来实现了,相关的包页通过mvc:default-servlet-handler自动扫描进去即可。最后面是视图解析器,配置前缀名和后缀名方便访问。
<?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="classpath:spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
最后将所有的配置xml文件在applicationContext文件中统一导入,逻辑清晰,方便管理。
准备工作到这里就结束了。接下来写对应包中的代码
2.具体业务的实现
(1)首先是实体类,和数据库中的要一一对应。
具体的get、set,toString,有参和无参构造方法就不写了。
(2)然后写dao层相关的代码这里只需要写一个接口里面定义一些方法即可。具体的交xml文件来配置。例如:
package com.hc.dao;
import com.hc.entity.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper{
//增加
int addBook(Books book);
//删除
int deleteBook(@Param("bookID") int id);
//修改
int updateBook(Books book);
//查找
Books queryBookById(@Param("bookID") int id);
//查找全部
List<Books> queryAllBooks();
//模糊查询
List<Books> likeBookByName(@Param("bookName") String bookName);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hc.dao.BookMapper">
<insert id="addBook" parameterType="books">
insert books(bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail})
</insert>
<delete id="deleteBook" parameterType="int">
delete from books where bookId = #{bookID}
</delete>
<update id="updateBook" parameterType="books">
update books
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<select id="queryBookById" resultType="books">
select * from books where bookID = #{bookID}
</select>
<select id="queryAllBooks" resultType="books">
select * from books
</select>
<select id="likeBookByName" resultType="books">
select * from books where bookName like CONCAT('%',#{bookName},'%')
</select>
</mapper>
(3)接下来是service业务层,只需要调动dao层即可。
也是先写一个BookService接口和对应的实现方法即可。这里就不赘述了。
(4)最后是controller层。调用具体的业务逻辑即可。
package com.hc.controller;
import com.hc.entity.Books;
import com.hc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
//controller调用service
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBooks")
public String queryAllBooks(Model model){
List<Books> booksList = bookService.queryAllBooks();
model.addAttribute("booksList",booksList);
return "showBooks";
}
@RequestMapping("/toaddBook")
public String toaddBook(){
return "addBook";
}
@RequestMapping("/addBook")
public String addBook(Books book){
int b = bookService.addBook(book);
return "redirect:/book/allBooks";
}
@RequestMapping("/toUpdataBook")
public String toUpdataBook(int id,Model model){
Books book = bookService.queryBookById(id);
model.addAttribute("book",book);
return "updataBook";
}
@RequestMapping("/updataBook")
public String updataBook(Books book){
bookService.updateBook(book);
return "redirect:/book/allBooks";
}
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id){
bookService.deleteBook(id);
return "redirect:/book/allBooks";
}
@RequestMapping("/likeBook")
public String likeBook(String bookName,Model model){
List<Books> booksList= bookService.likeBookByName(bookName);
if (booksList.size()==0) {
model.addAttribute("error","未查找到该书籍");
return "showBooks";
}
model.addAttribute("booksList",booksList);
/*for (Books book:books
) {
System.out.println(books);
}*/
System.out.println(booksList.size());
return "showBooks";
}
}
3.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">
<servlet>
<servlet-name>springmvc</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>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
classpath:applicationContext.xml这里一定要写applicationContext.xml因为我们最后的配置都整合到这个文件中了,如果写为其他任何一个配置文件都会扫描的不全,而导致空指针异常。
filter中配置的是防止乱码统一字符集。
这些文件应该是统一导入的,但是我的idea有些问题,扫描不到。老是报jstl无法解析的错误,如果有类似错误的话,将这些文件放到WEB-INF目录下即可解决。
4.jsp页面
jsp页面就比较简单了,这里就不多写了。来看下成品吧!
查询这里用的是模糊查询,输入相关的内容即可。
修改和删除等就不一一演示了!