文章目录
- SSM整合
- 1. 准备工作
- 2 MyBatis工作
- 3 Spring工作
- 4 application.xml
- 5 Controller层
SSM整合
1. 准备工作
1.依赖问题
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.25</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.15</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.15</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.6</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.14.RELEASE</version> </dependency></dependencies>
2.静态资源导出问题(对于src/main/java目录下的非.java文件也拷贝到classes目录下)
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources></build>
3.包结构创建出来
main
—-java (com.sutong.xxx)
—-resource (xx.xml, xx.properties)
—-webapp (WEB-INF, web.xml)
test
—-java
—-resource
2 MyBatis工作
0.sql-表结构
CREATE TABLE `t_books` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `count` int(11) DEFAULT NULL, `detail` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
1.MyBatis配置文件 mybatis-config.xml
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> <setting name="cacheEnabled" value="true"/> </settings> <typeAliases> <package name="com.sutong.pojo"/> </typeAliases></configuration>
2.pojo
准备好(偷懒可以导入lombok包,IDEA需要安装插件支持)
@Data // @ToString @EqualsAndHashCode @Getter @Setter @RequiredArgsConstructor 集合@AllArgsConstructor // 生成全参构造器@NoArgsConstructor // 生成无参构造器public class Books { private Integer id; private String name; private Integer count; private String detail;}
3.解决BookMapper.java
接口和BookMapper.xml
(增删查改!!)文件都放在dao包下
public interface BookMapper { void addBook(Books book); void deleteBook(Integer id); void updateBook(Books book); Books getBookById(Integer id); List<Books> getAllBook();}
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.sutong.dao.BookMapper"> <insert id="addBook"> insert into t_books(`name`, `count`, `detail`) values(#{name}, #{count}, #{detail}) </insert> <delete id="deleteBook"> delete from t_books where id = #{id} </delete> <update id="updateBook"> update t_books set `name` = #{name}, `count` = #{count}, `detail` = #{detail} where `id` = #{id} </update> <select id="getBookById" resultType="books"> select `id`, `name`, `count`, `detail` from t_books where `id` = #{id}; </select> <select id="getAllBook" resultType="books"> select `id`, `name`, `count`, `detail` from t_books; </select></mapper>
4.编写BookService.java
和BookServiceImpl.java
类,Service调用Dao层
service增删改可能有事务问题!!!
@Transactional // 所有方法开启事务了(不开启是操作一条数据提交一条)public class BookServiceImpl implements BookService { private BookMapper bookMapper; // 这里下面的配置文件注入,也可以用注解 @Override public void addBook(Books book) { bookMapper.addBook(book); } @Override public void deleteBook(Integer id) { bookMapper.deleteBook(id); } @Override public void updateBook(Books book) { bookMapper.updateBook(book); } @Override public Books getBookById(Integer id) { return bookMapper.getBookById(id); } @Override public List<Books> getAllBook() { return bookMapper.getAllBook(); } // 配置文件中注入bookMapper用的 public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; }}
3 Spring工作
database.properties
# 如果使用MySQL8+版本需要加上一个时区的配置,而且driver也不一样jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=truejdbc.username=rootjdbc.password=9527
spring-dao.xml
:
<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"> <context:property-placeholder location="classpath:database.properties"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="driverClassName" value="${jdbc.driver}" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- --> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <property name="basePackage" value="com.sutong.dao"/> </bean> <!-- --></beans>
spring-service.xml
:
<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:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.sutong.service"/> <bean id="bookServiceImpl" class="com.sutong.service.impl.BookServiceImpl"> <property name="bookMapper" ref="bookMapper"/> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>
spring-mvc.xml
:
<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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.sutong.controller"/> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine"> <bean class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver"> <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <property name="prefix" value="/WEB-INF/templates/"/> <property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8" /> </bean> </property> </bean> </property> </bean> <mvc:view-controller path="/" view-name="index"/> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="defaultCharset" value="UTF-8" /> <property name="supportedMediaTypes"> <list> <value>text/html</value> <value>text/plain</value> <value>application/json</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <mvc:default-servlet-handler/></beans>
web.xml
<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"> <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> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <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></web-app>
4 application.xml
application.xml总配置,去包含其他三个Spring配置文件!!
<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>
5 Controller层
@Controller@RequestMapping("/book")public class BookController { @Autowired // 这里只有byType也行 @Qualifier("bookServiceImpl") private BookService bookService; // 查询全部图书返回给页面显示 @RequestMapping("/list") public String list(Model model) { List<Books> books = bookService.getAllBook(); model.addAttribute("books", books); return "allBook"; } @RequestMapping("/delete") public String delete(Integer id) { bookService.deleteBook(id); return "redirect:/book/list"; }}
WEB-INF/templates/index.html
<body> <h3> <a th:href="@{/book/list}">进入书籍页面</a> </h3></body>
WEB-INF/templates/allBook.html
<body> <table> <tr> <th>书名</th> <th>数量</th> <th>描述</th> </tr> <tr th:each="book : ${books}"> <td th:text="${book.name}"></td> <td th:text="${book.count}"></td> <td th:text="${book.detail}"></td> </tr> </table></body>
测试:
http://localhost:8080/
进入首页,点击超链接就可以进入allbook.html
显示所有图书了