SSM(Spring+SpringMVC+Mybatis)登录实例

来源:互联网 发布:sql sever设置主键自增 编辑:程序博客网 时间:2024/05/21 01:31

1.创建Web Project项目
2.加载jar包

Mybatis和spring整合包:mybatis-spring-1.2.2.jar

Mybatis核心和Mybatis依赖包;

Spring的jar(包括springmvc的jar包);

数据库驱动包;

第三方数据库连接池;

点击下面链接可下载当前所需所有jar包:

点击打开链接

3.创建所需配置文件

创建Spring配置文件:
spring/applicationContext.xml:Spring配置文件(配置公用内容:数据源、事务);
spring/applicationContext-dao.xml:spring和mybatis整合的配置(SqlSessionFactory、mapper配置),配置与持久层相关接口的加载;
spring/applicationContext-service.xml:配置业务接口;
spring/springmvc.xml:springmvc的全局配置文件,整合过程中我们需要在这里配置组件扫描action,处理器映射器、处理器适配器和视图解析器。
创建Mybatis配置文件:
mybatis/SqlMapConfig.xml:mybatis全局配置文件。
配置文件:
log4j.properties:日志配置文件;
db.properties:数据库连接配置文件。

此项目目录如下:


4.properties配置文件源代码

log4j.properties配置文件基本不需要做任何修改。

# Global logging configurationlog4j.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://localhost:3306/databasenamejdbc.username=databaseusernamejdbc.password=databasepasswordjdbc.maxActive=3jdbc.maxIdle=1

5.准备环境

     在application.xml中配置数据源。

<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.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "><!-- 加载数据库连接配置文件 --><context:property-placeholder location="classpath:db.properties" /><!-- 数据库连接处dbcp --><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}" /><!-- 开发阶段数据库最大连接数建议设置小一点够用即可,设置为3 --><property name="maxActive" value="${jdbc.maxActive}" /><property name="maxIdle" value="${jdbc.maxIdle}" /></bean></beans>
    由spring管理sqlSessionFactory,在applicationContext-dao.xml中进行如下配置。

<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.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "><!-- 配置SqlSessionFactory --><bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 数据源 --><property name="dataSource" ref="dataSource"/><!-- 配置SqlMapConfig.xml --><property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/></bean></beans>
    在web.xml中进行加载spring容器和post乱码处理等配置。
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"><display-name>mybatis1218_ssm</display-name><!-- 加载spring容器 --><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/spring/applicationContext.xml,/WEB-INF/classes/spring/applicationContext-*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- post乱码处理 --><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><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></web-app>

6.整合持久层

    将Mybatis和Spring整合,目标是将生成的mapper交由spring管理,sqlSessionFactory交由spring来创建。

    有两种方法,一种是原始DAO方法,创建dao接口和dao实现类,在applicationContext.xml中为dao创建相应bean;第二种是使用动态代理的方法,并且使用mapper批量扫描器扫描mapper接口。此项目使用第二种方法。

    先从Mybatis逆向工程开始。Mybatis是ORM框架(对象关系映射),及表与对象之间的映射,与Hibernate相同,但Mybatis是一个不完全ORM框架,因为它需要程序员去编写SQL语句,自动去完成向SQL中映射输入参数,SQL查询结果映射成java对象。逆向工程可以使用插件的方式,也可以使用JAVA程序的方式,这里使用后者,程序里的内容也是基本固定的,我们只需要根据需要修改里边的XML文件即可,执行逆向工程生成所需po类、mapper接口和mapper.xml文件,后两者要放在同一个包内。逆向工程程序可从下面下载。

    点击打开链接

  下面是我的逆向工程中修改后的generatorConfig.xml文件,主要修改数据库连接信息、mapper接口与mapper.xml映射文件生成位置、所需生成表与表生成位置。

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><context id="testTables" targetRuntime="MyBatis3"><commentGenerator><!-- 是否去除自动生成的注释 true:是 : false:否 --><property name="suppressAllComments" value="true" /></commentGenerator><!--数据库连接的信息:驱动类、连接地址、用户名、密码 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/safe_video" userId="root"password="password"></jdbcConnection><!-- Oracle连接信息 --><!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" userId="yycg"password="yycg"></jdbcConnection> --><!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!-- targetProject:生成PO类的位置 --><javaModelGenerator targetPackage="com.ssm.po"targetProject=".\src"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="false" /><!-- 从数据库返回的值被清理前后的空格 --><property name="trimStrings" value="true" /></javaModelGenerator>        <!-- targetProject:mapper映射文件生成的位置 --><sqlMapGenerator targetPackage="com.ssm.mapper" targetProject=".\src"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- targetPackage:mapper接口生成的位置 --><javaClientGenerator type="XMLMAPPER"targetPackage="com.ssm.mapper" targetProject=".\src"><!-- enableSubPackages:是否让schema作为包的后缀 --><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- 指定数据库表 --><table schema="" tableName="safe_user"></table><!-- 有些表的字段需要指定java类型 <table schema="" tableName=""><columnOverride column="" javaType="" /></table> --></context></generatorConfiguration>
        将生成的mapper包和po包放在src下,修改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><settings><!-- 开启延迟加载 --><setting name="lazyLoadingEnabled" value="true"/><setting name="aggressiveLazyLoading" value="false"/><!-- 打开二级缓存 --><setting name="cacheEnabled" value="true"/></settings><!-- 配置别名 --><typeAliases><!-- 批量扫描po --><package name="com.ssm.po"/></typeAliases><!-- 配置mapper映射文件 --><mappers></mappers></configuration>

          在applicationContext-dao.xml中配置mapper(让spring生成动态代理),在beans中加入以下配置。

        <!-- 使用mapper批量扫描器扫描mapper接口规则:mapper.xml和mapper.java在一个目录 且同名即可 扫描出来mapper,自动让spring容器注册,bean的id就是mapper类名(首字母小写) --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 会话工厂 --><property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>  <!-- 扫描包路径   多个包中间用半角逗号分隔   --><property name="basePackage" value="com.ssm.mapper"/></bean>

