古语有云: 万恶淫为首,百善孝为先。 我们后辈当自勉。

上一章简单介绍了 Maven整合SSH项目(六),如果没有看过,​​请观看上一章​​

一 . Maven 整合SSM框架项目

如今,项目开发基本上都是使用 SSM项目进行开发,所以掌握 SSM各个框架的使用,是非常有必要的。 关于 MyBatis框架, SpringMVC框架, Spring框架, 有不明白的,可以观看老蝴蝶以前写的文章。

二. Maven 整合 SSM框架的详细步骤

二.一 创建数据库 ssm

由于 MyBatis 并不会像 Hibernate一样,由pojo 自动生成表, 相反,MyBatis的逆向工程是通过 表来生成对应的pojo. 所以,我们需要创建数据库 ,创建表 user.

利用 Navicat for MySQL 工具进行创建

1 . 创建数据库 ssm

Maven整合SSM项目(七)_maven

2 . 创建表 user 并 添加相应的数据, 其中 id 为主键,自增。

Maven整合SSM项目(七)_spring_02

二.二 创建 Maven 工程,取名为 SSM

与以前创建 Maven 项目一样。 新建–>其他—>Maven Project–>跳过下一步—> 填写SSM信息,选中的是 war 类型。

Maven整合SSM项目(七)_Maven中resources的用法_03

创建之后,缺少 web.xml 报错。

选中 SSM 项目, 右键 Java EE Tools——>Generate Deployment Descriptor Stub, 系统便会自动创建 web.xml 文件了。

二.三 在 pom.xml 里面添加依赖 (最重要的一步)

需要将 MyBatis, Spring,SpringMVC ,日志, tomcat,junit 测试,mysql数据库驱动 等 jar包都加入进来。

为了方便,老蝴蝶直接把 依赖和 tomcat的配置信息放置进来。

<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.yjl</groupId>
<artifactId>SSM</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- junit 测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- tomcat 配置 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<!-- jstl 与 standard -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- spring依赖 -->
<!-- spring web依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<!-- spring-aspects依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>

<!-- spring 与orm 依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<!-- spring 测试的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>

<!-- springmvc 的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>

<!-- mybatis的依赖 -->

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!-- mybatis与 spring整合 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>

<!-- myabtis分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.9</version>
</dependency>


<!-- mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<!-- c3p0依赖 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>

<!-- 日志依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.5</version>
</dependency>
<!-- slf4j 与log4j进行整合 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>

<!-- fastjson的包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>

<!-- hibernate验证框架 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-cdi</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-launcher</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>5.2</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.6</version>
</dependency>

<!-- ognl表达式 -->
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.15</version>
</dependency>
</dependencies>

<build>

<!--注意,这里需要添加 resources 标签。-->
<plugins>

<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<!--tomcat的插件名, tomcat7-maven-plugin, 用的是tomcat7版本 -->
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8026</port> <!--tomcat的端口号 -->
<path>/ssm</path> <!--tomcat的项目名 -->
<uriEncoding>UTF-8</uriEncoding> <!-- 防止get 提交时乱码 -->
</configuration>
</plugin>
</plugins>
</build>
</project>

所拥有的 jar包 有:

二.四 通过MyBatis的逆向工程,生成实体类和接口

运行 MyBatis的逆向工程, 将 ssm 数据库中的 user 表 逆向生成相应的实体类 User.java 和 UserExample.java

并放置到 src/main/java/com/yjl/pojo 里面。

将 UserMapper.java 和 UserMapper.xml 放置到 src/main/java/com/yjl/mapper 里面。

Maven整合SSM项目(七)_spring_04


Maven整合SSM项目(七)_Maven中SSM框架的依赖_05

二.五 创建各个 配置文件,将各自框架的 配置信息放置进去

配置文件 要放置在 src/main/resources 里面。

Maven整合SSM项目(七)_spring_06

1 . 数据库 db.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=abc123

2 . 日志文件 log4j.properties

### 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} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, stdout

## 配置MyBatis的级别
log4j.logger.com.yjl.mapper = debug

3 .mybatis 配置文件 SqlMapConfig.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>
<settings>
<!-- 设置配置文件 -->
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
<!-- 控制懒加载的 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
<!-- 设置日志为 log4j -->
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 配置别名 -->
<typeAliases>
<!-- 定义包的形式 ,可以多个-->
<package name="com.yjl.pojo"/>
</typeAliases>

