Spring=SpringMVC-Spring-MyBatis=SSM框架整合

一.SSM框架整合

需求:使用ssm框架完成對account表的增刪改查操作。

(1)搭建Mybatis環境:

1.確定數據庫 和表

CREATE DATABASE /*!32312 IF NOT EXISTS*/`spring_db` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `spring_db`;

/*Table structure for table `account` */

DROP TABLE IF EXISTS `account`;

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `money` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

/*Data for the table `account` */

insert  into `account`(`id`,`name`,`money`) values (1,'tom',1000),(2,'jerry',1000);

2.創建web模塊,導入相關座標:

<!--依賴管理-->
<dependencies>
    <!--mybatis相關座標-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.15</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.1</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

Account實體

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {

    private Integer id;

    private String name;

    private Double money;
}

AccountDao接口和映射

public interface AccountDao {

    public List<Account> findAll();
}

同時在resources資源裏面創建mybaits相關的AccountDao.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.wsl.dao.AccountDao">

   <select id="findAll" resultType="com.wsl.domain.Account">
        select * from account
    </select>

</mapper>

SqlMapConfig.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>

    <!--加載properties屬性文件-->
    <properties resource="jdbc.properties"></properties>

    <!--設置java類型別名-->
    <typeAliases>
        <package name="com.wsl.domain"></package>
    </typeAliases>

    <!--環境配置-->
    <environments default="mysql">
        <!--mysql環境-->
        <environment id="mysql">
            <!--使用JDBC類型事務管理器 -->
            <transactionManager type="JDBC"></transactionManager>
            <!--使用連接池 POOLED-->
            <dataSource type="POOLED">
                <property name="driver" 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>
            </dataSource>
        </environment>
    </environments>
    <!--加載映射文件-->
    <mappers>
        <package name="com.wsl.dao"></package>
    </mappers>
</configuration>

測試:

public class MyBatisTest {

    @Test
    public void test01() throws Exception {
        // 1.加載核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 2.構建工廠對象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        // 3.創建會話對象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 4.創建代理對象
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        // 5.查詢
        List<Account> list = accountDao.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
        // 6.釋放資源
        sqlSession.close();
    }
}

此時搭建MyBatis環境完畢

 

(2)搭建spring環境

1.導入spring座標

<!--spring相關座標-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>

2.AccountService接口和實現

public interface AccountService {

    List<Account> findAll();
}

@Service
public class AccountServiceImpl implements AccountService {

    @Override
    public List<Account> findAll() {
        System.out.println("AccountServiceImpl執行了...");
        return null;
    }
}

3.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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
       	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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--開啓註解組件掃描-->
    <context:component-scan base-package="com.wsl.service"/>


</beans>

測試:

@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void test01()throws Exception{
        List<Account> list = accountService.findAll();
    }
}

 

(3)spring整合MyBatis環境

思想:

原來我們使用mybatis框架,需要手動創建 sqlSessionFactory 、 sqlSession 、accountDao代理對象,被spring整合後,這些對象的創建權都交給ioc容器,我們的service層就可以直接使用@Autowired 完成依賴注入,整合就搞定了

MyBatis分析:

整合:

1.導入整合座標:

<!--spring整合mybatis座標-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.2</version>
</dependency>

<?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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
       	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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--開啓註解組件掃描-->
    <context:component-scan base-package="com.wsl.service"/>

    <!--加載第三方配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--配置連接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>


    <!--配置SqlSessionFactoryBean-->
    <bean id="sessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定連接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 指定實體類型別名 -->
        <property name="typeAliasesPackage" value="com.wsl.domain"/>
        <!-- 加載mybatis的核心配置文件,如果mybatis核心配置空了,這一步可以省略....-->
        <property name="configLocation" value="classpath:SqlMapConfig.xml"/>
    </bean>


    <!--配置dao層接口代理對象掃描-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wsl.dao"/>
    </bean>

</beans>

修改AccountService實現

@Service
public class AccountServiceImpl implements AccountService {

    // 依賴AccountDao
    @Autowired
    private AccountDao accountDao;

    @Override
    public List<Account> findAll() {
          return accountDao.findAll();
    }
}

測試:

@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void test01()throws Exception{
        List<Account> list = accountService.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
    }
}

測試通過:

總結:

 

(4)搭建SpringMVC環境

導入springMVC座標

<!--springMVC座標-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

導入相關頁面資源:

web.xml

前端控制器,中文過濾器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!--前端控制器-->
    <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-mvc.xml</param-value>
        </init-param>
        <load-on-startup>4</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!--post請求中文過濾器-->
    <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>

