搭建SSM+Mysql纯用户管理demo系统
学习SSM框架有两个难点: 1、从0到1搭建SSM框架,各种配置比较头疼 2、好多同学为了学习框架,下载了好多SSM的系统,但是功能太复杂,难以看到框架的核心东西 基于上面两点,我将功能点简化,只留下登录、用户管理模块(增删改查),让大家可以将重点放在SSM框架本身上来,更容易去研究和学会SSM框架。
详细搭建流程(三大配置)
在配置文件说明之前,我们以三层架构的角度看一下SSM框架在项目中所在的位置: 三层框架: 主要分为控制层(SpringMVC)、业务逻辑层(Service)、数据库层(Dao),三层结构作用主要是为了代码解耦,让业务功能实现起来更加清晰。我们可以注意到,与SSH相比,SpringMVC和Structs作用一样,也是servlet控制层。 那么SSM对应的在三层框架中的作用是什么呢,SpringMVC就相当于控制层(主要是Action);Mybatis相当于Dao数据库持久化层(Mybatis和Hibernate相比,Hibernate是全自动化的,不仅可以将数据库字段与成员变量映射,还把sql语句全部封装,不用自己写SQL,而Mybatis则需要自己手动写SQL,这样来说就比较灵活一些,自己管理SQL可以提高执行效率);Spring相当于一个大管家,它的作用也是为了代码的解耦,主要作用一个是IOC(注册service、controller、dao的对象)、另一个是AOP(切面编程,比如进行事务配置)。
1、创建空白的javaee项目,并且自己做好分包,这一步就略过了
2、springMvc配置:springMVC-servlet.xml
<?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: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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<context:component-scan base-package="com.code2life.*.controller"></context:component-scan>
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<mvc:resources location="/static/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/static/fonts/" mapping="/fonts/**"></mvc:resources>
<mvc:resources location="/static/img/" mapping="/img/**"></mvc:resources>
<mvc:resources location="/static/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/static/layui/" mapping="/layui/**"></mvc:resources>
<bean id="jspInternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>
springMVC也是属于spring框架的一种技术,它的作用和structs一样,处于控制层,即用来处理前后端交互的。 这里我们使用了注解,其实本质上和手动注册action一样,配置文件通过扫描包,来让项目运行时识别注解的位置。
我们可以看一下常用的注解:@Controller、@Autowired、@RequestMapping
@Controller是用来声明这里是controller层,@Autowired用来注册内部的成员变量、@RequestMapping是用来定义路由跳转地址。 (具体的大家可以看看spring注解部分,这里不做过多的讲解)
3、spring配置:applicationContext.xml
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<context:component-scan base-package="com.code2life.ssm.dao,com.code2life.ssm.service,com.code2life.ssm.orm"></context:component-scan>
<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/frameDemo?useUnicode=true&characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.code2life.ssm.orm"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
由于这里将spring和Mybatis进行了整合,所以这两个都放在了一个配置文件中。
同样的由于项目中使用了注解,所以spring的配置文件中配置了扫描包下面的文件来自动注册javabeans.同时,配置文件中配置了数据库的连接信息、事务配置。
最重要的是,spring配置文件中将mybatis的映射文件进行了配置,以便于项目中可以用mybatis的映射文件进行数据持久化。 我们来看下mybatis的映射文件: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.code2life.ssm.orm.UserMapper" >
<resultMap id="BaseResultMap" type="com.code2life.ssm.domain.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="pass_word" property="passWord" jdbcType="VARCHAR" />
<result column="real_name" property="realName" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="role" property="role" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, user_name, pass_word, real_name, age, `role`
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.code2life.ssm.domain.User" >
insert into user (user_name, pass_word, real_name,
age, `role`)
values (#{userName,jdbcType=VARCHAR}, #{passWord,jdbcType=VARCHAR}, #{realName,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER}, #{role,jdbcType=INTEGER})
<selectKey resultType="java.lang.Integer" keyProperty="id" >
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
<insert id="insertSelective" parameterType="com.code2life.ssm.domain.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="userName != null" >
user_name,
</if>
<if test="passWord != null" >
pass_word,
</if>
<if test="realName != null" >
real_name,
</if>
<if test="age != null" >
age,
</if>
<if test="role != null" >
`role`,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
</if>
<if test="passWord != null" >
#{passWord,jdbcType=VARCHAR},
</if>
<if test="realName != null" >
#{realName,jdbcType=VARCHAR},
</if>
<if test="age != null" >
#{age,jdbcType=INTEGER},
</if>
<if test="role != null" >
#{role,jdbcType=INTEGER},
</if>
</trim>
<selectKey resultType="java.lang.Integer" keyProperty="id" >
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.code2life.ssm.domain.User" >
update user
<set >
<if test="userName != null" >
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="passWord != null" >
pass_word = #{passWord,jdbcType=VARCHAR},
</if>
<if test="realName != null" >
real_name = #{realName,jdbcType=VARCHAR},
</if>
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
<if test="role != null" >
`role` = #{role,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.code2life.ssm.domain.User" >
update user
set user_name = #{userName,jdbcType=VARCHAR},
pass_word = #{passWord,jdbcType=VARCHAR},
real_name = #{realName,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
`role` = #{role,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="findUserListByPage" resultMap="BaseResultMap">
select * from user
<if test="start!=null and limit!=null">
limit #{start},#{limit}
</if>
</select>
<select id="countUser" resultType="int">
select count(*) from user
</select>
<select id="findUserByNameAndPassWord" parameterType="map" resultMap="BaseResultMap">
select * from user where user_name = #{userName} and pass_word = #{passWord}
</select>
</mapper>
最后这些配置文件最好放置在src目录下:
详细搭建流程(代码部分)
1、用户实体类映射:UserMapper.java
package com.code2life.ssm.orm;
import com.code2life.ssm.domain.User;
import com.code2life.ssm.vo.Page;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List<User> findUserListByPage(Page page);
int countUser();
List<User> findUserByNameAndPassWord(@Param("userName") String userName, @Param("passWord") String passWord);
}
2、service层:UserService.java
package com.code2life.ssm.service;
import com.code2life.ssm.domain.User;
import com.code2life.ssm.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.code2life.ssm.dao.AllDao;
import java.util.List;
@Service("userinfoService")
public class UserService {
@Autowired
private AllDao allDao;
public List<User> queryUserList(Page page){
return allDao.getUserDao().findUserListByPage(page);
}
public int countUser() {
return allDao.getUserDao().getUserCount();
}
public void deleteUser(Integer id) {
allDao.getUserDao().deleteUser(id);
}
public User queryUserByPK(Integer id) {
User user = allDao.getUserDao().findUserByPK(id);
return user;
}
public void updateUser(User user) {
allDao.getUserDao().updateUser(user);
}
public void addUserInfo(User user){
System.out.println("allDao.hashCode = " + allDao.hashCode());
System.err.println("Service层获取到插入的记录---》" + user.toString());
allDao.getUserDao().addUser(user);
}
public boolean loginCheck(String userName, String passWord) {
User user = allDao.getUserDao().findUserByUserNameAndPassWord(userName, passWord);
if (user != null) {
return true;
} else {
return false;
}
}
}
3、action控制层:UserAction.java
package com.code2life.ssm.controller;
import java.lang.reflect.Method;
import java.util.List;
import com.code2life.ssm.domain.User;
import com.code2life.ssm.service.AllService;
import com.code2life.ssm.vo.Page;
import com.code2life.ssm.vo.RespEntity;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
@Transactional
public class UserController extends BaseAction {
@Autowired
private AllService allService;
@RequestMapping("/goUserMange")
public ModelAndView goUserMange(Model model) {
ModelAndView mav = new ModelAndView("user-manage");
return mav;
}
@RequestMapping(value = "/user/list", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json;charset=UTF-8")
@ResponseBody
public String getUserList(Page page) {
int count = allService.getUserService().countUser();
List<User> list = allService.getUserService().queryUserList(page);
page.caculatestart();
RespEntity respEntity = new RespEntity(0, "成功");
respEntity.setCount(count);
respEntity.setData(list);
Gson gson = new Gson();
return gson.toJson(respEntity);
}
@RequestMapping("/user/delete")
public ModelAndView delstu(Integer id) {
allService.getUserService().deleteUser(id);
ModelAndView mav = new ModelAndView("user-manage");
return mav;
}
@RequestMapping("/goUpdateUser")
public String goUpdate(Integer id,Model model) {
User user = allService.getUserService().queryUserByPK(id);
model.addAttribute("user",user);
return "user-update";
}
@RequestMapping(value = "/user/update", method = RequestMethod.POST)
public String updateUser(Integer id, User user) {
user.setId(id);
allService.getUserService().updateUser(user);
ModelAndView mav = new ModelAndView("user-manage");
return "user-manage";
}
@RequestMapping("/goAddUser")
public ModelAndView goAddUser(Model model) {
ModelAndView mav = new ModelAndView("user-add");
return mav;
}
@RequestMapping(value = "/user/add")
public String addUserInfo(User user) {
this.getAllService().getUserService().addUserInfo(user);
return "user-manage";
}
}
到这里简单的一个SSM的用户管理系统就完成了,业务逻辑只有增删改查,自己运行起来后,还可以自己去拓展实现新的模块,这样也可以进一步消化框架的逻辑。
系统功能界面
总结
本次SSM+mysql用户管理框架我已经将代码整理好,并且写了详细的框架搭建流程的word文档以及前后端数据交互的流程,如果需要完整的demo,可以加博主V:(Code2Life2)
写博客不易,觉得写得不错,记得一键三连!
|