SSM框架整合搭建教程

自己配置了一个SSM框架,打算做个小网站,这里把SSM的配置流程详细的写了出来,方便很少接触这个框架的朋友使用,文中各个资源均免费提供!

一. 创建web项目(eclipse)

File-->new-->Dynamic Web Project (这里我们创建的项目名为SSM)

下面是大致目录结构

二. SSM所需jar包

jar包链接:https://pan.baidu.com/s/1dTClhO 密码:n4mm

三. 整合开始

1.mybatis配置文件(resource/mybatis/SqlMapConfig.xml)

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE configuration
3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
5 <configuration>
6
7 </configuration>

2.Dao,mybatis整合spring,通过spring管理

SqlSessionFactory、mapper代理对象

(resource/spring/applicationContext-dao.xml)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
 7     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
 8     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
 9     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
10
11     <!-- 数据库连接池 -->
12     <!-- 加载配置文件 -->
13     <context:property-placeholder location="classpath:*.properties" />
14     <!-- 数据库连接池 -->
15     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
16         destroy-method="close">
17         <property name="url" value="${jdbc.url}" />
18         <property name="username" value="${jdbc.username}" />
19         <property name="password" value="${jdbc.password}" />
20         <property name="driverClassName" value="${jdbc.driver}" />
21         <property name="maxActive" value="10" />
22         <property name="minIdle" value="5" />
23     </bean>
24     <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
25     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
26         <!-- 数据库连接池 -->
27         <property name="dataSource" ref="dataSource" />
28         <!-- 加载mybatis的全局配置文件 -->
29         <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
30     </bean>
31     <!-- 自动扫描 将Mapper接口生成代理注入到Spring -->
32     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
33         <property name="basePackage" value="com.mapper" />
34     </bean>
35 </beans>

这里用的是阿里的连接池,当然也可以用c3p0,个人建议用阿里

3. 所有的实现类都放到spring容器中管理。由spring创建数据库连接池,并有spring管理实务。

(resource/spring/applicationContext-service.xml)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
 7     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
 8     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
 9     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
10
11         <!-- spring自动去扫描base-pack下面或者子包下面的java文件-->
12         <!--管理Service实现类-->
13         <context:component-scan base-package="com.service"/>
14 </beans>

配置spring管理实务

(resource/spring/applicationContext-trans.xml)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
 7     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
 8     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
 9     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
10     <!-- 事务管理器 -->
11     <bean id="transactionManager"
12         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
13         <!-- 数据源 -->
14         <property name="dataSource" ref="dataSource" />
15     </bean>
16     <!-- 通知 -->
17     <tx:advice id="txAdvice" transaction-manager="transactionManager">
18         <tx:attributes>
19             <!-- 传播行为 -->
20             <tx:method name="save*" propagation="REQUIRED" />
21             <tx:method name="insert*" propagation="REQUIRED" />
22             <tx:method name="add*" propagation="REQUIRED" />
23             <tx:method name="create*" propagation="REQUIRED" />
24             <tx:method name="delete*" propagation="REQUIRED" />
25             <tx:method name="update*" propagation="REQUIRED" />
26             <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
27             <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
28             <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
29         </tx:attributes>
30     </tx:advice>
31     <!-- 切面 -->
32     <aop:config>
33         <aop:advisor advice-ref="txAdvice"
34             pointcut="execution(* com.service.*.*(..))" />
35     </aop:config>
36 </beans>

4. Springmvc整合spring框架,由springmvc管理controller

(resource/spring/springmvc.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: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/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">

    <!-- 扫描controller -->
    <context:component-scan base-package="com.controller" />

    <!-- Spring 来扫描指定包下的类,并注册被@Component,@Controller,@Service,@Repository等注解标记的组件 -->
    <mvc:annotation-driven />

    <!-- 配置SpringMVC的视图解析器-->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

5. 2中加载的属性配置文件(dbconfig.properties)

根据自己的数据库更改用户名密码以及库

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

6. 配置log4j

(log4j.properties)

log4j.rootLogger=error,CONSOLE,A
log4j.addivity.org.apache=false

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=error
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} -%-4r [%t] %-5p  %x - %m%n
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.Encoding=gbk
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout

