Spring+SpringMVC+MyBatis实现数据库连接的登录功能

来源:互联网 发布:阿里云企业邮箱升级 编辑:程序博客网 时间:2024/06/05 23:52

在使用SSM框架实现连接数据的登录功能时,

第一步首先导入相应的jar包,然后配置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配置文件 -->  <context-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:applicationContext.xml</param-value>  </context-param>  <!-- 监听器:通过监听器让Spring运行起来 -->  <!-- 给Spring配置一个监听器,让Spring运作起来 -->  <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>    <!-- SpringMVC的配置信息 -->  <!-- 通过servlet标签配置dispatcherServlet -->  <servlet>  <servlet-name>mvc</servlet-name>  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  <!-- 加载SpringMVC配置文件 -->  <init-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:servlet-mvc.xml</param-value>  </init-param>  <!-- 容器启动就加载这个servlet,第一个先要被运行  -->  <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>  <servlet-name>mvc</servlet-name>  <url-pattern>/</url-pattern>  </servlet-mapping>    <!-- 中文乱码解决 -->  <filter>  <filter-name>EncodingFilter</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>EncodingFilter</filter-name>  <url-pattern>/*</url-pattern>  </filter-mapping></web-app>
第二步,配置SpringMVC层配置文件servlet-mvc.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:aop="http://www.springframework.org/schema/aop"       xmlns:context="http://www.springframework.org/schema/context"      xmlns:jee="http://www.springframework.org/schema/jee"      xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:mvc="http://www.springframework.org/schema/mvc"      xsi:schemaLocation="            http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop.xsd          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/jee         http://www.springframework.org/schema/jee/spring-jee.xsd          http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd        http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx.xsd">    <!-- 使用注解的包,包括子集 --><context:component-scan base-package="com.jredu.controller" /><!-- 添加数据转换的注解驱动 -->    <mvc:annotation-driven>    <mvc:message-converters>    <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>    </mvc:message-converters>    </mvc:annotation-driven><!-- 视图解析器 --><bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/" /><property name="suffix" value=".jsp"></property></bean><!-- 上传组件 -->    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <!-- 设置上传的编码格式 -->    <property name="defaultEncoding" value="utf-8"/>    <!-- 设置最大上传大小 -->    <property name="maxUploadSize" value="5242880"/>    </bean></beans>  
然后配置连接数据的DAO层的配置文件applicationContext.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:aop="http://www.springframework.org/schema/aop"       xmlns:context="http://www.springframework.org/schema/context"      xmlns:jee="http://www.springframework.org/schema/jee"      xmlns:tx="http://www.springframework.org/schema/tx"      xsi:schemaLocation="            http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop.xsd          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/jee        http://www.springframework.org/schema/jee/spring-jee.xsd          http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx.xsd">    <!-- 自动扫描 --><context:component-scan base-package="com.jredu.dao" /><context:component-scan base-package="com.jredu.service" /><context:component-scan base-package="com.jredu.entity"/><!-- 引入配置文件,可以使用${}语法,location:指定读取文件的路径 --><context:property-placeholder location="classpath:jdbc.properties"/><!-- 配置数据源 --><bean id="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"p:driverClass="${jdbc.driverClassName}"p:jdbcUrl="${jdbc.url}"p:user="${jdbc.username}"p:password="${jdbc.password}"p:initialPoolSize="${jdbc.initialSize}"p:maxPoolSize="${jdbc.maxActive}"/><!-- 配置mybatis的sqlSessionFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><!-- 自动扫描mappers.xml文件 --><property name="mapperLocations" value="classpath:mybatis/mappers/*.xml"></property><!-- mybatis配置文件 --><property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property></bean><!-- DAO接口所在包名,Spring会自动查找其下的类 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.jredu.dao" /><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property></bean><!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><!-- 配置事务通知属性 -->  <tx:advice id="txAdvice" transaction-manager="transactionManager"><!-- 定义事务传播属性 -->  <tx:attributes><tx:method name="add*" propagation="REQUIRED" /><tx:method name="append*" propagation="REQUIRED" /><tx:method name="insert*" propagation="REQUIRED" /><tx:method name="save*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="modify*" propagation="REQUIRED" /><tx:method name="edit*" propagation="REQUIRED" /><tx:method name="delete*" propagation="REQUIRED" /><tx:method name="remove*" propagation="REQUIRED" /><tx:method name="repair" propagation="REQUIRED" /><tx:method name="delAndRepair" propagation="REQUIRED" /><tx:method name="get*" propagation="SUPPORTS" /><tx:method name="find*" propagation="SUPPORTS" /><tx:method name="load*" propagation="SUPPORTS" /><tx:method name="search*" propagation="SUPPORTS" /><tx:method name="datagrid*" propagation="SUPPORTS" /><tx:method name="*" propagation="SUPPORTS" /></tx:attributes></tx:advice>    <!-- 配置事务切面 -->      <aop:config>          <aop:pointcut id="serviceOperation"              expression="execution(* com.jredu.service.*.*(..))" />          <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />      </aop:config>  <!-- 异常统一处理 -->    <!-- <bean id="exceptionResolver" class="com.jredu.util.HandlerException"/> --></beans>
第三步,编写实体类User.java
public class User {private int id;private String name;private String pwd;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}}
在src下创建文件夹mybatis,并编写配置文件mybatis-config.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.jredu.entity"/></typeAliases></configuration>
第四步,在控制层(controller)编写控制类UserController.java

import java.util.Map;import javax.servlet.http.HttpSession;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.jredu.entity.User;import com.jredu.service.UserService;@Controller@RequestMapping("user")public class UserController {@Autowiredprivate UserService service;@RequestMapping("login.do")public String login(User user,Map<String,Object> map,HttpSession session){//业务逻辑层,返回模型数据User realUser=service.getUser(user);if (realUser!=null) {//把用户数据保存在session中session.setAttribute("user", user);//登录成功return "success";}else {//登录失败map.put("error", "账号或密码错误");return "login";}}}
调用业务处理层service层UserService.java

import com.jredu.entity.User;/** * 用户业务处理 * @author Administrator * */public interface UserService {/** * 将前台拿到的User到dao层查询,返回User类型 * @param user * @return */User getUser(User user);}
对service层接口实现UserServiceImpl.java,并调用dao层
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.authentication.encoding.Md5PasswordEncoder;import org.springframework.stereotype.Service;import com.jredu.dao.UserDao;import com.jredu.entity.User;import com.jredu.service.UserService;@Servicepublic class UserServiceImpl implements UserService{@Autowiredprivate UserDao dao;@Overridepublic User getUser(User user) {// TODO Auto-generated method stub//调用dao层查询结果return dao.selectByCondition(user);}}
第五步,dao层UserDao.java

import com.jredu.entity.User;public interface UserDao {User selectByCondition(User user);}
在刚建的文件夹mybatis下创建文件夹mybatis.mappers,并编写对数据库的操作的配置文件UserDao.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"><!-- namespace对应接口地址 --><mapper namespace="com.jredu.dao.UsersDao"><select id="selectByCondition" parameterType="User" resultType="User">select * from users where name=#{name} and pwd=#{pwd}</select></mapper> 
一个完整的运用SSM框架的登录操作就分为这几步,

还有一个重要的点是,连接数据库(Oracle)的文件jdbc.properties,放在src下

jdbc.driverClassName=oracle.jdbc.driver.OracleDriverjdbc.url=jdbc\:oracle\:thin\:@localhost\:1521\:orcljdbc.username=mybatisjdbc.password=12345#\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570  jdbc.initialSize=0  #\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570    jdbc.maxActive=20  #\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2    jdbc.maxIdle=20  #\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2  jdbc.minIdle=1  #\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4  jdbc.maxWait=60000  

阅读全文
0 0
原创粉丝点击