SSM框架搭建详细记录--非Maven--多模块--目录清晰

时间:2023-01-25 22:32:53

闲着没事总结下SSM框架搭建;现网上好多的SSM搭建框架教程的目录结构看上去都非常的乱,让我这个有强迫症的人来看,非常糟心,就想着自己总结个;

----------------------------------------------------------------------------------------------------------------------------------

我总结的这个搭建记录有一共用了2张数据库表;提供了两个访问链接;

                以下为最终结果

一个:http://localhost:8080/ssm/role/findAllRole

SSM框架搭建详细记录--非Maven--多模块--目录清晰

另一个:http://localhost:8080/ssm/user/findAllUser

SSM框架搭建详细记录--非Maven--多模块--目录清晰

--------------------------------------------------------------------------------------------------------------------------------

环境:eclipse   +      mysql

mysql共涉及到2张表

t_user表

CREATE TABLE `t_user` (
  `c_id` int(20) NOT NULL,
  `c_user_code` varchar(255) DEFAULT NULL,
  `c_user_name` varchar(255) DEFAULT NULL,
  `c_password` varchar(255) DEFAULT NULL,
  `c_age` int(20) DEFAULT NULL,
  PRIMARY KEY (`c_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

auth_role_t表

CREATE TABLE `auth_role_t` (
  `ROLE_ID` varchar(32) NOT NULL COMMENT '角色标识',
  `ROLE_CODE` varchar(32) NOT NULL COMMENT '角色编码',
  `ROLE_NAME` varchar(64) NOT NULL COMMENT '角色名称',
  `SUP_ROLE_ID` varchar(32) DEFAULT NULL COMMENT '顶层默认为*',
  `CREATE_BY` varchar(32) NOT NULL COMMENT '创建人',
  `CREATE_DATE` datetime NOT NULL COMMENT '创建时间',
  `UPDATE_BY` varchar(32) DEFAULT NULL COMMENT '修改人',
  `UPDATE_DATE` datetime DEFAULT NULL COMMENT '修改时间',
  `IS_ADMINROLE` char(1) DEFAULT NULL COMMENT '1 是 0 否',
  PRIMARY KEY (`ROLE_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='角色表';
-------------------------------------------------------------------------------------------------------------------------

Step1:新建Web项目

SSM框架搭建详细记录--非Maven--多模块--目录清晰

Step2:导入Jar包(可自行百度ssmjar包下载)至lib文件下;并建立好SSM所需配置文件

到此项目的目录结构为:

SSM框架搭建详细记录--非Maven--多模块--目录清晰

Step3:写入配置文件

一、写入jdbc.properties文件

#MYSQL
jdbc1.driverName=com.mysql.jdbc.Driver
jdbc1.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc1.user=root
jdbc1.password=root

二、写入mybatis-config.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>
    <!-- 别名定义 -->
    <typeAliases>
    	<!-- 批量别名定义,指定包名,mybatis自动扫描包中的po类,自动定义别名,别名是类名(首字母大写或小写都可以,一般用小写) --> 
        <package name="com.test.ssm"/> 
        <!-- 针对单个别名定义 type:类型的路径 alias:别名 -->  
        <!-- <typeAlias alias="User" type="com.test.ssm.user.model.User"/>
        <typeAlias alias="Role" type="com.test.ssm.role.model.Role"/> -->
    </typeAliases>
</configuration>

三、写入spring.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
     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/tx
         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
         
	 <!-- 加载配置文件 -->
	 <context:property-placeholder location="classpath:config/jdbc.properties"/>  
   
     <!-- 1. 数据源 : DriverManagerDataSource -->
     <bean id="dataSource"
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
         <property name="driverClassName" value="${jdbc1.driverName}" />
         <property name="url" value="${jdbc1.url}" />
         <property name="username" value="${jdbc1.user}" />
         <property name="password" value="${jdbc1.password}" />
     </bean>
 
     <!-- sqlSessionFactory -->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         <property name="dataSource" ref="dataSource"></property>
         <!-- 文件映射器,指定类文件 -->
         <property name="configLocation" value="classpath:config/mybatis-config.xml" /> 
          <!-- 自动扫描mapping.xml文件 --> 
         <property name="mapperLocations" value="classpath*:com/test/ssm/**/*Mapper.xml"/>
     </bean>
 
 	<!-- 配置SqlSessionTemplate -->  
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">  
    	<!-- 通过构造函数注入 -->
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />  
    </bean>
    
    <!-- 配置mybatis mapper接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.test.ssm.**.mapper"/>
        <property name="sqlSessionTemplateBeanName" value="sqlSessionTemplate"/>
    </bean> 
    
 
     <!--
         4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源
     -->
     <bean id="txManager"
         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource"></property>
     </bean>
 
     <!-- 5. 使用声明式事务
          transaction-manager:引用上面定义的事务管理器
      -->
     <tx:annotation-driven transaction-manager="txManager" />
 
 </beans>

四、写入spring-mvc.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:context="http://www.springframework.org/schema/context"
     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/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">
 
     <!-- 注解扫描包 -->
     <context:component-scan base-package="com.test.ssm" />
 
     <!-- 开启注解 -->
     <mvc:annotation-driven />
 
     <!--
         配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd
     -->
     <mvc:resources mapping="/img/**" location="/img/" />
     <mvc:resources mapping="/js/**" location="/js/" />
     <mvc:resources mapping="/css/**" location="/css/" />
     <mvc:resources mapping="/html/**" location="/html/" />
 
 

     <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
     <bean id="viewResolver"
         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
         <property name="prefix" value="/WEB-INF/jsp/" />
         <property name="suffix" value=".jsp" />
     </bean>
 </beans>

五、写入web.xml文件

<?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容器加载所有的配置文件的路径 -->
     <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath*:config/spring.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*:config/spring-mvc.xml</param-value>
         </init-param>
         <!-- 启动加载一次 -->  
         <load-on-startup>1</load-on-startup>
     </servlet>
 
     <!--为DispatcherServlet建立映射 -->
     <servlet-mapping>
         <servlet-name>springMVC</servlet-name>
         <!-- 此处可以可以配置成*.do -->
         <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>
 
     <welcome-file-list>
         <welcome-file>index.jsp</welcome-file>
     </welcome-file-list>
 </web-app>

Step4:建立2张表所对应的模块的包及文件

至此目录结构为:

SSM框架搭建详细记录--非Maven--多模块--目录清晰

---------------------------------------------------------------------------------------------------------------

User模块的文件建立

User模块的目录结构如下图

SSM框架搭建详细记录--非Maven--多模块--目录清晰

1.user模块下model包下建立User.java文件

package com.test.ssm.user.model;

public class User {
	
	private int userId;
	private String userCode;
	private String userName;
	private String password;
	private int age;
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUserCode() {
		return userCode;
	}
	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

2.user模块下mapper包下建立接口UserMapper.java文件

package com.test.ssm.user.mapper;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.test.ssm.user.model.User;
@Repository
public interface UserMapper {
	
	List<User> findAllUser();
}

3.User模块下mapper包下建立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.test.ssm.user.mapper.UserMapper">
    <!-- 解决表名与字段不匹配 -->
    <resultMap type="User" id="userResultMap">
        <id property="userId" column="c_id"/>
        <result property="userName" column="c_user_name"/>
        <result property="userCode" column="c_user_code"/>
        <result property="password" column="c_password"/>
        <result property="age" column="c_age"/>
    </resultMap>
    
    <select id="findAllUser" resultMap="userResultMap" resultType="User">
        select * from t_user
    </select>
</mapper>

4.User模块下service包下建立接口UserService.java文件

package com.test.ssm.user.service;

import java.util.List;

import com.test.ssm.user.model.User;

public interface UserService {
	
	List<User> findAllUser();
}

5.User模块下service包下建立impl包;并在impl包下建立UserServiceImpl.java文件;该文件实现UserService接口

package com.test.ssm.user.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.test.ssm.user.mapper.UserMapper;
import com.test.ssm.user.model.User;
import com.test.ssm.user.service.UserService;

@Service(value="userService")
@Transactional
public class UserServiceImpl implements UserService {

	@Resource
    public UserMapper userMapper;
	
	@Override
	public List<User> findAllUser() {
		List<User> findAllUser = userMapper.findAllUser();
		return findAllUser;
	}

}

6.User模块下Controller包下建立UserController.java文件

package com.test.ssm.user.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.test.ssm.user.model.User;
import com.test.ssm.user.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping("/findAllUser")
	public String findAllUser(HttpServletRequest request) {
		List<User> listUser = userService.findAllUser();
		request.setAttribute("listUser", listUser);
		return "/show";
	}
}

至此User模块的java文件编写完成

-------------------------------------------------------------------------------------------------------------------------------

Role模块的编写

Role模块的目录结构如下图:

SSM框架搭建详细记录--非Maven--多模块--目录清晰

1.Role模块下model包下Role.java文件编写

package com.test.ssm.role.model;

public class Role {

	private String roleId;
	private String roleCode;
	private String roleName;
	private String supRoleId;
	private String createBy;
	private String createDate;
	private String updateBy;
	private String updateDate;
	private String isAdminRole;
	public String getRoleId() {
		return roleId;
	}
	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}
	public String getRoleCode() {
		return roleCode;
	}
	public void setRoleCode(String roleCode) {
		this.roleCode = roleCode;
	}
	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	public String getSupRoleId() {
		return supRoleId;
	}
	public void setSupRoleId(String supRoleId) {
		this.supRoleId = supRoleId;
	}
	public String getCreateBy() {
		return createBy;
	}
	public void setCreateBy(String createBy) {
		this.createBy = createBy;
	}
	public String getCreateDate() {
		return createDate;
	}
	public void setCreateDate(String createDate) {
		this.createDate = createDate;
	}
	public String getUpdateBy() {
		return updateBy;
	}
	public void setUpdateBy(String updateBy) {
		this.updateBy = updateBy;
	}
	public String getUpdateDate() {
		return updateDate;
	}
	public void setUpdateDate(String updateDate) {
		this.updateDate = updateDate;
	}
	public String getIsAdminRole() {
		return isAdminRole;
	}
	public void setIsAdminRole(String isAdminRole) {
		this.isAdminRole = isAdminRole;
	}
	
}

2.Role模块下mapper包下建立接口RoleMapper.java文件编写

package com.test.ssm.role.mapper;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.test.ssm.role.model.Role;
@Repository
public interface RoleMapper {
	
	List<Role> findAllRole();
}

3.Role模块下mapper包下建立RoleMapper.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.test.ssm.role.mapper.RoleMapper">
    <!-- 解决表名与字段不匹配 -->
    <resultMap type="Role" id="roleResultMap">
        <id property="roleId" column="ROLE_ID"/>
        <result property="roleCode" column="ROLE_CODE"/>
        <result property="roleName" column="ROLE_NAME"/>
        <result property="supRoleId" column="SUP_ROLE_ID"/>
        <result property="createBy" column="CREATE_BY"/>
        <result property="createDate" column="CREATE_DATE"/>
        <result property="updateBy" column="UPDATE_BY"/>
        <result property="updateDate" column="UPDATE_DATE"/>
        <result property="isAdminRole" column="IS_ADMINROLE"/>
    </resultMap>
    
    <select id="findAllRole" resultMap="roleResultMap" resultType="Role">
        select * from auth_role_t
    </select>
</mapper>

4.Role模块下service包下建立接口RoleService.java文件

package com.test.ssm.role.service;

import java.util.List;

import com.test.ssm.role.model.Role;

public interface RoleService {
	
	List<Role> findAllRole();
}

5.Role模块下service包下建立impl包;并在impl包下建立RoleServiceImpl.java文件并实现接口RoleService

RoleServiceImpl.java的文件编写如下:

package com.test.ssm.role.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.test.ssm.role.mapper.RoleMapper;
import com.test.ssm.role.model.Role;
import com.test.ssm.role.service.RoleService;

@Service(value="roleService")
@Transactional
public class RoleServiceImpl implements RoleService {

	@Resource
    public RoleMapper roleMapper;
	
	@Override
	public List<Role> findAllRole() {
		List<Role> findAllRole = roleMapper.findAllRole();
		return findAllRole;
	}

}

6.Role模块下controller包下RoleController.java文件编写

package com.test.ssm.role.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.test.ssm.role.model.Role;
import com.test.ssm.role.service.RoleService;

@Controller
@RequestMapping("/role")
public class RoleController {

	@Autowired
	private RoleService roleService;

	@RequestMapping("/findAllRole")
	public String findAllRole(HttpServletRequest request) {
		List<Role> listRole = roleService.findAllRole();
		request.setAttribute("listRole", listRole);
		return "/showRole";
	}
}

至此Role模块的java代码编写完成

---------------------------------------------------------------------------------------------------------------------------------

Step5.建立前台jsp文件显示访问结果

1.建立文件及文件夹

        目录结构如下

SSM框架搭建详细记录--非Maven--多模块--目录清晰

2.show.jsp文件编写

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 <%
 String path = request.getContextPath();
 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 <html>
   <head>
     <base href="<%=basePath%>">
     
     <title>ssm</title>
     
     <meta http-equiv="pragma" content="no-cache">
     <meta http-equiv="cache-control" content="no-cache">
     <meta http-equiv="expires" content="0">    
     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
     <meta http-equiv="description" content="This is my page">
     <!--
     <link rel="stylesheet" type="text/css" href="styles.css">
     -->
 
   </head>
   
   <body>
    <table border="1">
         <tbody>
             <tr>
                 <th>姓名</th>
                 <th>年龄</th>
                 <th>登录名</th>
                 <th>密码</th>
             </tr>
             <c:if test="${!empty listUser }">
                 <c:forEach items="${listUser}" var="list">
                     <tr>
                         <td>${list.userName }</td>
                         <td>${list.age }</td>
                         <td>${list.userCode }</td>
                         <td>${list.password }</td>
                     </tr>                
                 </c:forEach>
             </c:if>
         </tbody>
     </table>
   </body>
 </html>

3.showRole.jsp文件编写

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 <%
 String path = request.getContextPath();
 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 <html>
   <head>
     <base href="<%=basePath%>">
     
     <title>ssm</title>
     
     <meta http-equiv="pragma" content="no-cache">
     <meta http-equiv="cache-control" content="no-cache">
     <meta http-equiv="expires" content="0">    
     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
     <meta http-equiv="description" content="This is my page">
     <!--
     <link rel="stylesheet" type="text/css" href="styles.css">
     -->
 
   </head>
   
   <body>
    <table border="1">
         <tbody>
             <tr>
                 <th>角色编码</th>
                 <th>角色名称</th>
                 <th>创建时间</th>
                 <th>是否管理</th>
             </tr>
             <c:if test="${!empty listRole }">
                 <c:forEach items="${listRole}" var="list">
                     <tr>
                         <td>${list.roleCode }</td>
                         <td>${list.roleName }</td>
                         <td>${list.createDate }</td>
                         <td>${list.isAdminRole }</td>
                     </tr>                
                 </c:forEach>
             </c:if>
         </tbody>
     </table>
   </body>
 </html>

至此SSM简单框架搭建完成。对于强迫症的我来说;这个架子目录结构非常清晰,我很是喜欢。。嘿嘿

-------------------------------------------------------------------------------------------------------------------------------

将项目部署到tomcat中;启动并访问地址

http://localhost:8080/ssm/role/findAllRole

http://localhost:8080/ssm/user/findAllUser

-------------------------------------------------------------------------------------------------------------------------------

GitHub项目下载地址

https://github.com/yisuixiaotufei/SSM