log4j.appender.A=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A.File=${catalina.home}/logs/FH_log/PurePro_
log4j.appender.A.DatePattern=yyyy-MM-dd‘.log‘
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=[FH_sys]  %d{yyyy-MM-dd HH\:mm\:ss} %5p %c{1}\:%L \: %m%n

(log4j.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

	<!-- Appenders -->
	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<param name="Target" value="System.out" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{yyyy HH:mm:ss} %-5p %c - %m%n" />
		</layout>
	</appender>

	<!-- Application Loggers -->
	<logger name="com">
		<level value="error" />
	</logger>

	<!-- 3rdparty Loggers -->
	<logger name="org.springframework.core">
		<level value="error" />
	</logger>	

	<logger name="org.springframework.beans">
		<level value="error" />
	</logger>

	<logger name="org.springframework.context">
		<level value="error" />
	</logger>

	<logger name="org.springframework.web">
		<level value="error" />
	</logger>

	<logger name="org.springframework.jdbc">
		<level value="error" />
	</logger>

	<logger name="org.mybatis.spring">
		<level value="error" />
	</logger>
	<logger name="java.sql">
		<level value="error" />
	</logger>
	<!-- Root Logger -->
	<root>
		<priority value="error" />
		<appender-ref ref="console" />
	</root>

</log4j:configuration>

SSM框架整合完成,至于mybatis逆向工程生成的mapper.xml和pojo请放到第一张图的目录下

注:逆向工程是根据数据库表反向生成pojo以及mapper.xml,所以,请先自动在数据库配置好user表。逆向工程得配置在下面得链接里面有详细注释。

测试数据库表(User)

private String id;

private String username;

private String password;

private String company;

private Integer age;

private Integer sex;

根据类型创建表即可

逆向工程项目我会贴出链接,解压导入改路径运行main方法就会自动生成了,注意配置生成的路径

逆向工程链接: 链接:https://pan.baidu.com/s/1QvSskH2UEC6EQF7MgVDOAQ 密码:t2pc

到这里项目整合完成,接下来是测试!
 UserController.java

 1 package com.controller;
 2
 3 import javax.annotation.Resource;
 4 import javax.servlet.http.HttpServletRequest;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.servlet.ModelAndView;
 8 import com.pojo.User;
 9 import com.service.UserService;
10
11 @Controller
12 @RequestMapping("/user")
13 public class UserController {
14
15     @Resource(name="userService")
16     private UserService userService;
17     /**
18      * 根据id查询
19      */
20     @RequestMapping(value="/queryById")
21     public ModelAndView queryById(HttpServletRequest request){
22         ModelAndView mv = new ModelAndView();
23         String id = request.getParameter("id");
24         try{
25             User var = userService.findById(id);
26             mv.setViewName("index");
27             mv.addObject("var", var);
28         } catch(Exception e){
29             e.printStackTrace();
30         }
31         return mv;
32     }
33 }

UserService.java

 1 package com.service;
 2
 3 import javax.annotation.Resource;
 4
 5 import org.springframework.stereotype.Service;
 6
 7 import com.mapper.UserMapper;
 8 import com.pojo.User;
 9
10 @Service("userService")
11 public class UserService {
12     @Resource
13     private UserMapper dao;
14     /*
15     * 通过id获取数据
16     */
17     public User findById(String id)throws Exception{
18         return (User)dao.selectByPrimaryKey(id);
19     }
20 }

补上之前漏掉得web.xml配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 5     id="WebApp_ID" version="2.5">
 6     <welcome-file-list>
 7         <welcome-file>index.jsp</welcome-file>
 8     </welcome-file-list>
 9     <!-- 加载spring容器 -->
10     <context-param>
11         <param-name>contextConfigLocation</param-name>
12         <param-value>classpath:spring/applicationContext*.xml</param-value>
13     </context-param>
14     <listener>
15         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
16     </listener>
17
18     <!-- 解决post乱码 -->
19     <filter>
20         <filter-name>CharacterEncodingFilter</filter-name>
21         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
22         <init-param>
23             <param-name>encoding</param-name>
24             <param-value>utf-8</param-value>
25         </init-param>
26         <!-- <init-param>
27             <param-name>forceEncoding</param-name>
28             <param-value>true</param-value>
29         </init-param> -->
30     </filter>
31     <filter-mapping>
32         <filter-name>CharacterEncodingFilter</filter-name>
33         <url-pattern>/*</url-pattern>
34     </filter-mapping>
35
36
37     <!-- springmvc的前端控制器 -->
38 <!--     <servlet>
39         <servlet-name>taotao-manager</servlet-name>
40         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
41         contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml"
42         <init-param>
43             <param-name>contextConfigLocation</param-name>
44             <param-value>classpath:spring/springmvc.xml</param-value>
45         </init-param>
46         <load-on-startup>1</load-on-startup>
47     </servlet>
48     <servlet-mapping>
49         <servlet-name>SSM</servlet-name>
50         <url-pattern>/</url-pattern>
51     </servlet-mapping> -->
52
53       <servlet>
54     <servlet-name>springMvc</servlet-name>
55     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
56     <init-param>
57       <param-name>contextConfigLocation</param-name>
58       <param-value>classpath:spring/springmvc.xml</param-value>
59     </init-param>
60     <load-on-startup>1</load-on-startup>
61   </servlet>
62   <servlet-mapping>
63     <servlet-name>springMvc</servlet-name>
64     <url-pattern>/</url-pattern>
65   </servlet-mapping>
66
67 </web-app>

为节省篇幅,更快的搭建成功,这里只写了一个方法,根据id查询数据

WebContent/index.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">
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>查询用户</title>
</head>
<body>
    <form action="user/queryById.do" method="post">
        输入要查询的id:    <input type="text" name="id" value="123456"/>
        <button type="submit">提交</button>
    </form>
</body>
</html>

WebContent/WEB-INF/jsp/index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@page import="com.pojo.*"%>
<!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">
    .td td{
        width: 100px;
    }
    .table{
        text-align: center;
        margin: 0 auto;
    }
</style>
</head>
<body>
<%
    User user = ((User)request.getAttribute("var"));
%>

    <table class="table">
        <tr class="td">
            <td>ID</td>
            <td>用户名</td>
            <td>密码</td>
            <td style="width: 200px">公司</td>
            <td>年龄</td>
            <td>性别</td>
        </tr>
<%if(user!=null){%>
        <tr class="td">
            <td><%=user.getId()%></td>
            <td><%=user.getUsername()%></td>
            <td><%=user.getPassword()%></td>
            <td><%=user.getCompany()%></td>
            <td><%=user.getAge()%></td>
            <td><%=user.getSex()==1?"男":"女"%></td>
        </tr>
    <%}else{ %>
        <tr class="td">
            <td style="color: red;">暂无相关数据</td>
        </tr>
<%} %>
    </table>

</body>
</html>

启动项目,输入localhost:8080/SSM 访问

为方便新手查错,博主按照博文重新搭建了一次,测试无误后将项目打包,上传至云盘,供您使用。(建议:希望您按照博文从头搭建,便于印象深刻)

项目完整链接(含数据库): https://pan.baidu.com/s/17O8HgkoSYblFfC3uziMrdA 密码:cw77

原文地址:https://www.cnblogs.com/aishangJava/p/10360901.html

时间: 2024-10-07 18:08:36

SSM框架整合搭建教程的相关文章

SSM框架整合详细教程(Spring+SpringMVC+Mabatis)

当前最火热的SSM框架整合教程,超级详细版 直接到正题,利用了最新稳定的框架 需要自己在Maven下搭建web工程 项目结构图: spring-mvc.xml <?xml version="1.0" encoding="UTF-8"?>   <beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.

SSM框架——整合搭建流程

本文是作者在看完 http://blog.csdn.net/zhshulin/article/details/37956105/ 之后自己搭建的流程: 1.首先创建maven工程,使用哪种方式进行创建都可以,可以参考博主之前的文章: <两种方式创建Maven项目[方式二]><两种方式创建Maven项目[方式一]> 2.先看看搭建最终搭建完成后的项目结构: 3.搭建流程: 数据库使用的是:mysql ide使用的是:eclipse[Version: Neon.2 Release (4

Spring+Spring MVC+MyBatis实现SSM框架整合详细教程【转】

关于Spring+SpringMVC+Mybatis 整合,见还有不少初学者一头雾水,于是写篇教程,初学者按部就班的来一次,可能就会少走不少弯路了. 一:框架介绍(啰嗦两句,可自行度娘) 1.1:Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来.它是为了解决企业应用开发的复杂性而创建的

java S2SH项目框架整合搭建实例教程

原创整理不易,转载请注明出处:java S2SH项目框架整合搭建实例教程 代码下载地址:http://www.zuidaima.com/share/1787220771113984.htm 现在开发的一个项目使用S2SH框架,配置环境用了一两天,现在把当时配置环境时写的文档整理下发出来,也算加强点记忆. 1 开发环境 ?         MyEclipse5.5 ?         JDK 1.6 ?         Java EE 5.0 ?         Tomcat6.0 ?      

Spring+SpringMvc+Mybatis框架集成搭建教程

一.背景 最近有很多同学由于没有过SSM(Spring+SpringMvc+Mybatis , 以下简称SSM)框架的搭建的经历,所以在自己搭建SSM框架集成的时候,出现了这样或者那样的问题,很是苦恼,网络上又没有很详细的讲解以及搭建的教程.闲来无事,我就利用空闲时间来写这样一个教程和搭建步骤,来帮助那些有问题的小伙伴,让你从此SSM搭建不再有问题. 二.教程目录 1.Spring+SpringMvc+Mybatis框架集成搭建教程一(项目创建) 2.Spring+SpringMvc+Mybat

Spring+SpringMvc+Mybatis框架集成搭建教程一(背景介绍及项目创建)

一.背景 最近有很多同学由于没有过SSM(Spring+SpringMvc+Mybatis , 以下简称SSM)框架的搭建的经历,所以在自己搭建SSM框架集成的时候,出现了这样或者那样的问题,很是苦恼,网络上又没有很详细的讲解以及搭建的教程.闲来无事,我就利用空闲时间来写这样一个教程和搭建步骤,来帮助那些有问题的小伙伴,让你从此SSM搭建不再有问题. 二.搭建步骤 1.框架搭建环境 Spring 4.2.6.RELEASE SpringMvc 4.2.6.RELEASE Mybatis 3.2.

ssm框架的搭建

最近有很多朋友问我一些ssm框架的搭建过程,由于其中一些配置文件相对比较多,我在这整理了一下,搭建了一个简单的ssm框架模型,有需要的朋友可以参考一下 ssm模型我放在了github上了,这是网址   https://github.com/hhy0602/ssm.git

java开发SSM框架的搭建(SpringMVC+Spring+MyBatis)

由于某些原因,重装系统,java-web开发虽然顺手,但烦人的一点是开发环境的搭建.差不多折腾了一整天,笔者在这里把SSM开发环境的搭建重新清理一遍,以飨读者,也供自己以后参考.善于总结,是做好每份工作必备的素质之一. 1安装java虚拟机-JDK(1.7_51) 详见笔者博文:http://blog.csdn.net/gisredevelopment/article/details/24304085 2 安装MyEclipse(2014专业版) 下载地址:http://www.myeclips

SSM框架整合(实现从数据库到页面展示)

SSM框架整合(实现从数据库到页面展示) 首先创建一个spring-web项目,然后需要配置环境dtd文件的引入,环境配置,jar包引入. 首先让我来看一下ssm的基本项目配件.(代码实现) 1.首先编写web.xml文件. <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x