首页
IT
登录
6mi
u
盘
搜
搜 索
IT
使用maven,实现ssm(spring+springmvc+mybatis)三大框架的整合DEMO
使用maven,实现ssm(spring+springmvc+mybatis)三大框架的整合DEMO
xiaoxiao
2021-03-25
101
刚进一家新公司,要求使用ssm三大框架,而且这个组合是现在的主流,所以在整合的同时将步骤一步一步记录下来,方便以后的再次使用。
1.首先是建立一个Maven-project,具体操作请参考我的另一篇文章 点击这里
2. 然后导入maven依赖,这里将我的依赖列出如下
[html] view plain copy
<
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/maven-v4_0_0.xsd"
>
<
modelVersion
>
4.0.0
</
modelVersion
>
<
groupId
>
org.bb
</
groupId
>
<
artifactId
>
ssm
</
artifactId
>
<
packaging
>
war
</
packaging
>
<
version
>
0.0.1-SNAPSHOT
</
version
>
<
name
>
ssm Maven Webapp
</
name
>
<
url
>
http://maven.apache.org
</
url
>
<
dependencies
>
<!-- 单元测试 -->
<
dependency
>
<
groupId
>
junit
</
groupId
>
<
artifactId
>
junit
</
artifactId
>
<
version
>
4.10
</
version
>
<
scope
>
test
</
scope
>
</
dependency
>
<!-- Spring 相关依赖 -->
<
dependency
>
<
groupId
>
org.springframework
</
groupId
>
<
artifactId
>
spring-context
</
artifactId
>
<
version
>
4.1.3.RELEASE
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
org.springframework
</
groupId
>
<
artifactId
>
spring-beans
</
artifactId
>
<
version
>
4.1.3.RELEASE
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
org.springframework
</
groupId
>
<
artifactId
>
spring-webmvc
</
artifactId
>
<
version
>
4.1.3.RELEASE
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
org.springframework
</
groupId
>
<
artifactId
>
spring-jdbc
</
artifactId
>
<
version
>
4.1.3.RELEASE
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>
org.springframework
</
groupId
>
<
artifactId
>
spring-aspects
</
artifactId
>
<
version
>
4.1.3.RELEASE
</
version
>
</
dependency
>
<!-- Mybatis 依赖 -->
<
dependency
>
<
groupId
>
org.mybatis
</
groupId
>
<
artifactId
>
mybatis
</
artifactId
>
<
version
>
3.4.2
</
version
>
</
dependency
>
<!-- mybatis整合Spring -->
<
dependency
>
<
groupId
>
org.mybatis
</
groupId
>
<
artifactId
>
mybatis-spring
</
artifactId
>
<
version
>
1.3.0
</
version
>
</
dependency
>
<!-- Mysql 依赖 -->
<
dependency
>
<
groupId
>
mysql
</
groupId
>
<
artifactId
>
mysql-connector-Java
</
artifactId
>
<
version
>
5.1.6
</
version
>
</
dependency
>
<!-- log4j日志 依赖 -->
<
dependency
>
<
groupId
>
apache-log4j
</
groupId
>
<
artifactId
>
log4j
</
artifactId
>
<
version
>
1.2.15
</
version
>
</
dependency
>
<!-- JSP相关 -->
<
dependency
>
<
groupId
>
jstl
</
groupId
>
<
artifactId
>
jstl
</
artifactId
>
<
version
>
1.2
</
version
>
</
dependency
>
<
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
>
</
dependencies
>
<
build
>
<
finalName
>
ssm
</
finalName
>
<
plugins
>
<
plugin
>
<
groupId
>
org.mybatis.generator
</
groupId
>
<
artifactId
>
mybatis-generator-maven-plugin
</
artifactId
>
<
version
>
1.3.2
</
version
>
<
configuration
>
<
verbose
>
true
</
verbose
>
<
overwrite
>
true
</
overwrite
>
</
configuration
>
</
plugin
>
</
plugins
>
</
build
>
</
project
>
3
.然后在src/main/java下新建需要的package,如下图所示
各包的用途如下:controller-无需多说,放的是springmvc的controller文件
mode-放的实体类
service-业务层
service.impl-业务实现层
mapper-mybatis的操作数据库的接口文件,类似于dao层(这里需要注意src/main/resources下的目录,和org.bb.ssm.mapper包名一样)
4.此处我使用mybatis-generator自动生成映射类、dao、xml文件,具体做法是:现在pom.xml中引用mybatis-generator这个插件(前面我们已经引进),在src/main/resource下新建generatorConfig.xml,内容如下:
[html] view plain copy
<?
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
>
<!-- <properties resource="init.properties"/> -->
<!-- 指定数据库连接驱动地址 -->
<
classPathEntry
location
=
"D:\Program Files\apache-maven-3.3.9\repository\mysql\mysql-connector-java\5.1.6\mysql-connector-Java-5.1.6.jar"
/>
<!-- 一个数据库一个 context -->
<
context
id
=
"context1"
>
<
commentGenerator
>
<!-- 是否取消注释 -->
<
property
name
=
"suppressAllComments"
value
=
"true"
>
</
property
>
<!-- 是否生成注释代时间戳-->
<
property
name
=
"suppressDate"
value
=
"true"
>
</
property
>
</
commentGenerator
>
<!-- jdbc连接配置 -->
<
jdbcConnection
connectionURL
=
"jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=UTF-8"
driverClass
=
"com.mysql.jdbc.Driver"
password
=
"root"
userId
=
"root"
/>
<!-- 类型转换 -->
<
javaTypeResolver
>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<
property
name
=
"forceBigDecimals"
value
=
"false"
/>
</
javaTypeResolver
>
<!-- 生成实体类的地址 -->
<
javaModelGenerator
targetPackage
=
"org.bb.ssm.model"
targetProject
=
"D:\SXYC\workspace\ssm\src\main\java"
/>
<!-- 生成mapper.xml文件 -->
<
sqlMapGenerator
targetPackage
=
"org.bb.ssm.mapper"
targetProject
=
"D:\SXYC\workspace\ssm\src\main\resources"
/>
<!-- 生成mapxml对应的client 也就是接口dao -->
<
javaClientGenerator
targetPackage
=
"org.bb.ssm.mapper"
targetProject
=
"D:\SXYC\workspace\ssm\src\main\java"
type
=
"XMLMAPPER"
/>
<
table
schema
=
"ssm"
tableName
=
"userinfo"
domainObjectName
=
"UserInfo"
enableCountByExample
=
"false"
enableDeleteByExample
=
"false"
enableSelectByExample
=
"false"
enableUpdateByExample
=
"false"
>
<!-- domainObjectName 指定生成的类的名字 -->
</
table
>
</
context
>
</
generatorConfiguration
>
[html] view plain copy
5
.鼠标右击pom.xml,run as "Maven build" 在goals中输入命令:mybatis-generator:generate,即可自动生成相应文件。
6.下面开始配置spring与mybatis的整合配置--applicationContext-mybatis.xml,直接上配置:
[html] view plain copy
<?
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"
xmlns:tx
=
"http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
>
<!-- Mybatis 和 Spring的整合 -->
<!-- 1.数据源:DriverManagerDataSource -->
<
bean
id
=
"dataSource"
class
=
"org.springframework.jdbc.datasource.DriverManagerDataSource"
>
<
property
name
=
"driverClassName"
value
=
"com.mysql.jdbc.Driver"
>
</
property
>
<
property
name
=
"url"
value
=
"jdbc:mysql://localhost:3306/ssm"
>
</
property
>
<
property
name
=
"username"
value
=
"root"
>
</
property
>
<
property
name
=
"password"
value
=
"root"
>
</
property
>
</
bean
>
<!-- 2.Mybatis 的 SqlSession的工厂:SqlSessionFactoryBean dataSource引用数据源 Mybatis
定义数据源,同意加载配置 --
>
<
bean
id
=
"sqlSessionFactory"
class
=
"org.mybatis.spring.SqlSessionFactoryBean"
>
<
property
name
=
"dataSource"
ref
=
"dataSource"
>
</
property
>
<
property
name
=
"configLocation"
value
=
"classpath:mybatis-config.xml"
>
</
property
>
</
bean
>
<!-- 3. Mybatis自动扫描加载Sql映射文件/接口:MapperScannerConfigurer sqlSessionFactory
basePackage:指定sql映射文件/接口所在的包(自动扫描) --
>
<
bean
class
=
"org.mybatis.spring.mapper.MapperScannerConfigurer"
>
<
property
name
=
"basePackage"
value
=
"org.bb.ssm.mapper"
>
</
property
>
<
property
name
=
"sqlSessionFactory"
ref
=
"sqlSessionFactory"
>
</
property
>
</
bean
>
<!-- 4.事务管理:DataSourceTransactionManager dataSource 引用上面定义好的数据源 -->
<
bean
id
=
"txManager"
class
=
"org.springframework.jdbc.datasource.DataSourceTransactionManager"
>
<
property
name
=
"dataSource"
ref
=
"dataSource"
>
</
property
>
</
bean
>
<!-- 5.使用声明式事务:
transaction-manager
=
"txManager"
tx:advice 这种 是用 aop方式管理事物
annotation-driven 这种是注解方式管理事物 第一种方式,需要在spring配置文件配置一些参数 第二种方式,需要在 类里 加一些注解进行事物管理
用一种就行,没必须都用 --
>
<
tx:annotation-driven
transaction-manager
=
"txManager"
/>
</
beans
>
7.配置Mybatis的配置文件,mybatis官方文档推荐起名为mybatis-config.xml,这里遵循约定:
[html] view plain copy
<?
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
>
<!-- 配置打印 SQL 到控制台 以及懒加载 -->
<
settings
>
<
setting
name
=
"logImpl"
value
=
"STDOUT_LOGGING"
/>
<!-- 打开延迟加载的全局开关 -->
<
setting
name
=
"lazyLoadingEnabled"
value
=
"true"
/>
<
setting
name
=
"aggressiveLazyLoading"
value
=
"false"
/>
<
setting
name
=
"mapUnderscoreToCamelCase"
value
=
"true"
/>
</
settings
>
<!-- 为org.bb.ssm.mode.UserInfo 设置一个别名 UserInfo -->
<
typeAliases
>
<
typeAlias
type
=
"org.bb.ssm.model.UserInfo"
alias
=
"UserInfo"
/>
</
typeAliases
>
<
mappers
>
<
package
name
=
"org.bb.ssm.mapper"
/>
</
mappers
>
</
configuration
>
8.下来是springMVC的配置文件spring-MVC.xml:
[html] view plain copy
<?
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"
xmlns:tx
=
"http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
>
<!-- 开启注解 -->
<
mvc:annotation-driven
/>
<!-- 配置自定扫描包 -->
<
context:component-scan
base-package
=
"org.bb.ssm.controller"
/>
<
context:component-scan
base-package
=
"org.bb.ssm.service.Impl"
/>
<!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
<
bean
id
=
"viewResolver"
class
=
"org.springframework.web.servlet.view.InternalResourceViewResolver"
>
<
property
name
=
"prefix"
value
=
"/WEB-INF/view/"
>
</
property
>
<
property
name
=
"suffix"
value
=
".jsp"
>
</
property
>
</
bean
>
<!-- 处理静态资源 -->
<
mvc:default-servlet-handler
/>
</
beans
>
9.web.xml配置:
[html] view plain copy
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
<
web-app
version
=
"2.5"
xmlns
=
"http://java.sun.com/xml/ns/javaee"
xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation
="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
>
<!-- 加载Spring 容器配置 -->
<
listener
>
<
listener-class
>
org.springframework.web.context.ContextLoaderListener
</
listener-class
>
</
listener
>
<!-- 加载spring与mybatis的整合配置 -->
<
context-param
>
<
param-name
>
contextConfigLocation
</
param-name
>
<
param-value
>
classpath:applicationContext-mybatis.xml
</
param-value
>
</
context-param
>
<!-- 配置 springMVC 核心控制器 -->
<
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-MVC.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
>
<!-- 防止Spring内存溢出监听器 -->
<
listener
>
<
listener-class
>
org.springframework.web.util.IntrospectorCleanupListener
</
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
>
<!-- 配置HiddenHttpMethodFilter过滤器,把 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
>
<
welcome-file-list
>
<
welcome-file
>
index.jsp
</
welcome-file
>
</
welcome-file-list
>
</
web-app
>
9.log4j日志配置:
[html] view plain copy
### set log levels ###
log4j.rootLogger
=
info
, Console , D
#Console
log4j.appender.Console
=
org
.apache.log4j.ConsoleAppender
log4j.appender.Console.layout
=
org
.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern
=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet
=
INFO
log4j.logger.org.apache
=
INFO
log4j.logger.java.sql.Connection
=
INFO
log4j.logger.java.sql.Statement
=
INFO
log4j.logger.java.sql.PreparedStatement
=
INFO
#output2file
log4j.appender.D
=
org
.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File
=
D
\:/logs/log.log
log4j.appender.D.Append
=
true
log4j.appender.D.Threshold
=
INFO
\#\# \u00E8\u00BE\u0093\u00E5\u0087\u00BAinfo\u00E7\u00BA\u00A7\u00E5\u0088\u00AB\u00E4\u00BB\u00A5\u00E4\u00B8\u008A\u00E7\u009A\u0084\u00E6\u0097\u00A5\u00E5\u00BF\u0097
log4j.appender.D.layout
=
org
.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern
= %-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n
10.补贴上数据库的建表sql:
[html] view plain copy
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ssm` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `ssm`;
/*Table structure for table `userinfo` */
DROP TABLE IF EXISTS `userinfo`;
CREATE TABLE `userinfo` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(30) DEFAULT NULL,
`user_age` int(3) DEFAULT NULL,
`user_address` varchar(400) DEFAULT NULL,
PRIMARY KEY (`user_id`)
)
ENGINE
=
InnoDB
AUTO_INCREMENT
=
1
DEFAULT
CHARSET
=
utf8
;
11.配置到这里已经完成,启动项目访问欢迎页面,如果看到熟悉的Hello world 代表整合成功了。
12.创建业务层接口文件,UserInfoService.java 和 对应的实现类 UserInfoServiceImpl.java
[html] view plain copy
package org.bb.ssm.service;
import java.util.List;
import org.bb.ssm.model.UserInfo;
/**
* Dao层是和数据库打交道的,Service层会封装具体的业务。有点抽象.. e.g. 用户管理系统
* dao封装了用户的增删改查。而业务上要求批量删除用户,Service就可以封装出一个批量删除用户的功能
* ,但是实现只是循环调用dao的单个删除
* 此处没有特殊的业务需求,所以和dao层写的一模一样
*
* @author Administrator
*
*/
public interface UserInfoService {
List
<
UserInfo
>
findAll();
int deleteByPrimaryKey(Integer userId);
int insert(UserInfo record);
int insertSelective(UserInfo record);
UserInfo selectByPrimaryKey(Integer userId);
int updateByPrimaryKeySelective(UserInfo record);
int updateByPrimaryKey(UserInfo record);
}
[html] view plain copy
package org.bb.ssm.service.Impl;
import java.util.List;
import javax.annotation.Resource;
import org.bb.ssm.mapper.UserInfoMapper;
import org.bb.ssm.model.UserInfo;
import org.bb.ssm.service.UserInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
//可以消除xml中对bean的配置
@Service
// 此处使用spring的声明式事务,不在使用sqlsession和提交事务了
@Transactional
public class UserInfoServiceImpl implements UserInfoService {
@Resource
/**
* @Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,
* 而@Resource默认按 byName自动注入罢了。@Resource有两个属性是比较重要的,
* 分是name和type,Spring将@Resource注解的name属性解析为bean的名字,
* 而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,
* 而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,
* 这时将通过反射机制使用byName自动注入策略。 @Resource装配顺序
*
*1.如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
*2.
*如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
*3.
*如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
*4.
*如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;
*/
private UserInfoMapper mapper;
/**
* 查询UserInfo表所有数据
*/
@Override
public List
<
UserInfo
>
findAll() {
List
<
UserInfo
>
list
=
mapper
.findAll();
return list;
}
@Override
public int deleteByPrimaryKey(Integer userId) {
return mapper.deleteByPrimaryKey(userId);
}
@Override
public int insert(UserInfo record) {
return mapper.insert(record);
}
@Override
public int insertSelective(UserInfo record) {
return mapper.insertSelective(record);
}
@Override
public UserInfo selectByPrimaryKey(Integer userId) {
return mapper.selectByPrimaryKey(userId);
}
@Override
public int updateByPrimaryKeySelective(UserInfo record) {
return mapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(UserInfo record) {
return mapper.updateByPrimaryKey(record);
}
}
13.创建controller文件,UserInfoCotroller.java
[html] view plain copy
package org.bb.ssm.controller;
import java.util.List;
import java.util.Map;
import org.bb.ssm.model.UserInfo;
import org.bb.ssm.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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.RequestParam;
@Controller
@RequestMapping(
value
=
"/user"
)
public class UserInfoCotroller {
@Autowired
private UserInfoService userInfoService;
/**
* 得到所有用户信息
* @param map
* @return
*/
@RequestMapping(
value
=
"/getAllUser"
)
public String getAllUser(Map
<
String
, Object
>
map){
List
<
UserInfo
>
userList
=
userInfoService
.findAll();
map.put("ALLUSER", userList);
return "allUser";
}
/**
* 通过handler前往添加用户页面
* @param map
* @return
*/
@RequestMapping(
value
=
"/addUser"
,
method
=
RequestMethod
.GET)
public String addUser(Map
<
String
, Object
>
map){
//因为页面使用spring的form标签,其中属性modelAttribute需要存在bean 要不会报错
map.put("command", new UserInfo());
return "addUser";
}
/**
* 添加用户操作
* @param userinfo
* @return
*/
@RequestMapping(
value
=
"/addUser"
,
method
=
RequestMethod
.POST)
public String save(UserInfo userinfo){
int
result
=
userInfoService
.insert(userinfo);
System.out.println("添加用户的操作结果为:"+result);
return "redirect:/user/getAllUser";
}
/**
* 删除用户操作
* @param id
* @return
*/
@RequestMapping(
value
=
"/delete/{id}"
,
method
=
RequestMethod
.DELETE)
public String delete(@PathVariable(
value
=
"id"
) int id){
int
result
=
userInfoService
.deleteByPrimaryKey(id);
System.out.println("删除用户的操作结果为:"+result+"传递进来的id为:"+id);
return "redirect:/user/getAllUser";
}
/**
* 更新前先根据id找到用户信息,回显到页面上
* @param id
* @param map
* @return
*/
@RequestMapping(
value
=
"/detail/{id}"
,
method
=
RequestMethod
.GET)
public String input(@PathVariable(
value
=
"id"
) Integer id,Map
<
String
, Object
>
map){
map.put("command", userInfoService.selectByPrimaryKey(id));
return "addUser";
}
@ModelAttribute
public void getUserInfo(@RequestParam(
value
=
"userId"
,
required
=
false
) Integer id
,Map
<
String
, Object
>
map){
System.out.println("每个controller 方法都会先调用我哦");
if(id != null){
System.out.println("update 操作");
map.put("userInfo", userInfoService.selectByPrimaryKey(id));
}
System.out.println("insert 操作");
}
@RequestMapping(
value
=
"/addUser"
,
method
=
RequestMethod
.PUT)
public String update(UserInfo userinfo){
userInfoService.updateByPrimaryKey(userinfo);
return "redirect:/user/getAllUser";
}
}
14.展示页面:分别是allUser.jsp、addUser.jsp
[html] view plain copy
<
%@ page
language
=
"java"
contentType
=
"text/html; charset=utf-8"
pageEncoding
=
"utf-8"
%
>
<
%@ taglib
prefix
=
"c"
uri
=
"http://java.sun.com/jsp/jstl/core"
%
>
<!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
>
全部员工
</
title
>
<!--
SpringMVC 处理静态资源:
1. 为什么会有这样的问题:
优雅的 REST 风格的资源URL 不希望带 .html 或 .do 等后缀
若将 DispatcherServlet 请求映射配置为 /,
则 Spring MVC 将捕获 WEB 容器的所有请求, 包括静态资源的请求, SpringMVC 会将他们当成一个普通请求处理,
因找不到对应处理器将导致错误。
2. 解决: 在 SpringMVC 的配置文件中配置
<
mvc:default-servlet-handler
/>
--
>
<
script
type
=
"text/javascript"
src
=
"../scripts/jquery-1.9.1.min.js"
>
</
script
>
<
script
type
=
"text/javascript"
>
$(function(){
$(".delete").click(function(){
var
href
= $(this).attr("href");
$("form").attr("action", href).submit();
return false;
});
});
</
script
>
</
head
>
<
body
>
<
form
action
=
""
method
=
"post"
>
<
input
type
=
"hidden"
name
=
"_method"
value
=
"DELETE"
/>
</
form
>
<
c:choose
>
<
c:when
test
=
"${empty requestScope.ALLUSER}"
>
没有员工信息
</
c:when
>
<
c:otherwise
>
<
table
border
=
"1"
>
<
tr
>
<
th
>
编号
</
th
>
<
th
>
姓名
</
th
>
<
th
>
年龄
</
th
>
<
th
>
地址
</
th
>
<
th
>
操作
</
th
>
</
tr
>
<
c:forEach
items
=
"${requestScope.ALLUSER }"
var
=
"UserInfo"
>
<
tr
>
<
td
>
${UserInfo.userId }
</
td
>
<
td
>
${UserInfo.userName }
</
td
>
<
td
>
${UserInfo.userAge }
</
td
>
<
td
>
${UserInfo.userAddress }
</
td
>
<
td
>
<
a
class
=
"delete"
href
=
"${pageContext.request.contextPath }/user/delete/${UserInfo.userId}"
>
删除
</
a
>
<
a
href
=
"${pageContext.request.contextPath }/user/detail/${UserInfo.userId}"
>
更新
</
a
>
</
td
>
</
tr
>
</
c:forEach
>
</
table
>
</
c:otherwise
>
</
c:choose
>
</
body
>
</
html
>
[html] view plain copy
<
%@ 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
=
"form"
uri
=
"http://www.springframework.org/tags/form"
%
>
<!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
>
添加新员工
</
title
>
</
head
>
<
body
>
<
form:form
action
=
"${pageContext.request.contextPath }/user/addUser"
method
=
"post"
modelAttribute
=
"command"
>
<
c:if
test
=
"${command.userId != null }"
>
<
form:hidden
path
=
"userId"
/>
<
input
type
=
"hidden"
name
=
"_method"
value
=
"PUT"
/>
<
%-- 对于 _method 不能使用 form:hidden 标签, 因为 modelAttribute 对应的 bean 中没有 _method 这个属性 --%
>
<
%--
<
form:hidden
path
=
"_method"
value
=
"PUT"
/>
--%
>
</
c:if
>
userName :
<
form:input
path
=
"userName"
/>
<
br
>
<
br
>
userAge :
<
form:input
path
=
"userAge"
/>
<
br
>
<
br
>
userAddress :
<
form:input
path
=
"userAddress"
/>
<
br
>
<
br
>
<
input
type
=
"submit"
value
=
"提交"
/>
</
form:form
>
</
body
>
</
html
>
15.运行tomcat,访问http://localhost:8089/ssm/user/addUser 进入添加用户页面,输入用户信息
点击提交
点击更新(此处addUser.jsp使用了springmvc的 form标签,可以更方便的进行数据的回显):
点击提交(这里偷懒,将更新和添加放在一个页面了)
点击删除
最后附上项目的树状图:
到这里,ssm整合以及用户的crud功能已基本实现。
附上源码:源码下载(此处需要积分)
gitHub:免积分下载
如有不对,还请指正!
转载请注明原文地址: https://ju.6miu.com/read-20899.html
技术
最新回复
(
0
)