SSM:由SpringMVC+Spring+Mybatis组合而成的一个web项目框架
作用: 使用SpringMVC负责请求的转发和视图的管理,Spring实现业务对象管理,mybatis实现数据的持久化操作
简单了解后,让我们开始动手吧!
完整项目结构图:
1.创建maven的web项目(推荐使用idea):
2.创建完成以后,向 pom.xml中导入需要的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.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Maven_Test</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Maven_Test Maven Webapp</name>
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<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.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.14</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
</plugin>
</plugins>
</build>
</project>
拓展:如果你用的是idea,导入pom.xmljar包依赖后,可以再加入 generatorConfig.xml(逆向工程配置文件) 来快速 生成所要的表数据,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--mysql 连接数据库jar 这里选择自己本地位置 -->
<classPathEntry location="F:\software\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar"/>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/s_1027_manage?useSSL=true"
userId="root" password="111111">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL
和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.wanshi.pojo"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 如果maven工程只是单独的一个工程,targetProject="src/main/java"
若果maven工程是分模块的工程,targetProject="所属模块的名称",例如: targetProject="ecps-manager-mapper",下同 -->
<sqlMapGenerator targetPackage="com.wanshi.dao"
targetProject="src/main/resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.wanshi.dao" targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<!--数据表名--> <!--生成后的文件名-->
<table tableName="t_user" domainObjectName="user"
enableSelectByPrimaryKey="true" enableUpdateByPrimaryKey="false"
enableDeleteByPrimaryKey="true" enableInsert="true"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<property name="useActualColumnNames" value="true" />
</table>
</context>
</generatorConfiguration>
刷新maven项目,可以看到
点击两下 mybatis-generator:generate 即可生成对应的实体类、mapper接口以及映射文件,来进行快速测试
3.写 mybatis.xml(mybatis核心配置文件):
<?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>
<settings>
<setting name="logImpl" value="stdout_logging"/>
</settings>
<!--数据库连接配置-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/s_1027_manage"/> <!--记得连接自己的数据库-->
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
</environments>
<!--mapper接口位置-->
<mappers>
<mapper class="com.wanshi.dao.userMapper"/>
</mappers>
</configuration>
4.接下来写 application.xml (Spring核心配置文件),用于让Spring管理对象,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
default-lazy-init="true"
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:component-scan base-package="com.wanshi"/>
<!--数据库信息-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/s_1027_manage" /> <!--记得连接自己的数据库-->
<property name="username" value="root" />
<property name="password" value="111111" />
</bean>
<!--sqlSessionFoctory工厂类,用于生产sqlsession对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定Mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!--配置dao接口扫描包,动态的实现了dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--受扫描的dao包-->
<property name="basePackage" value="com.wanshi.dao"/>
</bean>
<!--将userService交由Spring管理,创建时注入userMapper参数-->
<bean id="userService" class="com.wanshi.service.impl.userService_Impl">
<property name="userMapper" ref="userMapper"/>
</bean>
</beans>
5.写 spring-mvc.xml (SpringMVC核心配置文件),接收用户请求,类似于@webServlet,不过这里使用的是@Controller,具体代码如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:websocket="http://www.springframework.org/schema/websocket"
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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">
<!--<mvc:annotation-driven/> 支持注解了,不必再在此写bean了 -->
<mvc:annotation-driven/>
<!--扫描包的位置-->
<context:component-scan base-package="com.wanshi.web" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/> <!--只扫描Controller类-->
</context:component-scan>
</beans>
6.Spring配置文件与Spring-mvc配置文件写好后,是没法自动调用的,需要在 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"
metadata-complete="false">
<!-- 设置主页 -->
<welcome-file-list>
<welcome-file>web/test</welcome-file>
</welcome-file-list>
<!--映射位置,即什么字段可以进入视图层的controller-->
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/web/*</url-pattern> <!--映射字段,可自己定义-->
</servlet-mapping>
<!--项目启动即加载application.xml文件-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application*.xml</param-value>
</context-param>
</web-app>
7.写好具体测试要用的类(可以使用自己的数据表 类):
pojo包:
user实体类:
package com.wanshi.pojo;
public class user {
private String id;
private String username;
private String userpassword;
private String realname;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getUserpassword() {
return userpassword;
}
public void setUserpassword(String userpassword) {
this.userpassword = userpassword == null ? null : userpassword.trim();
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname == null ? null : realname.trim();
}
}
dao包
userMapper接口:
package com.wanshi.dao;
import com.wanshi.pojo.user;
public interface userMapper {
int deleteByPrimaryKey(String id);
int insert(user record);
int insertSelective(user record);
user selectByPrimaryKey(String id);
}
resources下的com.wanshi.dao包:
userMapper映射文件(userMapper.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.wanshi.dao.userMapper">
<resultMap id="BaseResultMap" type="com.wanshi.pojo.user">
<id column="id" jdbcType="VARCHAR" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="userpassword" jdbcType="VARCHAR" property="userpassword" />
<result column="realname" jdbcType="VARCHAR" property="realname" />
</resultMap>
<sql id="Base_Column_List">
id, username, userpassword, realname
</sql>
<!--根据主键查询user-->
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user
where id = #{id,jdbcType=VARCHAR}
</select>
<!--根据主键删除user-->
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete from t_user
where id = #{id,jdbcType=VARCHAR}
</delete>
<!--新增user,必须有所有的值-->
<insert id="insert" parameterType="com.wanshi.pojo.user">
insert into t_user (id, username, userpassword,
realname)
values (#{id,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, #{userpassword,jdbcType=VARCHAR},
#{realname,jdbcType=VARCHAR})
</insert>
<!--新增user,有什么值添什么值-->
<insert id="insertSelective" parameterType="com.wanshi.pojo.user">
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="username != null">
username,
</if>
<if test="userpassword != null">
userpassword,
</if>
<if test="realname != null">
realname,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=VARCHAR},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="userpassword != null">
#{userpassword,jdbcType=VARCHAR},
</if>
<if test="realname != null">
#{realname,jdbcType=VARCHAR},
</if>
</trim>
</insert>
</mapper>
service包
userService 接口:
package com.wanshi.service;
import com.wanshi.pojo.user;
public interface userService {
user selectByPrimaryKey(String id);
}
userService_Impl(userService实现类):
package com.wanshi.service.impl;
import com.wanshi.dao.userMapper;
import com.wanshi.pojo.user;
import com.wanshi.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
public class userService_Impl implements userService {
@Autowired
private userMapper userMapper;
public void setUserMapper(com.wanshi.dao.userMapper userMapper) {
this.userMapper=userMapper;
System.out.println("userMapper创建了");
}
@Override
public user selectByPrimaryKey(String id) {
return userMapper.selectByPrimaryKey(id);
}
}
web包
userController:
package com.wanshi.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class userController {
@Autowired
private com.wanshi.service.userService userService;
@RequestMapping("/test")
public String test(){
System.out.println(userService.selectByPrimaryKey("1b7d1dbd36fa11ec91feb025aa4198fa"));
return "/index.jsp";
}
}
8.使用idea的tomcat启动该项目后,因在web.xml中配置了主页, 启动后能打开Hello Word主页,并且idea的运行代码如下,即为配置完成
完整项目代码:https://pan.baidu.com/s/1Th9zPmhG9Km_q0avI_hwuQ
提取码:oycj