1. 程式人生 > >SSM(SpringMVC Spring Mybatis)框架整合搭建

SSM(SpringMVC Spring Mybatis)框架整合搭建

1、新建一個web工程。

2、首先看一下整體的框架結構:

 

3、將ssm框架搭建所需要的jar包複製到lib目錄下

3、需要配置各個配置檔案。

1)配置web.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
http://www.springmodules.org/schema/cache/springmodules-cache.xsd
http://www.springmodules.org/schema/cache/springmodules-encache.xsd"
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>qzone</display-name> <welcome-file-list> <welcome-file>user.jsp</welcome-file> </welcome-file-list> <!-- spring配置檔案 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <!-- spring監聽器 --> <listener> <listener-class
>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 編碼過濾器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true
</async-supported> <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> <!-- 新增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:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>

 

2)在resource/spring下建立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/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
 
    <!-- 指定要掃描的包com.etc下的所有 -->
    <context:component-scan base-package="com.ekingwin.bas.cloud.user"></context:component-scan>
 
    <!-- 配置資料來源 
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/ssm"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>   -->
    <!-- 載入配置檔案 -->
    <context:property-placeholder location="classpath:*.properties" />
    <!-- 資料庫連線池 --> 
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
    </bean> 
 
    <!-- 配置service的事務切面 -->
    <aop:config>
        <aop:pointcut id="serviceOperation" expression="execution(* com.etc.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
    </aop:config>
 
    <!-- 配置mybatis的SessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- 自動掃描Mapper.xml檔案 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
        <!-- mybaits配置檔案 -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
    </bean>
    
    <!-- spring將mybatis下的sqlSessionFactory注入到daoceng -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ekingwin.bas.cloud"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
    
    <!-- 事務管理 -->
    <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="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="new*" propagation="REQUIRED" />
            <tx:method name="set*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="change*" propagation="REQUIRED" />
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />
            <tx:method name="load*" propagation="REQUIRED" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" read-only="true" />
        </tx:attributes>
    </tx:advice>
    
</beans>

3)在resource/spring下建立spring-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/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-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
    <!-- 指定註解要掃描的包 -->
    <context:component-scan base-package="com.ekingwin.bas.cloud.user.web"></context:component-scan>
    <!-- 檢視解析器,自動加上字首和字尾 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    

    <!-- Spring 來掃描指定包下的類,並註冊被@Component,@Controller,@Service,@Repository等註解標記的元件 -->
    <mvc:annotation-driven />
 
</beans>

4)在resource/mybatis下建立mybatis-config.xml配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration 
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 批量定義別名,使得com.etc.entity包下的所有bean都使用別名(別名就是類名,首字母大寫或小寫都可以) -->
    <typeAliases>
        <package name="com.ekingwin.bas.cloud"/>
    </typeAliases>
</configuration>

5)在resource下建立dbconfig.properties檔案:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=123456

6)在resource下建立log4j.properties檔案:

<span style="font-size:18px;">log4j.rootLogger=info,appender1,appender2
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
log4j.appender.appender2=org.apache.log4j.FileAppender
log4j.appender.appender2.File=D:/logFile.txt
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
log4j.appender.appender2.layout=org.apache.log4j.TTCCLayout</span>

7)在resource/mapper下建立UserMapper.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ekingwin.bas.cloud.user.dao.IUserDao">
<!-- <resultMap type="User" id="UserResult">
        <result property="id" column="id"/>
        <result property="username" column="username"/>
    <result property="password" column="password"/> 
    </resultMap>      -->
<!--      <select id="login" parameterType="User" resultMap="UserResult">
        select * from user where username=#{username}
    </select> -->
   <select id="getInfo" parameterType="String" resultType="map">
        select * from user where username=#{username}
    </select> 
</mapper>

8)在user/web下的到下建立UserController.java檔案:

