SSM框架整合
·前言
刚通过视频学完mybatis、spring、springMVC,做了一个SSM框架的整合。此框架是结合了视频中老师的思路,按照自己的理解进行整合的。这是原出处:http://dwz.date/ac27。框架设计了一个图书表,并可以通过前端web页面对图书表进行增删改查等操作。由于没有前端基础,页面比较简陋。同时,代码不够规范,大小写格式没有按照规范来。希望以后可以注意到并改正。
·整合步骤:
(1)通过maven创建一个不使用模板的项目,设置GAV(groupId、artifactId、version),并把项目设置成web项目
(2)创建数据库 :
CREATE TABLE `books` ( `bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT \'书id\', `bookName` VARCHAR(100) NOT NULL COMMENT \'书名\', `bookCounts` INT(11) NOT NULL COMMENT \'数量\', `detail` VARCHAR(200) NOT NULL COMMENT \'描述\', KEY `bookID` (`bookID`) ) ENGINE=INNODB DEFAULT CHARSET=utf8
(3)导入依赖包,在pom.xml中配置:
<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> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.4</version> </dependency> </dependencies>
(4)设置静态资源过滤,在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>
(5)创建项目基本结构(创建每一层的包):
entity、dao、service、controller
(6)创建基础框架配置:
1.在resources文件夹中创建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> </configuration>
2.在resources文件夹中创建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>
(7)在resources文件夹中创建数据库配置文件 database.properties:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssmbuilduseSSL=true&useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=123
(8)IDEA关联数据库
(9)编写实体类:在entity下创建Books类:
package com.zyf.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; }
(10)编写dao层的BooksMapper接口:
package com.zyf.dao; import com.zyf.entity.Books; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BooksMapper { int addBooks(Books books); int deleteBooks(@Param("bookID") int id); int updateBooks(Books books); Books queryBooksById(@Param("bookID")int id); List<Books> queryAllBooks(); }
(11)编写BooksMapper.xml实现接口BooksMapper:
<?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.zyf.dao.BooksMapper"> <insert id="addBooks" parameterType="Books"> insert into mybatis.books values (#{bookID},#{bookName},#{bookCounts},#{detail}); </insert> <delete id="deleteBooks" parameterType="int"> delete from mybatis.books where bookID=#{bookID}; </delete> <update id="updateBooks" parameterType="Books"> update mybatis.books set bookName = #{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID}; </update> <select id="queryBooksById" resultType="Books"> select * from mybatis.books where bookID=#{bookID}; </select> <select id="queryAllBooks" resultType="Books"> select * from mybatis.books; </select> </mapper>
在编写该代码的时候,需要在resources/mybatis-config.xml中,定义别名以及注册该mapper.xml:
<typeAliases> <package name="com.zyf.entity"/> </typeAliases> <mappers> <mapper resource="com/zyf/dao/BooksMapper.xml"/> </mappers>
(12)编写service层BooksService接口:
package com.zyf.service; import com.zyf.entity.Books; import java.util.List; public interface BooksService { int addBooks(Books books); int deleteBooks(int id); int updateBooks(Books books); Books queryBooksById(int id); List<Books> queryAllBooks(); }
(13)编写service层BooksService的实现类BooksServiceImpl:
package com.zyf.service; import com.zyf.dao.BooksMapper; import com.zyf.entity.Books; import java.util.List; public class BooksServiceImpl implements BooksService{ //调用dao层的操作,设置一个set接口,方便Spring管理 private BooksMapper booksMapper; public void setBooksMapper(BooksMapper booksMapper){ this.booksMapper=booksMapper; } public int addBooks(Books books) { return booksMapper.addBooks(books); } public int deleteBooks(int id) { return booksMapper.deleteBooks(id); } public int updateBooks(Books books) { return booksMapper.updateBooks(books); } public Books queryBooksById(int id) { return booksMapper.queryBooksById(id); } public List<Books> queryAllBooks() { return booksMapper.queryAllBooks(); } }
(14)编写resources/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" 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"> <!--1.关联数据库配置文件--> <context:property-placeholder location="classpath:database.properties"/> <!--2.注入数据库连接池--> <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对象,设置连接池和mybatis配置文件的位置--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!--4.MapperScannerConfigurer 自动扫描 将Mapper接口生成代理注入到Spring--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zyf.dao"/> </bean> <!--5.将BookServiceImpl注入到容器中--> <!--当使用注解的方式注入时候,需要加入扫描代码<context:component-scan base-package="com.zyf.service" />--> <bean id="BookServiceImpl" class="com.zyf.service.BooksServiceImpl"> <property name="booksMapper" ref="booksMapper"/> </bean> <!--6.配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--截止到6mybatis已经整合完毕,从7开始配置SpringMVC,即控制层以及请求等等的相关内容--> <!--7.开启springMVC注解驱动,并设置JSON为utf-8--> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=utf-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!--8..静态资源默认servlet配置--> <mvc:default-servlet-handler/> <!--9.由于使用了注解所以需要扫描--> <context:component-scan base-package="com.zyf.controller"/> <!--10.配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
(15)编写web.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: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> <!--设置过滤器,此为一个编码类型的设置--> <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>
(16)编写控制层BooksController:
package com.zyf.controller; import com.zyf.entity.Books; import com.zyf.service.BooksService; 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("/Books") public class BooksController { @Autowired @Qualifier("BookServiceImpl") private BooksService booksService; @RequestMapping("/All") public String queryAllBooks(Model model) { List<Books> list = booksService.queryAllBooks(); model.addAttribute("books", list); return "AllBooks"; } @RequestMapping("/toAddBooks") public String toAddBooks() { //使用此方法,可以跳转到WEB-INF下面的jsp页面 return "AddBooks"; } @RequestMapping("/AddBooks") public String AddBooks(Books books) { System.out.println(books); booksService.addBooks(books); return "redirect:/Books/All"; } @RequestMapping("/DeleteBooks/{bookID}") public String DeleteBooks(@PathVariable("bookID") int bookID) { booksService.deleteBooks(bookID); return "redirect:/Books/All"; } @RequestMapping("/toUpdate") public String toUpdate(int id, Model model) { Books books = booksService.queryBooksById(id); model.addAttribute("books", books); return "UpdateBooks"; } @RequestMapping("/UpdateBooks") public String UpdateBooks(Books books) { booksService.updateBooks(books); return "redirect:/Books/All"; } }
(17)编写前端:1.主页面(index.jsp):
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <a href="${pageContext.request.contextPath}/Books/All">查看所有书籍</a> </body> </html>
2.展示所有书籍页面(AllBooks.jsp):
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>展示所有书籍</title> </head> <body> <p><a href="${pageContext.request.contextPath}/Books/toAddBooks">添加书籍</a></p> <table> <thead> <tr> <th>书籍编号</th> <th>书籍名字</th> <th>书籍数量</th> <th>书籍详情</th> <th>操作</th> </tr> </thead> <tbody> <c:forEach var="book" items="${books}"> <tr> <th>${book.bookID}</th> <th>${book.bookName}</th> <th>${book.bookCounts}</th> <th>${book.detail}</th> <th><a href="${pageContext.request.contextPath}/Books/toUpdate?id=${book.bookID}">修改</a>|<a href="${pageContext.request.contextPath}/Books/DeleteBooks/${book.bookID}">删除</a></th> </tr> </c:forEach> </tbody> </table> </body> </html>
3.添加书籍页面(AddBooks.jsp):
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>添加书籍</title> </head> <body> <form action="${pageContext.request.contextPath}/Books/AddBooks" method="post"> 书籍名字:<input type="text" name="bookName"/><br> 书籍数量:<input type="text" name="bookCounts"/><br> 书籍详情:<input type="text" name="detail"/><br> <input type="submit" name="添加"/> </form> </body> </html>
4.修改书籍页面(UpdateBooks.jsp):
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="${pageContext.request.contextPath}/Books/UpdateBooks" method="post"> <input type="hidden" name="bookID" value="${books.bookID}"> 书籍名字:<input name="bookName" type="text" value="${books.bookName}"><br> 书籍数量:<input name="bookCounts" type="text" value="${books.bookCounts}"><br> 书籍详情:<input name="detail" type="text" value="${books.detail}"><br> <input type="submit" name="修改"> </form> </body> </html>
(18)打开project structure,把包导入
·初步创建项目后运行遇到的问题:
(1)applicationContext.xml的头没有写全
(2)最后添加了Jackson的包没有在project structure中添加
(3)空指针报错异常检查:web.xml配置的前段控制器绑定的配置文件是否包含了所有配置、控制层调用的service的接口是new出来的还是spring的,new出来的是错误的。