SSM框架——Spring+SpringMVC+Mybatis的搭建教程

一:概述

SSM框架在项目开发中经常使用到,相比于SSH框架,它在仅几年的开发中运用的更加广泛。

Spring作为一个轻量级的框架,有很多的拓展功能,最主要的我们一般项目使用的就是IOC和AOP。

SpringMVC是Spring实现的一个Web层,相当于Struts的框架,但是比Struts更加灵活和强大!

Mybatis是 一个持久层的框架,在使用上相比Hibernate更加灵活,可以控制sql的编写,使用 XML或注解进行相关的配置!

根据上面的描述,学习SSM框架就非常的重要了!

二:搭建一个SSM的过程

使用Maven管理项目

使用Maven在Eclipse中创建一个webapp的项目 ,具体的创建过程不做演示,如有不会创建的[创建项目]

也可以使用Maven命令进行创建,在Dos窗口进入指定的目录,执行下面命令:

mvnarchetype:create -DgroupId=org.ssm.dufy -DartifactId=ssm-demo -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

使用命令要注意,系统安装了Maven,并配置好了环境变量![Maven的安装和环境变量配置]

导入项目(命名创建),添加依赖

导入项目是IDE中,或者直接在IDE创建,一般默认有【src/main/java】,手动创建【src/test/resources】、【src/test/java】文件夹。

如下项目结构:

然后直接配置 pom.xml文件中的包依赖!

4.0.0org.dufyssmwar0.0.1-SNAPSHOTssmDemohttp://maven.apache.org4.0.5.RELEASE3.2.11.6.61.2.125.1.35org.springframeworkspring-core${spring.version}org.springframeworkspring-webmvc${spring.version}org.springframeworkspring-context${spring.version}org.springframeworkspring-context-support${spring.version}org.springframeworkspring-aop${spring.version}org.springframeworkspring-aspects${spring.version}org.springframeworkspring-tx${spring.version}org.springframeworkspring-jdbc${spring.version}org.springframeworkspring-web${spring.version}org.springframeworkspring-test${spring.version}testorg.springframeworkspring-webmvc${spring.version}org.springframeworkspring-web${spring.version}mysqlmysql-connector-java${mysql.version}com.alibabadruid0.2.23com.alibabafastjson1.1.41log4jlog4j${log4j.version}org.slf4jslf4j-api${slf4j.version}ch.qos.logbacklogback-classic1.1.2ch.qos.logbacklogback-core1.1.2org.logback-extensionslogback-ext-spring0.1.1org.mybatismybatis${mybatis.version}org.mybatismybatis-spring1.2.0javax.servletjavax.servlet-api3.0.1javax.servlet.jspjavax.servlet.jsp-api2.3.2-b01javax.servletjstl1.2junitjunit3.8.1testssmDemo

创建数据库和表,生成代码

创建数据库我参考别人的博客数据库设计,这块没有自己去书写,直接添上代码

DROPTABLEIFEXISTS`user_t`;CREATETABLE`user_t`(`id`int(11)NOTNULLAUTO_INCREMENT,`user_name`varchar(40)NOTNULL,`password`varchar(255)NOTNULL,`age`int(4)NOTNULL,    PRIMARYKEY(`id`)  )ENGINE=InnoDBAUTO_INCREMENT=2DEFAULTCHARSET=utf8;/*Data for the table `user_t` */insertinto`user_t`(`id`,`user_name`,`password`,`age`)values(1,'测试','sfasgfaf',24)

生成代码请查看:

[Mybatis自动生成代码]

生成的代码导入图片解释:

Spring 和 mybatis整合,连接数据库,进行Junit测试

将生成的代码拷贝到项目中,然后进行Spring和Mybatis的整合,添加配置文件!

主要有

applicationContent.xml :Spring的相关配置!

Spring-mhbatis.xml : Spring和Mybatis集成配置!

jdbc.properties : 数据库信息配置!

