SSM项目框架
- 一、项目环境
- 二、项目准备
- 1、创建Maven工程
- 2、导入Jar包
- 3、引入bootstrap前端框架
- 4、引入JQuery
- Tips:引入上述标签的时候一定要是双标签(``),单标签(`
一、项目环境
1、功能点
- 分页
- 数据校验(jquery前端校验+JSR303后端校验)
- ajax
- Rest风格的URI; 使用HTTP协议请求方式的动词,来表示对资
源的操作(GET (查询),POST (新增),PUT (修改),DELETE
(删除) )
2、技术点
- 基础框架-ssm (SpringMVC+Spring+MyBatis )
- 数据库-MySQL
- 前端框架-bootstrap快速搭建简洁美观的界面
- 项目的依赖管理-Maven
- 分页-pagehelper
- 逆向工程-MyBatis Generator
3、环境
- 编辑器IDEA 2019.2
- 数据库 MySQL 5.7.19
- Tomcat 8.5
- Maven 3.3.9
- JDK 1.8
4、设计流程
二、项目准备
1、创建Maven工程
添加Web支持
2、导入Jar包
maven官网导入
- spring
- springmvc
- mybatis
- 数据库连接池
- 数据库驱动
- 其他(servlet-api、junit、jstl、lombok等)
3、引入bootstrap前端框架
- 打开 bootstrap官网
- 点击 Bootstrap3中文文档(v3.X.X)
- 点击 下载Bootstrap
- 解压下载的文件得到 bootstrap-3.3.7-dist
- 在项目的webapp下创建static文件夹,将解压后的文件放进去
- 在head标签中引入css样式和js文件:
<link rel="stylesheet" href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js" ></script>
4、引入JQuery
- 下载jQuery的包,拷贝到web文件夹下的static文件夹中的js文件夹中
- 在head标签中引入:
<script type="text/javascript" src="static/js/jquery1.11.3.min.js"></script>
Tips:引入上述标签的时候一定要是双标签(
<script></script>
),单标签(<script/>
)会导致失效!5、测试数据库连接
- 测试连接数据库
6、创建目录
1. java类路径下创建pojo、dao(mapper)、service、controller、filter等目录
2. web/WEB-INF 下创建jsp、static等页面目录
3. resources下创建相关配置文件7、resources下配置文件框架
(1)applicatonContext.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-4.0.xsd"> </beans>
(2)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>
Tips:小贴士
创建主配置文件时,提示Configure application context 时,直接选择Create new application context即可
创建主配置文件(ApplicationContext.xml)下的副配置文件(spring-dao.xml、spring-mvc.xml、spring-service.xml等)时,一般就直接Choose Application Context
具体的结构可以看:File > Project Structure > Modules 中查看
尽量保证ApplicationContext.xml和spring-dao.xml、spring-mvc.xml、spring-service.xml在同一个ApplicationContext下(3)数据库数据源database.properties配置
java.driver=com.mysql.jdbc.Driver #注意mysql8.0+版本,需要配置时区,则添加:&serverTimezone=Asia/Shanghai&useSSL=false java.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf-8 java.username=root java.password=root
(4)spring-dao.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-4.0.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> </beans>
(5)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: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-4.0.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"> <!--1、配置注解驱动--> <mvc:annotation-driven/> <!--2、静态资源过滤器--> <mvc:default-servlet-handler/> <!--3、扫描包:controller--> <context:component-scan base-package="com.lwf.controller"/> <!--4、视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
(6)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: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-4.0.xsd http://www.springframework.org/schema/context https://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"> </beans>
三、整合Mybatis层
1、pojo下创建实体类
(1)创建实体类或逆向生成
package com.lwf.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; }
Tips:通过structure可以查看类的结构
(2)在mybatis-config.xml文件中,为实体类取别名<typeAliases> <package name="com.lwf.pojo"/> </typeAliases>
2、dao层创建实体类接口
BookMapper
package com.lwf.dao; import com.lwf.pojo.Books; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BookMapper { //添加新书 int addBook(Books books); //删除书 int deleteBook(@Param("bookId")int id); //修改书籍 int updateBook(Books books); //查询一本书 Books queryBookById(@Param("bookId")int id); //查询所有书籍 List<Books> queryAllBooks(); //通过名字查询书籍 List<Books> queryBookName(@Param("queryBookName") String queryBookName); }
3、dao层下创建接口实现配置文件
BookMapper.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.lwf.dao.BookMapper"> <insert id="addBook" parameterType="Books"> insert into ssmbuild.books (bookName, bookCounts, detail) VALUES (#{bookName},#{bookCounts},#{detail}) </insert> <delete id="deleteBook" parameterType="_int"> delete from ssmbuild.books where bookID = #{bookId} </delete> <update id="updateBook" parameterType="Books"> update ssmbuild.books set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail} where bookID = #{bookID} </update> <!--啊啊啊啊啊!!!!--> <select id="queryBookById" resultType="Books"> select * from ssmbuild.books where bookID = #{bookId} </select> <select id="queryAllBooks" resultType="Books"> select * from books </select> <select id="queryBookName" resultType="Books"> select * from books where bookName like #{queryBookName} or detail like #{queryBookName} </select> </mapper>
写完接口要记得去mybatis-config.xml文件中进行绑定
(当mapper和mapper.xml在同一个文件夹中,名字相同时,就用class="XXX"进行绑定)<mappers> <mapper class="com.lwf.dao.BookMapper"/> </mappers>
4、service层下创建业务层接口
BookService
package com.lwf.service; import com.lwf.pojo.Books; import java.util.List; public interface BookService { //添加新书 int addBook(Books books); //删除书 int deleteBook(int id); //修改书籍 int updateBook(Books books); //查询一本书 Books queryBookById(int id); //查询所有书籍 List<Books> queryAllBooks(); //通过名字查询书籍 List<Books> queryBookName(String queryBookName); }
5、service层下创建接口实现类
BookServiceImplpackage com.lwf.service; import com.lwf.dao.BookMapper; import com.lwf.pojo.Books; import java.util.List; public class BookServiceImpl implements BookService { //业务层调用dao层 private BookMapper bookMapper; //用于Spring注入bookMapper public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } public int addBook(Books books) { return bookMapper.addBook(books); } public int deleteBook(int id) { return bookMapper.deleteBook(id); } public int updateBook(Books books) { return bookMapper.updateBook(books); } public Books queryBookById(int id) { return bookMapper.queryBookById(id); } public List<Books> queryAllBooks() { return bookMapper.queryAllBooks(); } public List<Books> queryBookName(String queryBookName) { return bookMapper.queryBookName(queryBookName); } }
四、整合Spring层
1、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-4.0.xsd"> </beans>
2、将主配置文件分别配置
将ApplicationContext的功能划分为dao层配置、service层配置、mvc层配置,并分别创建spring-dao.xml、spring-mvc.xml、spring-service.xml对三者进行配置。
spring-dao.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-4.0.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--1、关联配置文件。context可以扫描指定目录或指定文件进Spring容器中--> <context:property-placeholder location="classpath:database.properties"/> <!--2、数据库连接池,这边选择的是c3p0连接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${java.driver}"/> <property name="jdbcUrl" value="${java.url}"/> <property name="user" value="${java.username}"/> <property name="password" value="${java.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> <!--SqlSessionFactory绑定数据源和mybatis配置文件--> <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--绑定数据源--> <property name="dataSource" ref="dataSource"/> <!--绑定mybatis配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!--配置dao接口扫描包,动态实现了dao接口可以注入到Spring中--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入sqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/> <!--要扫描的包--> <property name="basePackage" value="com.lwf.dao"/> </bean> </beans>
配置完成后,记得在主配置文件中进行导入:
<import resource="classpath:spring-dao.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-4.0.xsd"> <import resource="classpath:spring-dao.xml"/> <import resource="classpath:spring-service.xml"/> <import resource="classpath:spring-mvc.xml"/> </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: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-4.0.xsd http://www.springframework.org/schema/context https://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"> <!--1、扫描service层下的包--> <context:component-scan base-package="com.lwf.service"/> <!--2、将所有业务类注入到spring中,可以通过配置或注解实现--> <bean id="BookServiceImpl" class="com.lwf.service.BookServiceImpl"> <property name="bookMapper" ref="bookMapper"/> </bean> <!--3、声明式事务管理--> <bean name="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入数据源--> <property name="dataSource" ref="dataSource"/> </bean> <!--4、aop事务支持--> <tx:advice id="txAdvice" transaction-manager="TransactionManager"> <!--给那些方法配置事务--> <!--配置事务的传播特性: new propagation= --> <tx:attributes> <tx:method name="add" propagation="REQUIRED"/> <tx:method name="delete" propagation= "REQUIRED"/> <tx:method name="update" propagation="REQUIRED"/> <tx:method name="query" read-only="true"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!--配置事务切入--> <aop:config> <aop:pointcut id="txPointCut" expression="execution(* com.lwf.dao.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> </beans>
配置完成后,主配置文件中进行导入:
<import resource="classpath:spring-service.xml"/>
五、整合SpringMVC层
1、配置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"> <!--1、配置前端控制器:DispatcherServlet--> <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> <!--2、字符编码过滤器:拦截所有的请求响应,将编码转为utf-8--> <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> <init-param> <param-name>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--Rest风格url:将页面普通的post请求转换为指定的delete或put请求--> <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> </web-app>
2、创建主配置文件的副文件: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: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-4.0.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"> <!--1、配置注解驱动--> <mvc:annotation-driven/> <!--2、静态资源过滤器--> <mvc:default-servlet-handler/> <!--3、扫描包:controller--> <context:component-scan base-package="com.lwf.controller"/> <!--4、视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
导入主配置文件中:
<import resource="classpath:spring-mvc.xml"/>
六、主页面
1、创建Controller层
@Qualifier注解的作用:说明
@Controller @RequestMapping("/book") public class BookController { @Autowired @Qualifier("BookServiceImpl") private BookService bookService; @RequestMapping("/allBooks") public String queryAll(Model model){ List<Books> allBooks = bookService.queryAllBooks(); model.addAttribute("allBooks",allBooks); return "allBooks"; } }
2、创建主页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>标题页</title> <%--引入jQuery--%> <script type="text/javascript" src="static/js/jquery1.11.3.min.js"></script> <!-- 引入bootstrap的css和js文件 即可使用bootstrap --> <link rel="stylesheet" href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> </head> <body> <div style="text-align:center" class = "row clearfix "> <div class="jumbotron"> <h1>苏州图书馆</h1> <p>Welocome To Suzhou Library</p> <p><a class="btn btn-primary btn-lg btn-success" href="${pageContext.request.contextPath}/book/allBooks" role="button">Enter Library</a></p> </div> </div> </body> </html>
Tips:引用本地静态资源的路径
当我们自主引入JQuery和BootStrap时,如果是和js、bootstarp同级别目录中(如上诉的index.jsp,都在web目录下),则引用的地址直接可以写:从类路径开始写
static/bootstrap-3.3.7-dist/js/bootstrap.min.js
,就可以引入了。但是到了别的层级目录,如我们的allBooks页面,在web\WEB-INF\jsp\allBooks.jsp下,则引入的路径就不能直接写static/bootstrap-3.3.7-dist/js/bootstrap.min.js
了,需要在前面加上:${PATH}
,就变成:${PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js
当然,如果是直接引用网页的资源就不需要这么麻烦了,直接写:<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
即可3、创建查询展示页面
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> <%--引入jQuery--%> <script type="text/javascript" src="${PATH}/static/js/jquery1.11.3.min.js"></script> <!-- 引入bootstrap的css和js文件 即可使用bootstrap --> <link rel="stylesheet" href="${PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <script src="${PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <div class = "row clearfix"> <div class="col-md-12 column"> <div class="page-header"> <h1> 书籍列表<small> Book List</small> </h1> </div> </div> <div class="row"> <div class="col-md-4 column"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/ToAddBook">新增书籍</a> </div> <div class="col-md-8 column form-inline row"> <%--查询书籍--%> <form action="${pageContext.request.contextPath}/book/queryBookName" method="get" style="float: right" class="form-inline form-search"> <input type="text" name="queryBookName" class="form-control input-medium search-query" placeholder="查询书籍名称或信息"> <input type="submit" value="查询" class="btn btn-primary "> </form> </div> </div> <div class="row clearfix"> <div class="col-md-12 column"> <table class="table table-hover table-striped"> <thead> <tr> <th>书籍编号</th> <th>书籍名称</th> <th>书籍数量</th> <th>书籍详情</th> <th>书籍管理</th> </tr> </thead> <tbody> <c:forEach var="book" items="${allBooks}"> <tr> <td>${book.bookID}</td> <td>${book.bookName}</td> <td>${book.bookCounts}</td> <td>${book.detail}</td> <td> <a class="btn btn-success" href="${pageContext.request.contextPath}/book/ToUpdateBook?id=${book.bookID}">修改</a> <a class="btn btn-danger" href="${pageContext.request.contextPath}/book/deleteBook?bookID=${book.bookID}" >删除</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> </body> </html>
Tips:依赖未导入,导致启动失败
启动项目前,先检查一下,是否成功导入lib依赖,如果没有导入可以通过下图进行导入:File>Project Settings>项目
看看WEB-INF下是否有lib文件夹,如果没有则按照3创建一个,然后
按照4-5进行所有依赖的导入
七、添加功能
本项目采用的是点击添加,跳转到专门的添加页面,完成后重定向到主页面的方式。弹窗添加方式还不会,此外添加页面只加了
required
关键字,防止字段为空,并没有通过Ajax做数据校验,检索书籍名是否重复。1、主页面跳转功能:
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/ToAdd">新增书籍</a>
2、添加页面:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>添加书籍</title> <%--引入jQuery--%> <script type="text/javascript" src="${PATH}/static/js/jquery1.11.3.min.js"></script> <!-- 引入bootstrap的css和js文件 即可使用bootstrap --> <link rel="stylesheet" href="${PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <script src="${PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <div class = "row clearfix"> <div class="col-md-12 column"> <div class="page-header"> <h1> 添加书籍<small> Add Book</small> </h1> </div> </div> <div class="col-md-12 column"> <form class="form-horizontal" action="${pageContext.request.contextPath}/book/addBook" method="post"> <div class="form-group"> <label for="BookName" class="col-sm-2 control-label">书籍名称</label> <div class="col-sm-10"> <%--添加required关键字可以保证该字段不能为空--%> <input type="text" class="form-control" id="BookName" name="bookName" placeholder="BookName" required> </div> </div> <div class="form-group"> <label for="Count" class="col-sm-2 control-label">书籍数量</label> <div class="col-sm-10"> <input type="text" class="form-control" id="Count" name="bookCounts" placeholder="Count" required> </div> </div> <div class="form-group"> <label for="detail" class="col-sm-2 control-label" >书籍详情</label> <div class="col-sm-10"> <input type="text" class="form-control" id="detail" name="detail" placeholder="detail" required> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">添加书籍</button> </div> </div> </form> </div> </div> </div> </body> </html>
3、Controller:
/*跳转到添加书籍的页面*/ @RequestMapping("/ToAdd") public String toAdd(){ return "addBook"; } /*添加书籍页面*/ @RequestMapping("/addBook") public String add(Books books){ bookService.addBook(books); return "redirect:/book/allBooks"; }
八、修改功能
1、主页面跳转
<a class="btn btn-success" href="${PageContext.request.contextPath}/book/toUpdate?id=${book.bookID}">修改</a>
2、修改页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>添加书籍</title> <%--引入jQuery--%> <script type="text/javascript" src="${PATH}/static/js/jquery1.11.3.min.js"></script> <!-- 引入bootstrap的css和js文件 即可使用bootstrap --> <link rel="stylesheet" href="${PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <script src="${PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <div class = "row clearfix"> <div class="col-md-12 column"> <div class="page-header"> <h1> 修改书籍<small> Update Book</small> </h1> </div> </div> <div class="col-md-12 column"> <form class="form-horizontal" action="${pageContext.request.contextPath}/book/updateBook" method="post"> <%--获取并隐藏书籍的ID信息--%> <input type="hidden" name="bookID" value="${QueryBook.bookID}"></input> <div class="form-group"> <label for="BookName" class="col-sm-2 control-label">书籍名称</label> <div class="col-sm-10"> <%--添加required关键字可以保证该字段不能为空--%> <input type="text" class="form-control" id="BookName" name="bookName" placeholder="BookName" value="${QueryBook.bookName}" required> </div> </div> <div class="form-group"> <label for="Count" class="col-sm-2 control-label">书籍数量</label> <div class="col-sm-10"> <input type="text" class="form-control" id="Count" name="bookCounts" placeholder="Count" value="${QueryBook.bookCounts}" required> </div> </div> <div class="form-group"> <label for="detail" class="col-sm-2 control-label" >书籍详情</label> <div class="col-sm-10"> <input type="text" class="form-control" id="detail" name="detail" placeholder="detail" value="${QueryBook.detail}" required> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">修改书籍</button> </div> </div> </form> </div> </div> </div> </body> </html>
3、Controller
跳转时获取当前行中的书籍ID到修改页面,查询id获取书籍信息,并展示,用户可对除ID外的信息进行编辑。但是没有做数据校验的功能,如果数据重复或数据类型错误,不会进行处理。数据类型错误会直接报错
/*跳转到修改书籍页面*/ @RequestMapping("/toUpdate") public String toUpdate(int id,Model model){ Books book = bookService.queryBookById(id); model.addAttribute("QueryBook",book); return "updateBook"; } /*修改书籍*/ @RequestMapping("/updateBook") public String updateBook(Books books){ bookService.updateBook(books); return "redirect:/book/allBooks"; }
九、删除功能(Rest风格)
1、Controller
@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值
/*删除书籍*/ @RequestMapping("/deleteBook/{bookID}") public String deleteBook(@PathVariable("bookID") int id){ bookService.deleteBook(id); return "redirect:/book/allBooks"; }
2、主页面的跳转
<a class="btn btn-danger" href="${PageContext.request.contextPath}/book/deleteBook/${book.bookID}" >删除</a>
十、查询功能
1、主页添加查询
<div class="row"> <div class="col-md-4 column"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/ToAdd">新增书籍</a> </div> <%--查询功能--%> <div class="col-md-8 column form-inline row"> <form class="navbar-form navbar-right" method="get" action="${PageContext.request.contextPath}/book/QueryBookByName"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" name="QueryBookByName" required> </div> <button type="submit" class="btn btn-default" >查询</button> </form> </div> </div>
2、查询结果页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>查询书籍展示页面</title> <%--引入jQuery--%> <script type="text/javascript" src="${PATH}/static/js/jquery1.11.3.min.js"></script> <!-- 引入bootstrap的css和js文件 即可使用bootstrap --> <link rel="stylesheet" href="${PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <script src="${PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <div class = "row clearfix"> <div class="col-md-12 column"> <div class="page-header"> <h1> 查询书籍<small> Book List</small> </h1> </div> </div> <div class="row"> <div class="col-md-4 column"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/ToAdd">新增书籍</a> <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBooks">返回主页</a> </div> <div class="col-md-8 column form-inline row"> <form class="navbar-form navbar-right" method="get" action="${PageContext.request.contextPath}/book/QueryBookByName"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" name="QueryBookByName" required> </div> <button type="submit" class="btn btn-default">查询</button> </form> </div> </div> <div class="row clearfix"> <div class="col-md-12 column"> <table class="table table-hover table-striped"> <thead> <tr> <th>书籍编号</th> <th>书籍名称</th> <th>书籍数量</th> <th>书籍详情</th> <th>书籍管理</th> </tr> </thead> <tbody> <c:forEach var="book" items="${list}"> <tr> <td>${book.bookID}</td> <td>${book.bookName}</td> <td>${book.bookCounts}</td> <td>${book.detail}</td> <td> <a class="btn btn-success" href="${PageContext.request.contextPath}/book/toUpdate?id=${book.bookID}">修改</a> <a class="btn btn-danger" href="${PageContext.request.contextPath}/book/deleteBook/${book.bookID}" >删除</a> </td> </tr> </c:forEach> </tbody> </table> <div style="text-align:center" class = "row clearfix "> <div class="col-md-12 column"> <div class="btn btn-lg btn-bd-primary"> <span style="text-decoration:none;color: red;font-weight: bold">${error}</span> </div> </div> </div> </div> </div> </body> </html>
3、Controller
/*书名查询*/ @RequestMapping("/QueryBookByName") public String QueryBookByName(String QueryBookByName,Model model){ if(QueryBookByName.length() != 0 || QueryBookByName != null){ QueryBookByName = "%"+QueryBookByName+"%"; List<Books> books = bookService.QueryBookByName(QueryBookByName); if ( books.size() != 0 ){ model.addAttribute("list",books); }else { model.addAttribute("error","未找到相关书籍"); } }else { model.addAttribute("error","请输入正确的书籍信息"); } return "QueryBooks"; }