<!-- 放置在别名之后,环境之前 -->
<plugins>
<!-- 分页插件,引入拦截器 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 指定数据库为mysql,虽然会自动监测。 -->
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>

</configuration>

4 . springmvc 的配置文件

<?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/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.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 ">
<!-- 配置的是注解的,重写视图解析器 -->
<context:component-scan base-package="com.yjl.action"></context:component-scan>

<!--配置静态资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/image/" mapping="/image/**"></mvc:resources>

<!-- 设置fastjson的配置方案 -->
<mvc:annotation-driven>
<!-- 设置不使用默认的消息转换器 -->
<mvc:message-converters register-defaults="false">
<!-- 配置Spring的转换器 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<!-- 配置fastjson中实现HttpMessageConverter接口的转换器 -->
<bean id="fastJsonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!-- 加入支持的媒体类型:返回contentType -->
<property name="supportedMediaTypes">
<list>
<!-- 这里顺序不能反,一定先写text/html,不然ie下会出现下载提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<!-- 可添加其他的属性来扩展功能,如日期 -->
<property name="features">
<list>
<!-- 默认的意思就是不配置这个属性,配置了就不是默认了 -->
<!-- 是否输出值为null的字段 ,默认是false-->
<value>WriteMapNullValue</value>

<value>WriteNullNumberAsZero</value>
<value>WriteNullListAsEmpty</value>
<value>WriteNullStringAsEmpty</value>
<value>WriteNullBooleanAsFalse</value>
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

<!-- 视图解析器 -->
<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 . spring 的配置文件dao 层 applicationContext-dao.xml

<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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置数据源 ,dbcp -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
</bean>
<!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
<property name="basePackage" value="com.yjl.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>

6 . springmvc 的配置文件 tx 事务层 applicationContext-tx.xml

<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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- 事务管理器
对mybatis操作数据库事务控制,spring使用jdbc的事务控制类
-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源
dataSource在applicationContext-dao.xml中配置了
-->
<property name="dataSource" ref="dataSource"/>
</bean>

<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<!--列举常见的方法形式-->
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="new*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="count*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- aop -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.yjl.service.impl.*.*(..))"/>
</aop:config>

</beans>

7 . spring的业务 层 applicationContext-service.xml

<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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!--添加事务-->
<!--
<context:component-scan base-package="com.yjl.action"></context:component-scan>
-->
<bean id="userService" class="com.yjl.service.impl.UserServiceImpl"></bean>

</beans>

二.六 web.xml 核心配置 WEB-INF 文件下

web.xml

<!-- 启动spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 乱码过滤器 -->
<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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 隐藏域方法 -->
<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>

<!--前端控制 器 -->
<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:spring/springmvc.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>

二.八 service层及其实现类 UserServiceImpl

UserService.java 接口: 基本与 UserMapper.java 接口一致

package com.yjl.service;

import java.util.List;

import com.yjl.pojo.User;
import com.yjl.pojo.UserExample;

/**
@author:岳泽霖
@date: 2019年9月9日 下午7:40:35
@Description 类的相关描述
*/
public interface UserService {
int countByExample(UserExample example);

int deleteByExample(UserExample example);

int deleteByPrimaryKey(Integer id);

int insert(User record);

int insertSelective(User record);

List<User> selectByExample(UserExample example);

User selectByPrimaryKey(Integer id);

int updateByExampleSelective( User record,UserExample example);

int updateByExample(User record, UserExample example);

int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
//根据sql语句进行相应的查询
List<User> pageExample(int limit, int offset);
}

UserServiceImpl.java 实现类

package com.yjl.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.yjl.mapper.UserMapper;
import com.yjl.pojo.User;
import com.yjl.pojo.UserExample;
import com.yjl.service.UserService;

