SSM 框架整合
1.技术环境说明
1.1.服务端技术说明
Web服务器:tomcat
数据库服务器:mysql
服务端技术框架:SpringMVC + Spring + Mybatis
……
1.2.客户端技术说明
HTML,CSS,JavaScript
JQuery
…..
2.技术整合
2.1.创建Maven Web项目
创建Maven Web项目(CGB-SSM-01)
生成项目的web.xml配置文件
2.2.整合Spring MVC
输入控制对象是直接与用户输入相关的对象
添加Spring MVC依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
配置Spring MVC核心控制器
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
添加spring-configs.xml配置文件
在resource目录中添加此如下配置文件模板
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd" >
</beans>
在配置文件中配置mvc
<!-- 自动扫描该包 -->
<context:component-scan base-package="com.jt" />
<!—启用MVC注解-->
<mvc:annotation-driven />
<!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp"></property>
</bean>
测试
编写控制器,验证MVC环境
@Controller
@RequestMapping("/role/")
public class SysRoleController {
@RequestMapping("roleUI")
public String listUI(){
return "sys/roles";
}
}
在WEB-INF下的pages/sys目录下创建role.jsp文件
在浏览器输入http://localhost:8080/SSM-ch /listUI.do检测是否能够到达控制器并跳转到
/WEB-INF/pages/sys/role.jsp
2.3.整合JSON对象转换
在spring-configs.xml文件中添加JSON依赖
添加Jackson依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.5</version>
</dependency>
在需要返回JSON对象的方法上使用@ResponseBody注解,例如
@RequestMapping("doTestJackson")
@ResponseBody
public Map<String,Object> doTestJackson(){
Map<String,Object> map=new HashMap<String,Object);
map.put(“id”,100);
map.put(“name’,101);
return map;
}
打开浏览器测试
http://localhost:8080/CGB-SSM-01/role/doTestJackson.do
2.4.整合DRUID连接池对象
DRUID 是阿里推出的一个能够有效处理高并发问题的连接池。
添加DRUID依赖(spring-configs.xml)
添加mysql驱动依赖(不要选5.1.6版本)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
添加druid依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.23</version>
</dependency>
添加config.properties
在resource目录下添加config.properties文件,其内容
如下
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=root
在spring-configs.xml 中配置DRUID
加载properties文件:
<util:properties id="cfg" location="classpath:config.properties"/>
配置DRUID数据源
<!--配置DruidDataSource连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close" init-method="init" lazy-init="true">
<property name="driverClassName" value="#{cfg.driver}" />
<property name="url" value="#{cfg.url}" />
<property name="username" value="#{cfg.username}" />
<property name="password" value="#{cfg.password}" />
</bean>
编写连接池单元测试
添加Junit依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
编写测试类
@Test
public void testPool() {
ApplicationContext ctx=
new ClassPathXmlApplicationContext("spring-configs.xml");
DruidDataSource dataSource=(DruidDataSource)ctx.getBean("dataSource");
System.out.println(dataSource);
Assert.assertNotEquals(dataSource, null);
}
2.5.整合MyBatis框架
添加MyBatis依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
在比较新的版本中通常还需要如下两个依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
在spring-configs.xml 配置文件添加如下内容
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" >
<list><value>classpath:mapper/*.xml</value></list>
</property>
</bean>
<!-- 扫描DAO接口所在包,Spring会自动查找其下的dao
接口,然后为接口创建代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.project.**.dao "/>
</bean>
编写单元测试
@Test
public void testSessionFactory() {
ApplicationContext ctx=
new ClassPathXmlApplicationContext("spring-configs.xml");
Object sessionFactory=ctx.getBean("sqlSessionFactory");
System.out.println(sessionFactory);
Assert.assertNotEquals(sessionFactory, null);
}
2.6.整合Log4J输出
目的是实现mybati SQL日志的输出便于调试跟踪(扩展实现)
添加log4J依赖:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
添加配置文件(log4j.properties)
log4j.rootLogger=INFO,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
log4j.logger.com.mybatis3=DEBUG
log4j.logger.com.jt=DEBUG//注意包的路径是自己的Javabean路径
添加配置文件(mybatis-configs.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>
<!-- mybatis控制台LOG输出 -->
<setting name="logImpl" value="LOG4J" />
</settings>
<!-->配置别名(此处通过设置包名来默认所有id为小写首字母)
<typeAliases>
<package name="com.project.sys.entity"/>
</typeAliases>
</configuration>
修改配置文件spring-configs.xml添加mybatis-configs.xml的配置
…
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-configs.xml"></property>
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations">
<list>
<value>classpath:mapper/*.xml</value>
</list>
</property>
</bean>
…
3.用户角色管理实践
3.1.用户角色管理概述
京淘项目中有一个权限管理子系统,此系统中包含用户管理,角色管理,菜单管理,组织机构管理等,
具体这些模块业务关系,后续分析,本节课首先从技术角度实现SSM技术的基本整合,实现上以角色管理模块为切入点。
项目基本架构图:
3.2.创建角色表
创建数据库
Create database jt_sys default character set utf8;
Use jt_sys
CREATE TABLE `sys_roles` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL COMMENT '角色名称',
`note` varchar(500) DEFAULT NULL COMMENT '备注',
`createdTime` datetime DEFAULT NULL COMMENT '创建时间',
`modifiedTime` datetime DEFAULT NULL COMMENT '修改时 间',
`createdUser` varchar(20) DEFAULT NULL COMMENT '创建 用户',
`modifiedUser` varchar(20) DEFAULT NULL COMMENT '修改用户',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8 COMMENT='角色'
添加测试数据
insert into sys_roles
values (null,'role-a','role-a ...',now(),now(),'admin', 'admin');
insert into sys_roles
values (null,'role-b','role-b ...',now(),now(),'admin', 'admin');
3.3.创建角色实体
这个实体类(Entity Bean)属性要与sys_roles表中字段有对应关系。
实体类特点:
1)实现序列化接口并添加序列化版本id
2)属性与表中字段有一一对应关系
3)类中定义无参的构造函数
4)类中基于属性添加set和get方法
5)建议重写toString方法,便于测试输出其数据
实体类应用场景:
1)对象关系映射(ORM):从表中取出的每条记录可以映射为这样的一个对象
2)封装页面数据:在控制层通过这样对象接收页面数据
3)…
package com.jt.sys.entity;
import java.io.Serializable;
import java.util.Date;
public class implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String note;
private Date createdTime;
private Date modifiedTime;
private String createdUser;
private String modifiedUser;
//set/get
}
3.4.创建角色DAO接口
实际项目中我们会基于DAO接口访问数据库,在本项目中我们只需要
定义DAO接口,不需要定义此接口的实现类。
package com.jt.sys.dao;
import java.util.List;
import com.jt.sys.entity.SysRole;
public interface SysRoleDao {
List<SysRole> findObjects();
int insertObject(SysRole entity);
//other methods ...
}
3.5.创建DAO接口映射文件
在resources/mapper目录下创建SysRoleMapper.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.jt.sys.dao.SysRoleDao">
<!-- 查询所有角色信息 -->
<select id="findObjects"
resultType="sysRole">
select *
from sys_roles
order by createdTime desc
</select>
<!-- 向表中写入数据 -->
<insert id="insertObject">
insert into sys_roles
(name,note,createdTime,modifiedTime,
createdUser,modifiedUser)
values
(#{name},#{note},now(),now(),
#{createdUser},#{modifiedUser})
</insert>
</mapper>
3.6.创建角色Service接口及实现类
定义service接口,在此接口的实现类中负责具体业务的处理。
package com.jt.sys.service;
import java.util.List;
import com.jt.sys.entity.SysRole;
public interface SysRoleService {
List<SysRole> findObjects();
int saveObject(SysRole entity);
}
定义service接口及实现类
package com.jt.sys.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jt.sys.dao.SysRoleDao;
import com.jt.sys.entity.SysRole;
import com.jt.sys.service.SysRoleService;
@Service
public class SysRoleServiceImpl implements SysRoleService {
@Autowired
private SysRoleDao sysRoleDao;
@Override
public List<SysRole> findObjects() {
//log,transaction
return sysRoleDao.findObjects();
}
@Override
public int saveObject(SysRole entity) {
//log,transaction
return sysRoleDao.insertObject(entity);
}
}
3.7.基于service创建单元测试
实际项目中一般,都会对每个业务都要进行单元测试
package com.jt.test;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jt.sys.entity.SysRole;
import com.jt.sys.service.SysRoleService;
public class TestSysRoleService {
private ClassPathXmlApplicationContext ctx;
@Before
public void init(){
ctx=new ClassPathXmlApplicationContext(
"spring-configs.xml");
}
@Test
public void testFindObjects(){
SysRoleService rs=
ctx.getBean("sysRoleServiceImpl",
SysRoleService.class);
List<SysRole> list=rs.findObjects();
System.out.println(list);
}
@Test
public void testSaveObject(){
SysRoleService rs=
ctx.getBean("sysRoleServiceImpl",
SysRoleService.class);
SysRole e=new SysRole();
e.setName("role-c");
e.setNote("note-c ...");
e.setCreatedUser("admin");
e.setModifiedUser("admin");
int rows=rs.saveObject(e);
Assert.assertEquals(1, rows);
System.out.println("save ok,rows="+rows);
}
@After
public void destory(){
ctx.close();
}
}
3.8.创建角色Controller类
修改com.jt.sys.controller包中的controller类,对对应方法中访问service,然后将数据显示在页面上。
package com.jt.sys.controller;
@Controller
@RequestMapping("/role/")
public class SysRoleController {
@Autowired
private SysRoleService sysRoleService;
@RequestMapping("roleUI")
public String listUI(Model model){
List<SysRole> list=
sysRoleService.findObjects();
model.addAttribute("data",list);
return "sys/roles";
}//WEB-INF/pages/sys/roles.jsp
@RequestMapping("doSaveObject")
public String doSaveObject(SysRole entity,
Model model){
sysRoleService.saveObject(entity);
List<SysRole> list=
sysRoleService.findObjects();
model.addAttribute("data",list);
model.addAttribute("msg", "save ok");
return "sys/roles";
}
@RequestMapping("doFindObjects")
@ResponseBody
public List<SysRole> doFindObjects(){
return sysRoleService.findObjects();
}
}
3.9.修改roles.jsp文件
修改roles.jsp文件通过jstl标签库显示请求作用域数据,说明使用JSTL时首先要在项目中添加jstl依赖:
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
roles.jsp内容如下(文件中的时间处理可以暂时不写)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<style type="text/css">
ul li{list-style: none}
</style>
</head>
<body>
<%
java.util.Date date=new java.util.Date();
java.text.SimpleDateFormat sdf=
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr=sdf.format(date);
request.setAttribute("dateStr", dateStr);
%>
<h1>角色管理<%=dateStr%></h1>
<div>
<fieldset>
<legend>角色添加</legend>
<h2>${msg}</h2>
<form action="doSaveObject.do" method="post">
<ul>
<li>name:<input type="text" name="name"/>
<li>note:<input type="text" name="note"/>
</ul>
<ul>
<li><input type="submit" value="save"/>
</ul>
</form>
</fieldset>
</div>
<div>
<fieldset>
<legend>角色列表</legend>
<table width="100%" border="1" cellpadding="1" cellspacing="0">
<tr>
<th>id</th>
<th>name</th>
<th>note</th>
</tr>
<c:forEach items="${data}" var="item">
<tr>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.note}</td>
</tr>
</c:forEach>
</table>
</fieldset>
</div>
</body>
</html>
SSM框架之简单整合
最新推荐文章于 2024-05-19 14:26:23 发布