Spring+SpringMVC+Mybatis简单配置和使用

之前做的项目一直使用SSM框架开发,用了几个月的SSM,个人感觉搭建起来比较简单也非常好用,之前自己也搭过小型的ssm但没记录下来,正好写ftp+nginx+fileinput的时候需要用到,所以又整理了一次就记录了下来。

SSM整合

一、配置文件

  1. 需要的JAR包

    Spring+SpringMVC+Mybatis简单配置和使用_第1张图片

  2. 创建编写jdbc配置文件jdbc.properties
    #JDBC Configure
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/test
    jdbc.username=root
    jdbc.password=123456
  1. 建立配置spring-mybatis文件

<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-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/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
      
      <context:component-scan base-package="com.xw.demo">context:component-scan>
      
      <bean id="jdbcConfigure" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:jdbc.properties">property>
      bean>
      
      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="${jdbc.driver}">property>
            <property name="url" value="${jdbc.url}">property>
            <property name="username" value="${jdbc.username}">property>
            <property name="password" value="${jdbc.password}">property>
      bean>
      
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" value="dataSource">property>
            
            <property name="mapperLocations" value="classpath:com/xw/demo/dao/mapper/*.xml">property>
      bean>
      
      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.xw.demo.dao">property>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
      bean>
      
      <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource">property>
      bean>
  beans>
  1. 建立配置spring-mvc文件

<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-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/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
       
     <context:component-scan base-package="com.xw.demo.controller">context:component-scan>
     
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/">property>
        <property name="suffix" value=".jsp">property>
     bean>
     
     <mvc:annotation-driven>mvc:annotation-driven>
     
     <mvc:resources location="/js/" mapping="/js/**"/>
     <mvc:resources location="/image/" mapping="/image/**"/>
     <mvc:resources location="/css/" mapping="/css/**"/>
beans>
  1. 配置web.xml文件
    
<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"  
    version="3.0">  
  <display-name>display-name> 
    
    <context-param>
        <param-name>contextConfigLocationparam-name>  
        <param-value>classpath:spring-mybatis.xmlparam-value>  
    context-param>
    
    <filter>  
        <filter-name>encodingFilterfilter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
        <async-supported>trueasync-supported>  
        <init-param>  
            <param-name>encodingparam-name>  
            <param-value>UTF-8param-value>  
        init-param>  
    filter>  
    <filter-mapping>  
        <filter-name>encodingFilterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
    listener>
    
    <servlet>
        <servlet-name>SpringMVCservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>  
            <param-name>contextConfigLocationparam-name>  
            <param-value>classpath:spring-mvc.xmlparam-value>  
        init-param>  
        <load-on-startup>1load-on-startup>  
        <async-supported>trueasync-supported>  
    servlet>
    <servlet-mapping> 
        <servlet-name>SpringMVCservlet-name>
        <url-pattern>/url-pattern>    
    servlet-mapping>  
    <welcome-file-list>
        <welcome-file>/index.jspwelcome-file>
    welcome-file-list> 
web-app>
  1. 建立配置日志记录文件log4j.properties
log4j.rootLogger=INFO,Console,File  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  

log4j.appender.File = org.apache.log4j.RollingFileAppender  
log4j.appender.File.File = logs/ssm.log  
log4j.appender.File.MaxFileSize = 10MB  
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n  

关于上面的几个配置文件可以参照博文http://blog.csdn.net/mrslw/article/details/52824145的详细介绍,上面每个配置的功能介绍是比较详细的。

二、功能编写

上面的配置文件配置好后接下来就做一个简单的用户登录系统
建立的文件结构:

Spring+SpringMVC+Mybatis简单配置和使用_第2张图片
User.java文件:

package com.xw.demo.domain;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = -5383127837792395250L;
    //用户ID
    private Integer id;
    //用户名
    private String username;
    //用户密码
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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;
    }

}

UserMapper代码:

    
  

<mapper namespace="com.xw.demo.dao.UserDao">
    <resultMap type="com.xw.demo.domain.User" id="UserMap">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
    resultMap>
    
    <select id="selectByUsername" resultMap="UserMap" parameterType="String" resultType="com.xw.demo.domain.User">
        SELECT * FROM TB_USER WHERE USERNAME = #{username};
    select>
mapper>

UserDao代码:

package com.xw.demo.dao;

import com.xw.demo.domain.User;

public interface UserDao {
    /**
     * 根据用户名查询
     * @param username 用户名
     * @return
     */
    public User selectByUsername(String username);
}

UserService代码:

package com.xw.demo.service;

import com.xw.demo.domain.User;

public interface UserService {
    /**
     * 根据用户名查询
     * @param username 用户名
     * @return
     */
    public User selectByUsername(String username);
}

UserServiceImpl代码:

package com.xw.demo.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.xw.demo.dao.UserDao;
import com.xw.demo.domain.User;
import com.xw.demo.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    /**
     * 根据用户名查询
     * @param username 用户名
     * @return user 用户集合
     */
    public User selectByUsername(String username) {
        User user = userDao.selectByUsername(username);
        return user;
    }

}

登录页面:
Spring+SpringMVC+Mybatis简单配置和使用_第3张图片
代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<html>
  <head>
    <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" href="https://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">  
    <script src="https://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js">script>
    <script src="https://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js">script>

  head>

  <body>
    <div style="padding: 300px 100px 10px;" align="center">
        <form class="bs-example bs-example-form" name="login_form" id="login_form">
            <div class="input-group">
                <span class="input-group-addon" style="width:67px;">用户名span>
                <input type="text" name="username" id="username" class="form-control" placeholder="请输入您的用户名" />
            div>
            <div style="margin:10px">div>
            <div class="input-group">
                <span class="input-group-addon" style="width:67px;">密   码span>
                <input type="text" name="password" id="password" class="form-control" placeholder="请输入您的密码" />
            div>
            <div style="margin:10px">div>
            <div>
                <button type="button" style="width:265px;" name="login_btn" id="login_btn" class="btn btn-primary" data-toggle="button">登录button>
            div>
        form>
    div>
  body>
  <script type="text/javascript">
        $(function() {
            $("#login_btn").click(function(){
                $("#login_form").submit();
            });
            $("#login_form").ajaxForm({
                url:"/SSM/user/loginCheck",
                dataType:"json",
                type:"post",
                success:function(data){
                    alert(data.message);
                }
            });
        });
  script>
html>

Controller层编写

package com.xw.demo.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xw.demo.domain.User;
import com.xw.demo.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    private final static String LOGIN_PAGE = "/login";

    @RequestMapping(value = "/login",method=RequestMethod.GET)
    public String tologin(){
        return LOGIN_PAGE;
    }

    @RequestMapping(value = "/loginCheck", method = RequestMethod.POST)
    @ResponseBody
    public Map login(String username,String password){
        Map map = new HashMap();
        User user = userService.selectByUsername(username);
        if(user != null && user.getPassword().equals(password)){
            map.put("message", "登陆成功!");
        }else{
            map.put("message", "用户名或者密码错误!");
        }
        return map;
    }
}

三、功能测试

输入正确的用户名和密码:
Spring+SpringMVC+Mybatis简单配置和使用_第4张图片
输入错误的用户名和密码:
Spring+SpringMVC+Mybatis简单配置和使用_第5张图片
到这里整个SSM环境下的登录验证就完成了。

你可能感兴趣的:(SSM)