/**
@author:岳泽霖
@date: 2019年9月9日 下午7:40:49
@Description 类的相关描述
*/
//注意,此时用的是注解的形式
@Service
public class UserServiceImpl implements UserService{

@Autowired
private UserMapper userMapper;

@Override
public int countByExample(UserExample example) {
return userMapper.countByExample(example);
}

@Override
public int deleteByExample(UserExample example) {
return userMapper.deleteByExample(example);
}

@Override
public int deleteByPrimaryKey(Integer id) {
return userMapper.deleteByPrimaryKey(id);
}

@Override
public int insert(User record) {
return userMapper.insert(record);
}

@Override
public int insertSelective(User record) {
return userMapper.insertSelective(record);
}

@Override
public List<User> selectByExample(UserExample example) {
return userMapper.selectByExample(example);
}

@Override
public User selectByPrimaryKey(Integer id) {
return userMapper.selectByPrimaryKey(id);
}

@Override
public int updateByExampleSelective(User record, UserExample example) {
return userMapper.updateByExampleSelective(record,example);
}

@Override
public int updateByExample(User record, UserExample example) {
return userMapper.updateByExample(record,example);
}

@Override
public int updateByPrimaryKeySelective(User record) {
return userMapper.updateByPrimaryKeySelective(record);
}

@Override
public int updateByPrimaryKey(User record) {
return userMapper.updateByPrimaryKey(record);
}

@Override
public List<User> pageExample(int page, int rowNum) {
PageHelper.startPage(page, rowNum);
UserExample example=new UserExample();
return userMapper.selectByExample(example);
}

}

二.九 UserAction 控制类

package com.yjl.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yjl.pojo.User;
import com.yjl.service.UserService;

/**
@atuhor:岳泽霖
@Description: 类描述
*/
@Controller
@RequestMapping(value="/user")
public class UserAction {
@Autowired
private UserService userService;
//转到登录的页面
@RequestMapping(value="toLogin")
public String toLogin(Model model){
model.addAttribute("user",new User());
return "user/login";
}
//一定不要忘记添加 produces 属性。 添加时,方法为POST
@RequestMapping(value="add",method=RequestMethod.POST,produces={"application/json"})
public @ResponseBody Map<String,Object> add(User user){
userService.insert(user);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("request_status",true);
return resultMap;
}
//修改时,方法为PUT
@RequestMapping(value="edit/{id}",method=RequestMethod.PUT,produces={"application/json"})
public @ResponseBody Map<String,Object> edit(User user){
userService.updateByPrimaryKeySelective(user);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("request_status",true);
return resultMap;
}
//删除时,方法用DELETE
@RequestMapping(value="deleteById/{id}",method=RequestMethod.DELETE,produces={"application/json"})
public @ResponseBody Map<String,Object> deleteById(@PathVariable(value="id") int id){
userService.deleteByPrimaryKey(id);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("request_status",true);
return resultMap;
}
//查询时,用GET
@RequestMapping(value="findById/{id}",method=RequestMethod.GET,produces={"application/json"})
public @ResponseBody Map<String,Object> findById(@PathVariable(value="id") int id){
User user=userService.selectByPrimaryKey(id);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("request_status",true);
resultMap.put("user",user);
return resultMap;
}
//查询时,用GET
@RequestMapping(value="findAll",method=RequestMethod.GET,produces={"application/json"})
public @ResponseBody Map<String,Object> findAll(){
List<User> userList=userService.pageExample(1,10);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("request_status",true);
resultMap.put("userList",userList);
return resultMap;
}
}

二.十 前端页面 login.jsp

在WEB-INF 下创建 jsp/user/ login.jsp 页面。 不要忘记在 js里面放置 jquery.js

Maven整合SSM项目(七)_Maven中resources的用法_07

login.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">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-2.1.1.min.js"></script>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<title>展示</title>
</head>
<body>
<h2>两个蝴蝶飞,Maven整合SSM框架使用</h2>
<form:form commandName="user" type="post">
<button type="button" id="add" onclick="addJson()">添加</button><br/>
<button type="button" id="edit" onclick="editJson()">修改</button><br/>
<button type="button" id="delete" onclick="delJson()">删除</button><br/>
<button type="button" id="findById" onclick="findByIdJson()">查询id></button><br/>
<button type="button" id="findAll" onclick="findAllJson()">查询全部</button><br/>
<div id="showId"> 展示的信息</div>
</form:form>

