欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

手把手搭建SSM框架

程序员文章站 2024-01-18 22:45:16
...

            搭建一个简单的SSM框架,分享给大家,以后自己也可以拿出来用

1.用maven项目管理工具搭建一个简单SSM的demo:工具Eclipse,Mysql-5.5,Tomcat-7.0,Maven-3.0,jdk-1.8

         (1) 新建一个手把手搭建SSM框架动态web项目,当然也可以建一个Java普通项目,

         (2)Dynamic Web Project手把手搭建SSM框架

选择好你需要设置的配置和tomcat版本,点击下一步手把手搭建SSM框架

可以添加一个resources文件夹,方便后面我们存放各种配置文件。点击下一步手把手搭建SSM框架记得把这个勾选上,是后面需要设置的一个web.xml文件。

            (3)这样我们就创建好了一个动态Web项目手把手搭建SSM框架

                  (4)右击项目名,选择下面的Configure==>Convert to Maven Project手把手搭建SSM框架

点击完成就行,加入Maven项目管理工具能使我们在做项目省很多心思。

手把手搭建SSM框架

我们需要在这个pom.xml写我们需要的引入依赖包及版本,大家可以上maven仓库查找需要的版本http://mvnrepository.com/

        (5)依赖包

<dependencies>
		<!-- 单元测试 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
		</dependency>
		<!-- 1.日志 -->
		<!-- 实现slf4j接口并整合 -->
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.1.1</version>
		</dependency>
		<!-- 2.数据库 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
			<scope>runtime</scope>
		</dependency>
		<!-- DAO: MyBatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.3.0</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.3</version>
		</dependency>
		<!-- 3.Servlet web -->
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>

		<dependency>

			<groupId>jstl</groupId>

			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>		
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<!-- 4.Spring -->
		<!-- 1)Spring核心 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<!-- 2)Spring DAO层 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<!-- 3)Spring web -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<!-- 4)Spring test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<!-- Map工具类 -->
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>		
	</dependencies>

   3.写入环境

    (1)jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/ssm2?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10

jdbc.username=root

jdbc.password=123456

    (2)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>
    <!-- 配置全局属性 -->
    <settings>
        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true" />


        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />


        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

后面我是将spring配置文件分为3个部分,方便我们管理

    (3)spring-dao.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"
    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.xsd">
    <!-- 配置整合mybatis过程 -->
    <!-- 1.配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:jdbc.properties" />


    <!-- 2.数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <!-- 配置连接池属性 -->
        <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>


    <!-- 3.配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 扫描entity包 使用别名 -->
        <property name="typeAliasesPackage" value="cn.ssm.entity" />
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:src/cn/ssm/dao/*.xml" />
    </bean>


    <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="cn.ssm" />
    </bean>
</beans>

(4)spring-service.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: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/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="cn.smm" />


    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>


    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

       
(5)spring-web.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.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    
     <!-- 4.扫描web相关的bean -->
     <context:component-scan base-package="cn.smm" />
    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解模式 -->
    <!-- 简化配置: 
        (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter 
        (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持 
    -->
    <mvc:annotation-driven />


    <!-- 2.静态资源默认servlet配置
        (1)加入对静态资源的处理:js,gif,png
        (2)允许使用"/"做整体映射
     -->
     <mvc:default-servlet-handler/>
	 <!-- 配置登陆拦截器 -->  
      <mvc:interceptor>       	
          <mvc:mapping path="/**"/>  
          <bean class="cn.labelnet.ssm.filter.LoginHandlerIntercepter"></bean>  
      </mvc:interceptor>
        
     <!-- 3.配置jsp 显示ViewResolver -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
     </bean>    
</beans>
(6)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ssm</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!--Spring核心监听器  -->
  <!--在服务器启动时加载Spring容器,且只会加载一次  -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath: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:springmvc.xml</param-value>
		</init-param>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>

  <!--配置由Spring 提供的针对中文乱码的编码过滤器 -->
  <!-- 编码过滤器 -->
	<filter>
		<filter-name>CharacterEncodingFilter</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>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  
</web-app>

4.创建项目骨架

手把手搭建SSM框架

基本的结构,还可以分mapper包,放mybatis的映射文件

(1)User.java实体类
package cn.ssm.entity;

public class User {
	private Integer id;
	private String code;
	private String password;
	private String name;
	private String phone;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", code=" + code + ", name=" + name + ", phone=" + phone + "]";
	}	
}

     (2)UserDao.java用户接口

package cn.ssm.dao;

import cn.ssm.entity.User;

public interface UserDao {
	void login(String code,String password);//登陆
	int add(User user);//注册
	int queryAllById(int id);//查询
}
    (3)UserDao.xml   UserMapper

        

<?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="cn.smm.dao.UserDao">
    <!-- 目的:为dao接口方法提供sql语句配置 -->
    <!-- 登陆验证 -->
    <select id="login" parameterType="map">
    	SELECT            
            code,
            password
        FROM
            user
      	where
      		code=#{code}
      		and
      		password=#{password}
    </select>
    <!-- 查询 -->
    <select id="queryAllById" resultType="User" parameterType="int">
        SELECT
            id,
            code,
            name,
            phone,            
        FROM
            user
      	WHERE
      		id=#{id}
    </select>
    
	<!-- 添加用户 -->	
   	<insert id="add" resultType="int" parameterType="User">
        insert into
        	user(        	
        	code,
        	password,
        	name,
        	phone)
        values(            
            code=#{code},
            password=#{password},
            name=#{name},
            phone=#{phone})         
    </insert>	
</mapper>

        (4)UserService.java 

package cn.ssm.service;

import cn.ssm.entity.User;

public interface UserService {
	/** 
     * 登录验证 
     * @param account 登录账号 
     * @param userPassword 密码 
     * @return  validate true通过 false未通过 
     * @throws Exception 
     */  
    User login(String code, String password) throws Exception; 
    /**
     * 注册
     * @param user
     */
    int add(User user)throws Exception;
    /**
     * ID查询
     * @param id
     * @return
     * @throws Exception
     */
    User queryById(int id)throws Exception;
}

        (5)UserServiceImpl.java