spring-mvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">

    <!--開啓註解組件掃描-->
    <context:component-scan base-package="com.wsl.web"></context:component-scan>
    <!--開啓mvc註解支持-->
    <mvc:annotation-driven></mvc:annotation-driven>

   
</beans>

 

AccountController和list.jsp頁面

@RequestMapping(value = "/account", name = "賬戶模塊")
public class AccountController {

    @RequestMapping(value = "/findAll", name = "查詢賬戶列表")
    public String findAll(Model model) {
        
        // 模擬service,提供假數據...
        List<Account> list = new ArrayList<>();
        list.add(new Account(1, "jack", 200d));
        list.add(new Account(2, "lucy", 100d));
        list.add(new Account(3, "lufei", 200d));
        list.add(new Account(4, "james", 3000d));
        model.addAttribute("list", list);

        return "/list.jsp"; // 使用默認視圖解析器
    }
}

訪問測試:在index.jsp配置:

然後進行tomcat部署即可測試成功

 

(5)Spring整合(web容器)

思想:

springMVC和spring本身就是同一家公司,不需要編寫任何整合代碼,可以做到無縫對接....

雖然不需要寫任何整合代碼,但是web.xml 只加載了(DispatcherServlet)前端控制器,掃描了 spring-mvc.xml配置文件,並沒有去加載 applicationContext.xml配置文件,所以web層無法依賴注入service層代碼...

我們現在需要在web項目啓動時,加載spring環境,那麼springMVC就可以從spring容器獲得service對象了...

我們這裏需要藉助一個監聽器:ServletContextListener,就可以在web工程啓動時,加載spring的環境 applicationContext.xml,初始化spring容器,至此我們的web層就可以注入service層代碼了...

spring框架就提供了這個一個監聽器,專門加載applicationContext.xml,配置文件... 這裏需要導入一個座標spring-web,springMVC的座標其實已經包含了它

在web.xml中配置監聽器:

	<!--配置監聽器,加載Spring環境-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

修改AccountController

@Controller
@RequestMapping(value = "/account", name = "賬戶模塊")
public class AccountController {

    // 依賴AccountService
    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "/findAll", name = "查詢賬戶列表")
    public String findAll(Model model) {
        List<Account> list = accountService.findAll();
        model.addAttribute("list", list);

        return "/list.jsp"; // 使用默認視圖解析器
    }
}

自此,三大框架整合成功了

 

(6)賬戶新增:

add.jsp修改

web層


    @RequestMapping(value = "/save",name = "添加賬戶")
    public String save(Account account){
        accountService.save(account);
        return "redirect:/account/findAll.do";
    }

service層

dao層:

測試完成即可

 

(7)聲明式事務

方式一:註解方式

applicationContext.xml文件

AccountService實現

(2)xml方式:


    <!--配置事務管理器-->
    <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="*"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="serviceOperation" expression="execution(* com.wsl.service..*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"></aop:advisor>
    </aop:config>

 

(8)賬戶修改:

list.jsp

web層:

service層:

dao層“

    Account findById(Integer id);

    <select id="findById" resultType="com.wsl.domain.Account">
        select * from account where id=#{id}
    </select>

update.jsp

修改數據:

update.jsp

web層

service層

dao層

    void update(Account account);

一般sql執行方案:
update account set name=#{name},money=#{money} where id=#{id}

動態sql執行方案:

    <update id="update">
        update account
        <set>
            <if test="name !=null">
                name=#{name},
            </if>
            <if test="money !=null">
                money=#{money},
            </if>
        </set>
        where id=#{id}
    </update>

執行完畢即可成功

 

(9)刪除賬戶:

list.jsp

AccountController

    @RequestMapping(value = "/delete",name = "賬戶刪除")
    public String delete(Integer id){
        accountService.delete(id);
        return "redirect:/account/findAll.do";
    }

service

    @Override
    public void delete(Integer id) {
        accountDao.delete(id);
    }

dao層

  void delete(Integer id);


    <delete id="delete">
        delete  from account where id=#{id}
    </delete>

執行完畢即可

(10)批量刪除:

全選與反選:

運行流程:

web層:

service層

dao層:

測試完成成功。

 

二.用戶登錄權限控制:

在企業開發中,有的頁面需要進行權限控制。

思想:

(1)用戶登錄

準備user表與數據:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;


insert  into `user`(`id`,`username`,`password`) values (1,'jack','123'),(2,'tom','123');

User實體:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    
    private Integer id;
    
    private String username;
    
    private String password;
}

login.jsp

web層