<script>
function addJson(){
jsonAjax("add","add","id=10&name=精灵妹&password=1234&sex=女&age=24&description=一个快乐的精灵&_method=POST");
}
function editJson(){
jsonAjax("edit","edit/10","id=10&name=精灵妹&description=一个快乐的精灵哈哈&_method=PUT");
}
function delJson(){
jsonAjax("delete","deleteById/10","_method=DELETE");
}
function findByIdJson(){
jsonAjax("findById","findById/10","_method=GET");
}
function findAllJson(){
jsonAjax("findAll","findAll","_method=GET");
}
function jsonAjax(sign,url,data){
var message="";
switch(sign){
case "add":{
message="添加成功";
break;
}
case "edit":{
message="修改成功";
break;
}
case "delete":{
message="删除成功";
break;
}
case "findById":{
message="查询单个成功";
break;
}
case "findAll":{
message="查询全部成功";
break;
}
}

$.ajax({
type:"post",
url:url, //注意请求路径
data:data,
success:function(resultData){
if(resultData.request_status){
//清空
$("#showId").empty();
//追加
$("#showId").append(message+"<br/>");

if(sign=="findById"){
var data=resultData.user;
var str="<table><tr><th>编号</th><th>姓名</th><th>描述</th></tr>";
str+="<tr>";
str+="<td>"+data.id+"</td>";
str+="<td>"+data.name+"</td>";
str+="<td>"+data.description+"</td>";
str+="</tr>";
str+="</table>";
$("#showId").append(str);
}
if(sign=="findAll"){
var data=resultData.userList;
var str="<table><tr><th>编号</th><th>姓名</th><th>描述</th></tr>";
$.each(data,function(idx,item){
str+="<tr>";
str+="<td>"+item.id+"</td>";
str+="<td>"+item.name+"</td>";
str+="<td>"+item.description+"</td>";
str+="</tr>";
})
str+="</table>";
$("#showId").append(str);
}
}
}
})
}
</script>
</body>
</html>

二.十 一 运行Maven ,观察错误

选中 SSM 项目, 右键 运行方式, 选择 Maven build (注意,现在开始就不需要 … 了), 输入命令 clean tomcat7:run

Maven整合SSM项目(七)_maven_08

观察控制台,发现没有报错。 这点与 SSH框架是不同的。

输入网址: http://localhost:8026/ssm/user/toLogin , 进行到显示的页面:

Maven整合SSM项目(七)_Maven整合SSM框架_09

这个时候,仍然是没有报错的。

点击查看全部的按钮, 这个时候观察控制台

Maven整合SSM项目(七)_Maven中resources的用法_10

报错了。 说没有找到 com.yjl.mapper.UserMapper.selectByExample
实际上 连 com.yjl.mapper.UserMapper 都没有找到, 即 com/yjl/mapper/UserMapper.xml 没有找到

与 SSH 项目时,问题是一致的。

可以与 SSH处理时一致, 在src/main/resources/ 目录下创建 一个 com/yjl/mapper 文件夹, 将UserMapper.xml 放置到这里面,可以正常的运行。

但现在,在SSM 框架里面,我们换一种做法。 直接 在pom.xml 中进行添加。

二.十二 解决 找不到 UserMapper.xml 的错误

在pom.xml 文件中, 在 <build> </build> 节点里面添加 resources 节点进行添加。

<build>
<resources>
<!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
<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>
<!--下面是 tomcat7的配置-->

</build>

这样,便可以了。

二.十三 重新运行命令 clean tomcat7:run, 进行验证

注意,这个时候点击的是 Maven build , 而不是 Maven build…

Maven build 可以直接记录上一次的操作,不用在重新输入命令了,非常方便。

重新输入网址: http://localhost:8026/ssm/user/toLogin

点击查看全部按钮, 发现控制台没有报错,页面可以正常显示。

Maven整合SSM项目(七)_maven_11


控制台打印:

Maven整合SSM项目(七)_Maven整合SSM框架_12

说明,分页插件是成功的。

二.十四 验证其他操作是否成功

点击添加按钮,

Maven整合SSM项目(七)_spring_13

再次点击查看全部

Maven整合SSM项目(七)_spring_14

点击修改按钮

Maven整合SSM项目(七)_Maven中resources的用法_15

再次点击查看全部

Maven整合SSM项目(七)_spring_16

点击查询 id按钮

Maven整合SSM项目(七)_maven_17

点击删除按钮

Maven整合SSM项目(七)_Maven中resources的用法_18

再次点击查看全部

Maven整合SSM项目(七)_Maven中resources的用法_19

是正确的。

二.十五 不合理的解决

仔细观察上面的代码和构成,会发现还是有很多不合理的地方。 如 pom.xml 中版本号的处理, dao,service,action 中并没有分模块开发等。

这些缺点将在下一个章节进行解决。

谢谢!!!