本文介绍使用SpringMVC+Spring+MyBatis三大框架使用Maven快速搭建一个demo,实现数据从数据库中查询返回到页面进行展示的过程。
技术选型:SpringMVC+Spring+MyBatis+MySql+Maven+JSP+IDEA+Tomcat7+JDK1.8+Navicat for MySql
下面开始搭建项目:
一、数据库环境搭建
1、首先使用Navicat for MySql连接MySql数据库,创建一个新的数据库或者使用某一个已经存在的数据库,我这里新创建了一个test数据库,并新建一张user表,建表SQL和插入测试数据的SQL如下:
<!--SQL建表语句--> CREATE TABLE `user` ( `id` INT (50) NOT NULL, `name` VARCHAR (100) NOT NULL, `age` INT (50) NOT NULL, `address` VARCHAR (200) NOT NULL, PRIMARY KEY (`id`) ); <!--插入数据--> INSERT INTO USER (id,name,age,address)VALUES(1,'小谢',18,'上海市'); INSERT INTO USER (id,name,age,address)VALUES(2,'小尚',18,'上海市'); INSERT INTO USER (id,name,age,address)VALUES(3,'小楠',18,'天津市'); INSERT INTO USER (id,name,age,address)VALUES(4,'小勋',18,'郑州市'); INSERT INTO USER (id,name,age,address)VALUES(5,'小乔',18,'郑州市'); INSERT INTO USER (id,name,age,address)VALUES(6,'小威',18,'郑州市'); INSERT INTO USER (id,name,age,address)VALUES(7,'小欢',18,'武汉市');
二、创建一个Maven项目并补全项目目录和相关包名
1、打开IDEA,新建一个项目;
2、新建一个为ssmDemo的Maven项目,使用idea创建骨架,选择webapp进行创建:
3、项目GroupId和ArtifactId自己定义即可:
4、配置本地Maven路径:
5、配置项目名称和项目路径,点击Finish按钮即可创建项目,等待项目初始化完成:
6、项目初始化完成后,项目目录结构如下:
7、补充项目路径完整,在main文件夹下面创建java和resources文件夹,并作为项目资源文件夹;在src目录下新建test文件夹,并在test文件夹下面创建java和resources文件夹,并作为项目资源文件夹,test文件夹留做单元测试时使用:
8、在src/java目录下面创建controller、dao、domain、service、service.impl包;
三、SSM配置文件整合
1、pom.xml文件中的相关jar包的坐标,在pom.xml中添加完jar包坐标后Maven会自动下载相关的jar包,SSM整合所需要的jar包说明在注释中已经注明;
xml version="1.0" encoding="UTF-8"?> <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.0modelVersion> <groupId>com.xyfergroupId> <artifactId>ssmDemoartifactId> <version>1.0-SNAPSHOTversion> <packaging>warpackaging> <properties> <spring.version>5.0.2.RELEASEspring.version> <slf4j.version>1.6.6slf4j.version> <log4j.version>1.2.12log4j.version> <shiro.version>1.2.3shiro.version> <mysql.version>5.1.6mysql.version> <mybatis.version>3.4.5mybatis.version> <spring.security.version>5.0.1.RELEASEspring.security.version> <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> properties> <dependencies> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatisartifactId> <version>${mybatis.version}version> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatis-springartifactId> <version>1.3.0version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-contextartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-context-supportartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-aopartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-coreartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-beansartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-txartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-ormartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.aspectjgroupId> <artifactId>aspectjweaverartifactId> <version>1.6.8version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.12version> <scope>testscope> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>${mysql.version}version> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>javax.servlet-apiartifactId> <version>3.1.0version> <scope>providedscope> dependency> <dependency> <groupId>javax.servlet.jspgroupId> <artifactId>jsp-apiartifactId> <version>2.0version> <scope>providedscope> dependency> <dependency> <groupId>jstlgroupId> <artifactId>jstlartifactId> <version>1.2version> dependency> <dependency> <groupId>log4jgroupId> <artifactId>log4jartifactId> <version>${log4j.version}version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-apiartifactId> <version>${slf4j.version}version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-log4j12artifactId> <version>${slf4j.version}version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>druidartifactId> <version>1.0.9version> dependency> dependencies> project>
如果项目名下面有红色波浪线,则是缺少相应的jar包,使用Maven更新jar即可解决:
2、在src/resources文件夹下面添加springmvc.xml和applicationContext.xml文件
3、在web.xml文件配置DispatcherServlet和spring监听器,加载springmvc.xml和applicationContext.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_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <servlet-name>springmvcservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:springmvc.xmlparam-value> init-param> servlet> <servlet-mapping> <servlet-name>springmvcservlet-name> <url-pattern>*.actionurl-pattern> servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class> listener> <context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath*:applicationContext.xmlparam-value> context-param> web-app>
4、在springmvc.xml中配置controller包扫描和视图解析器;
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: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-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <context:component-scan base-package="com.xyfer.controller">context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/">property> <property name="suffix" value=".jsp">property> bean> beans>
5、在applicationContext.xml配置数据库连接信息,dao和service包扫描;
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" 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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="root" /> bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.xyfer.domain">property> <property name="mapperLocations" value="classpath:com.xyfer.dao/*Mapper.xml"/> bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.xyfer.dao">property> bean> <context:component-scan base-package="com.xyfer.service"/> beans>
6、日志文件log4j.properties放在src/resources文件夹下面;
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5
p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to
'debug' ###
#在开发阶段日志级别使用 debug
log4j.rootLogger=debug, stdout
### 在日志中输出 sql 的输入参数 ###
log4j.logger.org.hibernate.type=TRACE
至此,SSM(SpringMVC+Spring+MyBatis)三大框架整合搭建,配置文件已经整合完成。
下面开始创建java类和接口,以实现数据库数据到前端jsp页面的展示:
四、实体类和controller、service、dao接口的创建;
1、根据数据库中user表字段和实体类的映射关系,在src/main/java/com/xyfer/domain下面创建实体类User.java;
package com.xyfer.domain; public class User { public int id; public String name; public int age; public String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; } }
2、在src/main/java/com/xyfer/dao下面创建UserDao,并创建一个findUserById的方法;
package com.xyfer.dao; import com.xyfer.domain.User; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; /** * dao层 */ @Repository public interface UserDao { /** * 根据id查询user * @param id * @return */ public User findUserById(int id); }
在applicationContext.xml中配置了mapper文件的位置:
所以在src/main/resources下面创建com.xyfer.dao的包,并创建UserDaoMapper.xml文件,注意mapper文件中的namespace的配置,并书写id问getUserById的SQL语句
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.xyfer.dao.UserDao"> <select id="findUserById" parameterType="int" resultType="com.xyfer.domain.User"> select * from user where id=#{id} select> mapper>
3、在src/main/java/com/xyfer/service中创建UserService接口,并在src/main/java/com/xyfer/service/impl中创建实现类UserServiceImpl;
UserService接口:
package com.xyfer.service; import com.xyfer.domain.User; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * UserService层 */ public interface UserService { /** * 根据id查询user * @param id * @return */ public User findUserById(int id); }
实现类UserServiceImpl:
package com.xyfer.service.impl; import com.xyfer.dao.UserDao; import com.xyfer.domain.User; import com.xyfer.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * UserServiceImpl service实现类 */ @Service @Transactional public class UserServiceImpl implements UserService { @Autowired public UserDao userDao; /** * 根据id查询user * @param id * @return */ public User findUserById(int id) { return userDao.findUserById(id); } }
4、在src/main/java/com/xyfer/controller中创建UserController:
package com.xyfer.controller; import com.xyfer.domain.User; import com.xyfer.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * controller层 */ @Controller @RequestMapping("/xyfer") public class UserController { @Autowired public UserService userService; /** * 根据id查询user * @param id * @return */ @RequestMapping("/findUserById") public String findUserById(int id, Model model){ User user = userService.findUserById(id); model.addAttribute("user",user); return "userInfo"; }; }
五、前端页面展示;
由于在springmvc.xml中配置的视图解析器如图所示,并且controller控制器返回的是"userInfo":
所以要在src/main/webapp/WEB-INF下面创建一个jsp文件夹,并创建一个userInfo.jsp文件;
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> 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>user信息title> head> <body> <form> <table width="100%" border=1> <tr> <td>姓名td> <td> ${user.name } td> tr> <tr> <td>年龄td> <td> ${user.age } td> tr> <tr> <td>地址td> <td>${user.address} textarea> td> tr> table> form> body> html>
至此,已经写好所有项目需要的类和接口,项目路径如图所示:
六、发布部署项目并通过浏览器访问,得到预期的从数据库中返回的数据;
1、打开部署项目页面:
2、添加一个tomcat服务;
3、配置Server和Deployment
选择Artifact
选择war包
配置访问路径:
在浏览器中输入访问地址:http://localhost:8080/ssm/,回车,出现如下页面,则项目发布部署成功:
下面通过地址带参数发送请求,查询我们想要的数据:
地址如下:http://localhost:8080/ssm/xyfer/findUserById.action?id=1
DispatcherServlet拦截action请求,回车后的页面跳转后得到userInfo页面:
浏览器出现这个页面时,证明我们已经从数据库中查询到id值为1的user数据,并在前端页面展示user的信息。
此时,我们已经完成了SSM(SpringMVC+Spring+MyBatis)三大框架使用Maven快速搭建整合并实现数据库数据到页面进行展示。