package cn.ssm.service;


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

import cn.ssm.dao.UserDao;
import cn.ssm.entity.User;

public class UserServiceImpl implements UserService {
	@Autowired
	UserDao userDao;
	@Override
	public User login(String code, String password) throws Exception {
		
		return userDao.login(code, password);
	}

	@Override
	public int add(User user) throws Exception {
		
		return userDao.add(user);
	}

	@Override
	public User queryById(int id) throws Exception {
		
		return userDao.queryById(id);
	}

}

        (6)UserCtroller.java

package cn.ssm.web;

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

import cn.ssm.entity.User;
import cn.ssm.service.UserService;

@Controller
@RequestMapping("/user")
public class UserCtroller {
	@Autowired
	UserService userService;

	@RequestMapping("login")
	public String login(String code, String password, Model model) throws Exception {
		System.out.println("用户登陆" + code + password);
		userService.login(code, password);		
		model.addAttribute("sg", "登陆成功");
		return "show";

	}

	@RequestMapping("add")
	public String add(User user, Model model) throws Exception {
		System.out.println("用户注册" + user.getCode() + user.getPassword());

		int addUser = userService.add(user);
		model.addAttribute("sg", "注册成功");

		if (addUser == 1) {
			return "login";
		}
		return null;

	}

	@RequestMapping("query")
	public String queryById(int id, Model model) throws Exception {
		System.out.println("查询id" + id);
		userService.queryById(id);
		model.addAttribute("sg", "查询结果");
		return "show";

	}
}

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">
<title>用户注册</title>
</head>
<body>
	<form action="${pageContext.request.contextPath }/user/regist.action">
		<table border="1">
			<tr>
				<td>用户名</td>
				<td><input type="text" name="name"></td>
			</tr>
			<tr>
				<td>密码</td>
				<td><input type="text" name="password"></td>
			</tr>
			<tr>
				<td><input type="submit" value="注册"></td>
			</tr>
		</table>
	</form>
</body>
</html>

登陆

<%@ 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">
<title>用户登录</title>
</head>
<body>
	<form action="${pageContext.request.contextPath }/user/login.action">
		<table border="1">
			<tr>
				<td>用户名</td>
				<td><input type="text" name="name"></td>
			</tr>
			<tr>
				<td>密码</td>
				<td><input type="text" name="password"></td>
			</tr>
			<tr>
				<td><input type="submit" value="登录"></td>
			</tr>
		</table>
	</form>
</body>
</html>

登陆成功

<%@ 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">
<title>登录成功</title>
</head>
<body>
	${msg }</br>
	<a href="${pageContext.request.contextPath }/login.jsp">去登录</a>
</body>
</html>