7.整合业务层

    由Spring管理Service,Service通过Spring调用mapper,有Spring进行事务配置。

    开发Service接口。

package com.ssm.service;import com.ssm.po.SafeUser;public interface UserService {/** * 登录验证 * @param type 登录账号类型 * @param account 登录账号 * @param userPassword 密码 * @return  validate true通过 false未通过 * @throws Exception */public SafeUser loginValidate(String type, String account, String userPassword) throws Exception;}
        开发Service实现类,使用@Autowired注解自动注入mapper对象。

package com.ssm.service.impl;import java.util.ArrayList;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import com.ssm.mapper.SafeUserMapper;import com.ssm.po.SafeUser;import com.ssm.po.SafeUserExample;import com.ssm.service.UserService;public class UserServiceImpl implements UserService {@AutowiredSafeUserMapper safeUserMapper;@Overridepublic SafeUser loginValidate(String type, String account,String userPassword) throws Exception {List<SafeUser> users = new ArrayList<SafeUser>();//定义查询对象SafeUserExample userExample = new SafeUserExample();SafeUserExample.Criteria criteria = userExample.createCriteria();if (type.equals("tel")) {//使用手机登录criteria.andUserTelEqualTo(account);}else if (type.equals("email")) {//使用邮箱登录criteria.andUserEmailEqualTo(account);}else if (type.equals("id")) {//使用ID登录criteria.andUserIdEqualTo(account);}else {return null;}criteria.andUserPasswordEqualTo(userPassword);users = safeUserMapper.selectByExample(userExample);if(users.size()==1) {//找到一条记录,用户存在return users.get(0);}return null;}}
        将Service借口交由Spring管理,在applicationContext-service.xml进行如下配置。

<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.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "><!-- 用户管理 --><bean id="userService" class="com.ssm.service.impl.UserServiceImpl"></bean></beans>
        采用声明式事务配置,在applicationContext.xml中配置事务。

<!-- 事务管理器,mybatis使用jdbc事务管理--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 数据源 --><property name="dataSource" ref="dataSource" ></property></bean><!-- 通知 --><tx:advice id="txAdvice" transaction-manager="transactionManager" ><!-- 配置传播行为 --><tx:attributes><tx:method name="save*" propagation="REQUIRED" rollback-for="Exception" /><tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception"/><tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/><tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/><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.ssm.service.impl.*.*(..))"/></aop:config>

8.整合控制层

        在action中通过Spring调用Service。

        在web.xml中配置SpringMVC的前端控制器。

<!-- 前端控制器 --><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- contextConfigLocation指定 springmvc的全局配置文件 如果 contextConfigLocation不指定,默认找配置文件名称:servlet的name+"-servlet.xml" --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/springmvc.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>*.action</url-pattern></servlet-mapping>
        配置springmvc.xml。

<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.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "><!-- 组件扫描action --><context:component-scan base-package="com.ssm.action"></context:component-scan><!-- 处理器映射器 处理器适配器 --><mvc:annotation-driven></mvc:annotation-driven><!-- 视图解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 视图的前缀 --><property name="prefix" value="/WEB-INF/jsp/" /><!-- 视图的后缀 --><property name="suffix" value=".jsp" /></bean></beans>
        编写action,使用注解开发,在action包下创建UserAction.class,进行登录验证,如果成功就通过视图解析器进入“WEB-INF/jsp/test.jsp”,如果失败进入index.jsp。

package com.ssm.action;import javax.servlet.http.HttpSession;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 com.ssm.po.SafeUser;import com.ssm.service.UserService;@Controller@RequestMapping("/user")public class UserAction {@Autowiredprivate UserService userService;@RequestMapping("/login")public String loginVailet(Model model, HttpSession session, String account, String pwd) throws Exception {SafeUser user = new SafeUser();user = userService.loginValidate("tel", account, pwd);if (user!=null) {session.setAttribute("user", user);return "test";}return "redirect:../index.jsp";}}

9.编写界面

        成功页面test.jsp,路径为WEB-INF/jsp/test.jsp。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>主页</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>   ${user.userTel }  </body></html>
        index.jsp为登录页面,放在WebRoot下。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>登录</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>    <form action="${pageContext.request.contextPath}/user/login.action" method="post" onsubmit="return logincheck();"><div class="login_row login_row_text"><label id="login_lab_user" class="login_lab">账号</label><input id="loginname" class="itext" type="text" name="account" tabindex="1" autocomplete="off"placeholder="邮箱/用户名/已验证手机"></div><div class="login_row login_row_text"><label id="login_lab_pwd" class="login_lab">密码</label><input id="signpwd" class="itext" type="password" name="pwd" tabindex="2" autocomplete="off"placeholder="密码"></div><div class="login_row"><input id="autologin" type="checkbox" name="autologin" tabindex="3"><label>自动登录</label><span id="spanfor"><a target="_blank">忘记密码?</a></span></div><div class="login_row"><input id="loginbut" type="submit" name="login_sub" value="登       录" tabindex="4"></div><div id="meserror"><ul id="meserrorul"></ul></div></form>  </body></html>
前端控制器中过滤.action后缀的请求,通过SpringMVC配置文件springmvc.xml中context:component-scan扫描到到相应action中执行。

        接下来进入登录页面即index.jsp中测试即可。

        下面是工程源代码。

        点击打开链接








原创粉丝点击