@Controller
@RequestMapping(value = "/user", name = "用戶模塊")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", name = "登錄功能")
    public String login(User user, HttpServletRequest request, HttpSession session) {
        User currentUser = userService.login(user);
        if (currentUser == null) { // 登錄失敗
            request.setAttribute("error", "用戶名或密碼錯誤...");
            return "/login.jsp";
        }

        // 登錄成功,跳轉到查詢列表頁面
        session.setAttribute("currentUser", currentUser);
        return "redirect:/account/findAll.do";
    }
}

service層

dao層

login.jsp:顯示錯誤信息

 

(2)權限攔截:

自定義登錄攔截器

/*
    登錄攔截器
 */
public class LoginInterceptor implements HandlerInterceptor {


    // 預處理攔截

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1.從session中獲取登錄user對象
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        // 2.判斷
        if(currentUser == null){
            try {
                // 重定向到登錄頁面
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 未登錄,攔截
            return false;
        }
        // 已登錄放行
        return true;
    }
}

在spring-mvc.xml中配置攔截器規則

    <!--配置登錄攔截器規則-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/account/*"/>
            <bean class="com.wsl.web.interceptor.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

 

三.Spring父子容器;

我們使用的spring框架,通過ContextLoaderListener加載的spring容器(父容器)

我們使用的springMVC框架,通過DispatcherServlet加載springMVC容器(子容器)

 

 

四,總結

ssm配置的總結項:

項目整體架構:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>com.wsl</groupId>  
  <artifactId>springday08_mybatis_spring_springMVC</artifactId>  
  <version>1.0-SNAPSHOT</version>  
  <!--依賴管理-->  
  <packaging>war</packaging>
  <dependencies> 
    <!--mybatis連接相關座標-->  
    <dependency> 
      <groupId>mysql</groupId>  
      <artifactId>mysql-connector-java</artifactId>  
      <version>5.1.47</version> 
    </dependency>  
    <dependency> 
      <groupId>com.alibaba</groupId>  
      <artifactId>druid</artifactId>  
      <version>1.1.15</version> 
    </dependency>  
    <dependency> 
      <groupId>org.mybatis</groupId>  
      <artifactId>mybatis</artifactId>  
      <version>3.5.1</version> 
    </dependency>  
    <dependency> 
      <groupId>org.projectlombok</groupId>  
      <artifactId>lombok</artifactId>  
      <version>1.18.10</version> 
    </dependency>  
    <dependency> 
      <groupId>junit</groupId>  
      <artifactId>junit</artifactId>  
      <version>4.12</version> 
    </dependency>  
    <!--spring相關座標-->  
    <dependency> 
      <groupId>org.springframework</groupId>  
      <artifactId>spring-context</artifactId>  
      <version>5.1.5.RELEASE</version> 
    </dependency>  
    <dependency> 
      <groupId>org.aspectj</groupId>  
      <artifactId>aspectjweaver</artifactId>  
      <version>1.9.5</version> 
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency> 
      <groupId>org.springframework</groupId>  
      <artifactId>spring-jdbc</artifactId>  
      <version>5.1.5.RELEASE</version> 
    </dependency>  
    <dependency> 
      <groupId>org.springframework</groupId>  
      <artifactId>spring-test</artifactId>  
      <version>5.1.5.RELEASE</version> 
    </dependency>  
    <!--spring整合mybatis座標-->  
    <dependency> 
      <groupId>org.mybatis</groupId>  
      <artifactId>mybatis-spring</artifactId>  
      <version>1.3.2</version> 
    </dependency>  
    <!--springMVC座標-->  
    <dependency> 
      <groupId>org.springframework</groupId>  
      <artifactId>spring-webmvc</artifactId>  
      <version>5.1.5.RELEASE</version> 
    </dependency>  
    <dependency> 
      <groupId>javax.servlet</groupId>  
      <artifactId>servlet-api</artifactId>  
      <version>2.5</version>  
      <scope>provided</scope> 
    </dependency>  
    <dependency> 
      <groupId>javax.servlet</groupId>  
      <artifactId>jsp-api</artifactId>  
      <version>2.0</version>  
      <scope>provided</scope> 
    </dependency>  
    <dependency> 
      <groupId>jstl</groupId>  
      <artifactId>jstl</artifactId>  
      <version>1.2</version> 
    </dependency> 
  </dependencies>  
  <!--指定maven編譯版本-->  
  <build> 
    <plugins> 
      <plugin> 
        <groupId>org.apache.maven.plugins</groupId>  
        <artifactId>maven-compiler-plugin</artifactId>  
        <version>3.1</version>  
        <configuration> 
          <source>1.8</source>  
          <target>1.8</target>  
          <encoding>UTF-8</encoding> 
        </configuration> 
      </plugin> 
    </plugins> 
  </build> 
</project>

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_2_5.xsd"
	version="2.5">

	<!--前端控制器  加載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-mvc.xml</param-value>
	</init-param>
	<load-on-startup>4</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>springmvc</servlet-name>
	<url-pattern>*.do</url-pattern>
</servlet-mapping>

	<!--配置監聽器,加載Spring環境-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!--post請求中中文過濾器-->
	<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>

SqlMapConfig.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>

    <!--&lt;!&ndash;加載properties屬性文件&ndash;&gt;-->
    <!--<properties resource="jdbc.properties"></properties>-->
    <!--&lt;!&ndash;設置java類型別名&ndash;&gt;-->
    <!--<typeAliases>-->
        <!--<package name="com.wsl.domain"></package>-->
    <!--</typeAliases>-->
    <!--&lt;!&ndash;環境配置&ndash;&gt;-->
    <!--<environments default="mysql">-->
        <!--<environment id="mysql">-->
            <!--<transactionManager type="JDBC"></transactionManager>-->
            <!--<dataSource type="POOLED">-->
                <!--<property name="driver" 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>-->
            <!--</dataSource>-->
        <!--</environment>-->
    <!--</environments>-->
    <!--<mappers>-->
        <!--<package name="com.wsl.dao"></package>-->
    <!--</mappers>-->
</configuration>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=root

spring-mvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">

    <!--開啓註解組件掃描-->
    <context:component-scan base-package="com.wsl.web"></context:component-scan>
    <!--開啓mvc註解支持-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--配置登錄攔截器規則-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/account/*"/>
            <bean class="com.wsl.web.interceptor.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
       	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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--開啓註解組件掃描-->
    <context:component-scan base-package="com.wsl.service"></context:component-scan>

    <!--加載第三方配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!--配置連接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <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>

    <!--配置SqlSessionFactoryBean-->
    <bean id="sessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--指定連接池-->
        <property name="dataSource" ref="dataSource"></property>
        <!--指定實體類型名稱-->
        <property name="typeAliasesPackage" value="com.wsl.domain"></property>
        <!-- 加載mybatis的核心配置文件,如果mybatis核心配置空了,這一步可以省略....-->
        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
    </bean>

    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wsl.dao"></property>
    </bean>

    <!--&lt;!&ndash;配置事務管理器&ndash;&gt;-->
    <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="*"/>-->
        <!--</tx:attributes>-->
    <!--</tx:advice>-->
    <!--<aop:config>-->
        <!--<aop:pointcut id="serviceOperation" expression="execution(* com.wsl.service..*.*(..))"></aop:pointcut>-->
        <!--<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"></aop:advisor>-->
    <!--</aop:config>-->
    <!--開啓tx註解支持-->
    <tx:annotation-driven></tx:annotation-driven>
</beans>

AccountController

@Controller
@RequestMapping(value = "/account",name = "賬戶模塊")
public class AccountController {

    @Autowired
    AccountService accountService;

    @RequestMapping(value = "/findAll",name = "查詢賬戶列表")
    public String findAll(Model model){
//        List<Account> list = new ArrayList<>();
//        list.add(new Account(1,"javak",2000d));
//        list.add(new Account(2,"abc",2600d));
//        list.add(new Account(3,"ecd",600d));
//        list.add(new Account(4,"edd",1200d));
//        list.add(new Account(5,"tom",4300d));
//        list.add(new Account(6,"c++",3200d));
//        model.addAttribute("list",list);
        List<Account> list = accountService.findAll();
        model.addAttribute("list",list);
        return "/list.jsp";
    }


    @RequestMapping(value = "/save",name = "添加賬戶")
    public String save(Account account){
        accountService.save(account);
        return "redirect:/account/findAll.do";
    }

    @RequestMapping(value = "/findById",name = "查詢賬戶")
    public String findById(Integer id, Model model){
        Account account = accountService.findById(id);
        model.addAttribute("account",account);
        return "/update.jsp";
    }
    @RequestMapping(value = "/update",name = "更新賬戶")
    public String update(Account account){
        accountService.update(account);
        return "redirect:/account/findAll.do";
    }
    @RequestMapping(value = "/delete",name = "賬戶刪除")
    public String delete(Integer id){
        accountService.delete(id);
        return "redirect:/account/findAll.do";
    }

    @RequestMapping(value = "/deleteBath",name = "批量刪除")
    public String deleteBath(Integer[] ids){
        accountService.deleteBath(ids);
        return "redirect:/account/findAll.do";
    }

}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章