ssm-ssm整合(springmvc+mybatis)
来源:互联网 发布:论文数据造假的多吗 编辑:程序博客网 时间:2024/05/20 16:32
ssm框架整合在如今是很常用的,前面我们已经讲解过ssm2以及sm的整合,那么今天我们讲解一下ssm的整合。
同样的,我们以一个用户登录的案例进行讲解。
项目结构如下所示:
数据库表结构:
id-intusername-varcharpassword-varchar
项目源码下载:点击下载
war包下载:点击下载
项目演示视频地址:点击观看
开发工具:
eclipse neon
tomcat7.0
Mybatis3.2.7
Spring3.2
jdk1.7
同样的,项目包括view、Service、Model三层,那么我们从小至上进行开发,即model-service-view
Model层
1、相关资源文件
log4j文件:
# Global logging configuration#在开发环境下日志级别要设置成DEBUG,生产环境设置成info或errorlog4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
db.properties文件:
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://127.0.0.1/bs?character=utf-8jdbc.username=rootjdbc.password=0707
2、Mybatis配置文件SqlMapConfig.xml编写
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><typeAliases><package name="com.sw.po"/></typeAliases></configuration>
3、编写po对象文件
package com.sw.po;/* *@Author swxctx *@time 2017年5月15日 *@Explain:用户表po对象 *id:编号 *username:用户名 *password:密码 */public class User {private int id;private String username;private String password;public int getId() {return id;}public void setId(int id) {this.id = id;}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;}}
4、编写mapper.java文件
package com.sw.mapper;/* *@Author swxctx *@time 2017年5月15日 *@Explain:Mapper接口 */public interface UserMapper {/*用户登录:根据用户名查找用户密码,检查是否匹配进行登录*/public String findPassByName(String username)throws Exception;}
5、编写mapper.xml文件
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.sw.mapper.UserMapper"><!-- 用户登录(根据用户名查找返回密码,校验) --><select id="findPassByName" parameterType="String" resultType="String">select password from user where username=#{username}</select></mapper>
6、编写applicationContext-dao文件,用于spring容器管理mapper以及整合mybatis
<?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.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/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 "><!-- 加载配置文件 --><context:property-placeholder location="classpath:db.properties"/><!-- 配置注解自动扫描范围 --> <!-- <context:component-scan base-package="com.sw.mapper"></context:component-scan> --> <!-- 自动装配 --> <!-- <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> --><!-- 数据库连接池 --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/><property name="maxActive" value="10"/><property name="maxIdle" value="5"/></bean><!-- 管理mybatis --><!-- mapper配置 --><!-- 让spring管理sqlsessionfactory 使用mybatis-spring.jar --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 数据库连接池 --><property name="dataSource" ref="dataSource" /><!-- 加载mybatis的全局配置文件 --><property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /></bean><!-- mapper扫描(自动扫描) --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 扫描的包名 --><property name="basePackage" value="com.sw.mapper"></property><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property></bean></beans>
至此,Model层的开发已经完成,我们进行一下测试,如下:
package com.sw.test;import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.sw.mapper.UserMapper;/* *@Author swxctx *@time 2017年5月15日 *@Explain:Spring与Mybatis整合测试-dao */public class UserDaoTest {private ApplicationContext applicationContext;@Beforepublic void setUp() throws Exception {//springapplicationContext = new ClassPathXmlApplicationContext("classpath:/spring/applicationContext-dao.xml");}@Testpublic void test() throws Exception {UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");String pass=userMapper.findPassByName("bs");System.out.println(pass);}}
测试结果如下图:
如上图所示,Mybatis与Spring的整合已经完成,可以正常运行,model层至此开发完毕,接下来进行Service层的开发。
Service层
Service层主要包括Service接口以及Service实现类,通过Spring管理Service层的实现类。
1、编写Service层接口
package com.sw.service;/* *@Author swxctx *@time 2017年5月15日 *@Explain:Service层接口 */public interface UserService {public final static String SERVICE_NAME="UserServiceImpl";/*用户登录验证*/public String findLoginCheck(String username)throws Exception;}
2、编写Service实现类
package com.sw.service.impl;import org.springframework.stereotype.Service;import com.sw.container.SwServiceProvider;import com.sw.mapper.UserMapper;import com.sw.service.UserService;/* *@Author swxctx *@time 2017年5月15日 *@Explain:Service层接口实现类 */@Servicepublic class UserServiceImpl implements UserService{//登录检查@Overridepublic String findLoginCheck(String username) throws Exception {UserMapper userMapper=(UserMapper) SwServiceProvider.getService("userMapper");String pass = userMapper.findPassByName(username);return pass;}}
3、将Service层实现类放入spring管理,编写applicationContext-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: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.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/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 "><!-- Service层配置 --><!-- 配置注解自动扫描范围 --> <!-- <context:component-scan base-package="com.sw"></context:component-scan> --><!-- Servic层方法实现配置 --> <bean id="UserServiceImpl" class="com.sw.service.impl.UserServiceImpl"></bean></beans>
4、接下来我们需要通过Spring控制事务,编写applicationContext-transaction.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.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/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 "><!-- 事务控制 --><!-- 事务管理器 对mybatis操作数据库事务控制,spring使用jdbc的事务控制类--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 数据源dataSource在applicationContext-dao.xml中配置了 --><property name="dataSource" ref="dataSource"/></bean><!-- 通知 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><!-- 传播行为 --><tx:method name="save*" propagation="REQUIRED"/><tx:method name="delete*" propagation="REQUIRED"/><tx:method name="insert*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="find*" propagation="SUPPORTS" read-only="true"/><tx:method name="get*" propagation="SUPPORTS" read-only="true"/><tx:method name="select*" propagation="SUPPORTS" read-only="true"/></tx:attributes></tx:advice><!-- aop --><aop:config><aop:advisor advice-ref="txAdvice" pointcut="execution(* com.sw.service.impl.*.*(..))"/></aop:config></beans>
5、接下来我们需要在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-template</display-name> <!-- spring配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
如上,service层的配置也已经完毕,接下来,介绍一个加载spring配置文件的小程序,主要用于每次获取bean时加载配置文件,避免每次加载所造成的资源浪费,当然在这里也可以使用@Autowired来进行自动装配加载,但是我个人比较习惯配置的方式,接下来编写工具类,如下:
加载配置文件:
package com.sw.container;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/* *@Author swxctx *@time 2017年5月15日 *@Explain:服务类,用用户加载applicationContext.xml文件 */public class ServiceProvideCord {protected static ApplicationContext applicationContext;public static void load(String[] fileName){applicationContext = new ClassPathXmlApplicationContext(fileName);}}
获取service:
package com.sw.container;import org.apache.commons.lang.StringUtils;/* *@Author swxctx *@time 2017年5月15日 *@Explain:Service层服务类 */@SuppressWarnings("static-access")public class SwServiceProvider {private static ServiceProvideCord serviceProvideCord;//静态加载static{serviceProvideCord = new ServiceProvideCord();serviceProvideCord.load(new String[]{"classpath:/spring/applicationContext-service.xml","classpath:/spring/applicationContext-dao.xml","classpath:/spring/applicationContext-transaction.xml"});}public static Object getService(String serviceName){//服务名称为空if(StringUtils.isBlank(serviceName)){throw new RuntimeException("当前服务名称不存在...");}Object object = null;if(serviceProvideCord.applicationContext.containsBean(serviceName)){//获取beanobject = serviceProvideCord.applicationContext.getBean(serviceName);}if(object==null){throw new RuntimeException("服务名称为【"+serviceName+"】下的服务节点不存在...");}return object;}}
在这里使用的是数组加载多个配置文件。
接下来我们可以进行测试了,如下:
package com.sw.test;import org.junit.Test;import com.sw.container.SwServiceProvider;import com.sw.service.UserService;/* *@Author swxctx *@time 2017年5月15日 *@Explain:Service层测试 */public class UserServiceTest {@Testpublic void testLogin() throws Exception {UserService userService = (UserService) SwServiceProvider.getService("UserServiceImpl");String pass=userService.findLoginCheck("bs");System.out.println(pass);}}
从上面的代码我们可以看到,这里使用了工具类SwServiceProvider来对bean进行获取,测试结果如下:
如上所示,配置成功,接下来可以进行view层的开发了。
View层
view层使用Springmvc来对表单进行处理,在这里使用的是注解的方式进行Controller的开发,在这里各有所长,也可以根据自己的喜好选择配置文件的方式,或者继承Request进行开发。
1、编写登录界面
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body><form action="logincheck.action" mephod="post">用户:<input type="text" id="username" name="username" placeholder="用户名"><br>密码:<input type="password" id="password" name="password" placeholder="密码" ><br><input type="submit" value="提交"></form></body></html>
2、成功界面
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>success</title></head><body><p>登录成功</p></body></html>
3、编写失败界面
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>err</title></head><body><p>登录失败</p></body></html>
4、进行controller的开发
首先我们需要在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: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.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/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 "><!-- 扫描controller --><context:component-scan base-package="com.sw.controller"></context:component-scan><!-- 使用注解的方式开发 --><!-- 配置适配器与映射器-通过drivern进行综合 --><mvc:annotation-driven></mvc:annotation-driven><!-- 配置视图解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 配置页面路径的前缀 --><property name="prefix" value="/WEB-INF/page/"/><!-- 配置jsp路径的后缀 --><property name="suffix" value=".html"/></bean></beans>
5、进一步在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-template</display-name> <!-- spring配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置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/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping></web-app>
如上web.xml为最终整体的配置。
6、接下来需要编写vo对象,用于映射表单的数据(这里更简洁的办法为使用SpringMVC的参数绑定,即不需要编写此文件,在实际开发中也应该使用参数绑定,通过User类注入即可,不用再编写UserForm类),如下
package com.sw.view.form;/* *@Author swxctx *@time 2017年5月16日 *@Explain:vo对象 */public class UserForm {private String username;private String password;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;}}
7、最后可以进行Controller的开发了,如下:
package com.sw.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.sw.container.SwServiceProvider;import com.sw.service.UserService;import com.sw.view.form.UserForm;/* *@Author swxctx *@time 2017年5月16日 *@Explain:完成登录相关工作 */@Controllerpublic class LoginController{//vo对象//UserForm userForm = new UserForm();//serviceUserService userService = (UserService) SwServiceProvider.getService(UserService.SERVICE_NAME);//登录验证@RequestMapping("/logincheck")public ModelAndView loginCheck(UserForm userForm)throws Exception{String pass = userService.findLoginCheck(userForm.getUsername());ModelAndView modelAndView = new ModelAndView();//判断if(userForm.getPassword().equals(pass)){modelAndView.setViewName("login/success");}else{modelAndView.setViewName("login/err");}return modelAndView;}}
至此,ssm的整合已经完成了,接下来我们到浏览器测试一下。
登录界面:
登录成功:
登录失败:
结语:ssm的整合开发其实与ssh以及ssm2大同小异,其基本原理都是mvc,将项目分层开发,分层管理,从model到service再到view,其实就是一个用户的操作过程逆向;获取数据、装配数据、显示数据,按照这一规律进行开发,则已经很明了。
在本文中,其实并不适合学习,可以下载源码进行相关的测试,更深入的学习,本章仅仅进行了整合,并没有考虑资源的分配以及各种优化配置。
个人观点,请多指教。
- ssm-ssm整合(springmvc+mybatis)
- SSM(Spring+SpringMVC+MyBatis)整合
- spring、springmvc、mybatis整合(SSM)
- SSM(spring+mybatis+springmvc)整合 配置文件
- SSM整合(SpringMVC+Spring+Mybatis)
- SSM框架整合(Spring+SpringMVC+MyBatis)
- SSM框架(springmvc+spring+mybatis)整合
- SSM框架整合(Spring+SpringMVC+Mybatis)
- Spring SpringMVC Mybatis(SSM+Oracle整合)
- SSM框架整合(Spring+SpringMVC+MyBatis)
- SSM整合(SpringMVC,Spring,Mybatis)
- SSM(spring+springMVC+mybatis)整合配置
- ssm(spring+springmvc+mybatis)整合
- SSM框架整合(Spring+SpringMVC+MyBatis)
- SSM整合(SpringMVC、Spring、Mybatis)
- SSM(Spring+SpringMVC+Mybatis) 整合
- SSM(spring+springMVC+Mybatis)简单整合
- SSM整合(springmvc + spring + mybatis)
- tf.Variable函数的用法
- Linux终端设置成256色模式
- proteus入门学习(by 朱玲)
- P1208 犯罪团伙(超大数据)
- leetcode 576(week 12)
- ssm-ssm整合(springmvc+mybatis)
- Android目录结构
- 栈
- |poj 2186|强连通分量|Popular Cows
- 在 Laravel 5 中使用 Repository 模式实现业务逻辑和数据访问的分离
- Solr查询参数echoParams
- class.getResource与class.getClassLoader().getResource使用
- IntellijIdea创建Maven-Struts2的web项目
- JSTL标准标签库之核心标签(三)