springmvc学习总结(二) -- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解
@[email protected] 写在最前
之前分享过下面这几篇:
mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)(附demo和搭建过程遇到的问题解决方法)
mybatis学习笔记(六) -- maven+spring+mybatis从零开始搭建整合详细过程(下)
这一篇,在这些练习的基础上,将它们整合在一起!
搭建步骤如下
一、新建maven项目,配置环境,测试是否配置成功
二、整合spring+mybatis,添加ApplicationContext.xml文件,修改pom.xml,,并连接mysql,测试是否搭建成功
(如果想了解单独的mybatis项目,可参考mybatis学习笔记(一)-- 简单入门(附测试Demo详细过程))
三、整合springmvc,添加springmvc-servlet.xml文件,修改调整,测试是否搭建成功
附:第一,二步详细操作步骤可参考
mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)
mybatis学习笔记(六) -- maven+spring+mybatis从零开始搭建整合详细过程(下)
当然下面也会附上详细的搭建过程!
项目结构一览
现在开始体验!!!
一、新建maven项目
1、新建项目,然后修改几个配置,修改完如下:
2、添加Dynamic Web Module
Apply后,查看项目结构可以看到多了个WebContent
3、将WebContent下的两个文件复制到src/main/webapp下,然后将WebContent整个删掉
4、修改Deployment Assembly,只留下下面几个
新增/src/main/webapp,步骤Add->Floder->src->main->webapp->finish
5、测试,在src/main/webapp下,新建一个index.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body>hello </body> </html>
修改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"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
运行tomcat,访问:http://localhost:8888/SSM01/,页面显示“hello”
到此,第一步骤完成!!!
二、整合Spring+MyBatis
1、修改pom.xml,加载项目需要的jar
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lmei.ssm</groupId> <artifactId>SSM01</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.0.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> <!-- 添加Spring-core包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-context包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-tx包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-jdbc包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 为了方便进行单元测试,添加spring-test包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!--添加spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!--添加aspectjweaver包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.5</version> </dependency> <!-- 添加mybatis与Spring整合的核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.5.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.2</version> </dependency> </dependencies> </project>
2、数据库准备
新建数据表tb_book,添加测试数据
3、新建包和类
(1)添加实体类Book
package com.lmei.ssm.entity; public class Book { private int id; private String bookName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } @Override public String toString() { return this.getId()+"\t"+this.getBookName(); } }
(2)添加Dao,BookDao
package com.lmei.ssm.dao; import java.util.List; import com.lmei.ssm.entity.Book; public interface BookDao { public List<Book> getAllBook(); }
(3)添加service,BookService
package com.lmei.ssm.service; import java.util.List; import com.lmei.ssm.entity.Book; public interface BookService { public List<Book> getAllBook(); }
(4)添加impl,BookServiceImpl实现BookService
package com.lmei.ssm.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.lmei.ssm.dao.BookDao; import com.lmei.ssm.entity.Book; import com.lmei.ssm.service.BookService; @Service public class BookServiceImpl implements BookService{ @Resource BookDao bookDao; public List<Book> getAllBook() { return bookDao.getAllBook(); } }
(5)添加BookMapper
<?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.lmei.ssm.dao.BookDao"> <select id="getAllBook" parameterType="int" resultType="Book"> select * from tb_book </select> </mapper>
4、添加ApplicationContext.xm和db.propertiesl文件,并注册映射
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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" 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-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <!-- 引入db.properties属性文件 --> <context:property-placeholder location="classpath:db.properties" /> <!--定义一个jdbc数据源,创建一个驱动管理数据源的bean --> <bean id="jdbcDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!--创建一个sql会话工厂bean,指定数据源 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定数据源 --> <property name="dataSource" ref="jdbcDataSource" /> <!--类型别名包,引入com.lmei.ssm.entity下的所有类 --> <property name="typeAliasesPackage" value="com.lmei.ssm.entity"></property> <!--指定sql映射xml文件的路径 --> <property name="mapperLocations" value="classpath:com/lmei/ssm/mapper/*Mapper.xml"></property> </bean> <!--自动扫描映射接口--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定sql会话工厂,在上面配置过的 --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <!-- 指定基础包,即自动扫描com.lmei.ssm.dao这个包下的所有接口类 --> <property name="basePackage" value="com.lmei.ssm.dao"></property> </bean> <!-- 创建一个sqlSession对象 --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <!--自动扫描组件 --> <context:component-scan base-package="com.lmei.ssm"> <context:exclude-filter type="aspectj" expression="com.lmei.ssm.dao.*"/> </context:component-scan> <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy> </beans>
db.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull jdbc.username=root jdbc.password=123456
5、添加测试类
TestMyBatisSpring
package com.lmei.ssm.test; import static org.junit.Assert.assertNotNull; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.lmei.ssm.dao.BookDao; import com.lmei.ssm.entity.Book; public class TestMyBatisSpring { @Test public void test() { //初始化容器 ApplicationContext ctx=new ClassPathXmlApplicationContext("ApplicationContext.xml"); //获得bean BookDao bookDao = ctx.getBean(BookDao.class); //访问数据库 List<Book> books = bookDao.getAllBook(); for (Book book : books) { System.out.println(book.getBookName()); } assertNotNull(books); } }
Run As->JUnit Test
到此,第二步完成Spring+MyBatis+Mysql!!!
三、整合springmvc
1、修改实体类Book
package com.lmei.ssm.entity; import java.io.Serializable; public class Book implements Serializable { private static final long serialVersionUID = 1L; private int id; private String bookName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } @Override public String toString() { return "id:" + getId() + ",bookName:" + getBookName() ; } }
2、在WEB-INF下新建一个文件夹view,然后在里面新建hello.jsp文件,用来测试springmvc是否搭建成功
路径webapp/WEB-INF/view/hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%-- <%@ page isELIgnored="false" %> --%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <p>${message}</p> </body> </html>
3、新建一个controller,HelloWorld.java
HelloWorld.java代码:
package com.lmei.ssm.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; //@Controller是为了让Spring IOC容器初始化时自动扫描到; //@RequestMapping是为了映射请求路径 @Controller @RequestMapping("/Hello") public class HelloWorld { @RequestMapping("/SayHello") public String SayHello(Model model) { model.addAttribute("message", "Hello Spring MVC!"); System.out.println(model.containsAttribute("message")); //是否成功赋值 return "hello"; } }
4、添加springmvc-servlet.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 http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- 自动扫描包,实现支持注解的IOC --> <context:component-scan base-package="com.lmei.ssm" /> <!-- Spring MVC不处理静态资源 --> <mvc:default-servlet-handler /> <!-- 支持mvc注解驱动 --> <mvc:annotation-driven /> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/view/" /> <!-- 后缀 --> <property name="suffix" value=".jsp" /> </bean> </beans>
5、修改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"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- Spring容器启动监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:ApplicationContext.xml</param-value> </context-param> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!--Spring mvc配置文件路径 --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:springmvc-servlet.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>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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
之前在测试过程中,不小心把<url-pattern>/ 写错成 /*,导致springmvc把*.jsp,*.sql,*.txt都当做txt处理,访问页面时,直接在浏览器加载了jsp源码。
导致测试页面hello.jsp中的${message}一直取不到Controller传过来的值。
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
6、测试,项目右键->Run As->Run On Server->Tomcat...
运行成功后,访问:http://localhost:8888/SSM01/Hello/SayHello
控制台输出:输出true,表示${message}赋值成功
浏览器输出:
到此,SpringMVC搭建成功 !!!
继续整合!!!
7、在controller包下,新建一个BookController
package com.lmei.ssm.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.lmei.ssm.entity.Book; import com.lmei.ssm.service.BookService; @Controller @RequestMapping("/Book") public class BookController { @Resource BookService bookService; @RequestMapping("/getAllBook") public String getAllBook(Model model) { List<Book> books = bookService.getAllBook(); for (Book book : books) { System.out.println(book.getBookName()); } model.addAttribute("books", books); return "Book/index"; } }
8、在WEB-INFO/view下新建一个文件夹Book,然后在文件夹内添加index.jsp
Book/index.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>图书管理</title> </head> <body> <div> <h3 class="title"><span>图书管理</span></h3> <table border="1" width="30%" class="tab"> <tr> <th>编号</th> <th>书名</th> </tr> <c:forEach var="book" items="${books}"> <tr> <td>${book.id}</td> <td>${book.bookName}</td> </tr> </c:forEach> </table> </div> </body> </html>
9、测试
运行服务器,在浏览器访问:http://localhost:8888/SSM01/Book/getAllBook
到此,完成SpringMVC+Spring+MyBatis的整合!!!
最后,附上项目Demo源码,点此下载
本文分享到此结束!!