package com.ekingwin.bas.cloud.user.web;
 
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ekingwin.bas.cloud.user.UserException;
import com.ekingwin.bas.cloud.user.dao.entity.User;
import com.ekingwin.bas.cloud.user.dto.UserDto;
import com.ekingwin.bas.cloud.user.service.IUserService;
import com.ekingwin.bas.cloud.user.service.impl.UserServiceImpl;




//@RestController
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
//    @Qualifier(value = "userMetaServiceImpl")
    private IUserService userService;
    
//    
//    @Resource
//    private UserServiceImpl userService;
    
//    @RequestMapping(value = "/login", method = RequestMethod.POST)
//    public String login(UserDto user) throws UserException{
//        System.out.println("123123");
//        return     userService.getmessage(user);
//        }
    
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login (@RequestBody UserDto user) throws UserException{
        System.out.println("123123");
        return     userService.getmessage(user);
//        User resultUser = userService.login(user);
//        if(resultUser == null){
//            request.setAttribute("user", user);
//            request.setAttribute("errorMsg","使用者名稱或密碼錯誤");
//            return "index";
//        }else{
//            HttpSession session = request.getSession();
//            session.setAttribute("currentUser",user);
//            return "redirect:/success.jsp";
//        }
//        return  null;
    }
    
}

9)在user/service下建立IUserService.java:

package com.ekingwin.bas.cloud.user.service;

import javax.servlet.http.HttpServletRequest;

import com.ekingwin.bas.cloud.user.UserException;
import com.ekingwin.bas.cloud.user.dto.UserDto;

public interface IUserService {
    
    public String  getmessage(UserDto user) throws UserException;

}

10)在user/service/impl下建立UserServiceImpl.java檔案:

package com.ekingwin.bas.cloud.user.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import com.ekingwin.bas.cloud.user.UserException;

import com.ekingwin.bas.cloud.user.dao.IUserDao;
import com.ekingwin.bas.cloud.user.dao.entity.User;
import com.ekingwin.bas.cloud.user.dto.UserDto;
import com.ekingwin.bas.cloud.user.service.IUserService;


@Primary
@Service
public class UserServiceImpl implements IUserService{
    
//    @Resource
//    private UserDao userDao;
    
    @Autowired
    private IUserDao userDao;

    public User login(User user) {
        User users =  userDao.login(user);
        System.out.println("12313247092137498123");
         return users;
    }
    
    @Override
    public String getmessage(UserDto user) throws UserException {
        // TODO Auto-generated method stub
        
        String username = user.getUsername();
        List<Map<String, Object>>  list = userDao.getInfo(username);
        System.out.println(list);
        System.out.println("123123");
        return null;
    }
}


//@Service
//public class UserServiceImpl implements IUserService{
//
//
//    @Autowired
//    private UserDao userDao;
//
//    
//    @Override
//    public String getmessage(UserDto user) throws UserException {
////        String username = user.getUsername();
////        String username=user.getParameter("username");
////        List<Map<String,Object>> list =userDao.getInfo(username);
////        System.out.println(list.get(0).get("username"));
//        return null;
//    }
//    }

11)user/dto下建立UserDto.java檔案:

package com.ekingwin.bas.cloud.user.dto;

public class UserDto {
    private String id;
    private String username;
    private String password;
    private String company;
    private String age;
    private String sex;

    public String getId() {
        return id;
    }

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

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

 12)user/dao下建立IUserDao.java檔案:

package com.ekingwin.bas.cloud.user.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;

import com.ekingwin.bas.cloud.user.dao.entity.User;
import com.ekingwin.bas.cloud.utils.BasMapper;


public interface IUserDao extends BasMapper<User>{
    public User login(User user);
    public List<Map<String, Object>> getInfo(@Param("username")String username);
}

13)在user/dao/entity下建立User.java檔案:

package com.ekingwin.bas.cloud.user.dao.entity;

import javax.persistence.Id;
import javax.persistence.Table;

//@Table(name = "user")
public class User {

    @Id
    private String id;
    private String username;
    private String password;
    private String company;
    private String age;
    private String sex;

    public String getId() {
        return id;
    }

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

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

4、啟動Tomcat在瀏覽器上即可。