logback.xml : 日志输出信息配置!(不做介绍,详细信息查看源码

主要介绍applicationContext.xml、Spring-mhbatis.xml、jdbc.properties。主要内容如下:

jdbc.properties

jdbc_driverClassName=com.mysql.jdbc.Driverjdbc_url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8jdbc_username=rootjdbc_password=root

applicationContext.xml


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

"> 可以不在配置 -->

spring-mybatis.xml


http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

测试代码,两种方式:

测试1:

package org.ssm.dufy.service;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.test.context.ContextConfiguration;importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;importorg.ssm.dufy.entity.User;/**

* 配置spring和junit整合,junit启动时加载springIOC容器 spring-test,junit

*/@RunWith(SpringJUnit4ClassRunner.class)// 告诉junit spring配置文件@ContextConfiguration({"classpath:applicationContext.xml"})publicclassIUserServiceTest{    @AutowiredpublicIUserServiceuserService;        @Testpublicvoid getUserByIdTest(){Useruser = userService.getUserById(1);System.out.println(user.getUserName());    }    }

测试2:

package org.ssm.dufy.service;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.ssm.dufy.entity.User;publicclassIUserServiceTest2{publicstaticvoid main(String[] args) {ApplicationContextapplication = newClassPathXmlApplicationContext("applicationContext.xml");IUserServiceuService = (IUserService) application.getBean("userService");Useruser = uService.getUserById(1);System.out.println(user.getUserName());    }}

5:整合SpringMVC,添加配置,创建jsp

SpringMVC需要的依赖在pom.xml中已经加上了,现在需在Web项目中的web.xml中添加启动SpringMVC启动配置和Spring整合SpringMVC的配置了。

新增如下两个文件:

spring-mvc.xml


http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.2.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> application/json -->json=application/json                xml=application/xml                html=text/html/ 映射时,能映射静态资源 -->

web.xml

SSM-DEMOcontextConfigLocationclasspath:applicationContext.xml

webAppRootKey

springmvc.root

-->SpringEncodingFilterorg.springframework.web.filter.CharacterEncodingFilterencodingUTF-8forceEncodingtrueSpringEncodingFilter/*logbackConfigLocationclasspath:logback.xmlch.qos.logback.ext.spring.web.LogbackConfigListenerorg.springframework.web.context.ContextLoaderListenerdispatcherServletorg.springframework.web.servlet.DispatcherServletcontextConfigLocationclasspath:spring-mvc.xml1dispatcherServlet/index.jsp

新增index.jsp文件

<%@pagecontentType="text/html; charset=utf-8"%>

Hello World!

6.启动web服务,测试

将上面的项目添加到Tomcat中,启动,控制台没有报错,并在地址栏访问,http://localhost:8080/ssm。页面显示Hello World! 项目配置ok!

7:编写Controller,和对应得业务界面

新增UserController,通过参数传递uid获取用户,若用户存在,跳转到showName.jsp ,若用户不存在,则跳转到error.jsp,并返回提示信息!

package org.ssm.dufy.web;importjavax.servlet.http.HttpServletRequest;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.servlet.ModelAndView;importorg.ssm.dufy.entity.User;importorg.ssm.dufy.service.IUserService;@ControllerpublicclassUserController{    @AutowiredprivateIUserServiceuserService;        @RequestMapping(value="/showname",method=RequestMethod.GET)publicStringshowUserName(@RequestParam("uid") int uid,HttpServletRequestrequest,Modelmodel){System.out.println("showname");Useruser = userService.getUserById(uid);if(user != null){            request.setAttribute("name", user.getUserName());            model.addAttribute("mame", user.getUserName());return"showName";        }        request.setAttribute("error","没有找到该用户!");return"error";    }}

Jsp内容如下:

showName.jsp

<%@pagecontentType="text/html; charset=utf-8"%>show name

Welcome

${name }

访问此页面

error.jsp

<%@pagecontentType="text/html; charset=utf-8"%>error page

${error }

三:遇到的问题

1:找不到UserService,报错

可能是包扫描路径的问题,检查一下Service是否在扫描的范围内

2:jsp接收不到request.setAttribute("","");内容

查资料说是因为 JSP的版本问题,可以在Jsp 上面添加 <%@ page isELIgnored="false" %>

或者修改web.xml ,添加version版本!

愿意了解框架技术或者源码的朋友直接加求求(企鹅):2042849237

更多详细源码参考来源:http://minglisoft.cn/technology

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容