SpringMVC笔记——SSM框架搭建简单实例

简介

Spring+SpringMVC+MyBatis框架(SSM)是相比紧俏的中小型集团级档次开支的框架,对于新手来说也是比较容易学习入门的。虽说容易,但在框架搭建过程中依然遭逢了好多问题,因而用实例记录下来吧。

MyBatis 1


实例

第一步——导包

Spring框架包及其倚重包
MyBatis框架包及其依赖包
MyBatis-EhCache架包
C3P0架包
MySql数据库驱动包

品种架包如下:
MyBatis 2

类别协会如下:
MyBatis 3

第二步——整合Dao层(Spring+MyBatis)

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>
    <settings>
        <setting name="cacheEnabled" value="true"/>
    </settings>
</configuration>

因为MyBatis交给Spring管理,由此Mapper在Spring中安排,这里的部署只开辟二级缓存

applicationContext-dao.xml

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db_pwc" />
        <property name="user" value="pwc" />
        <property name="password" value="123456" />
        <property name="maxPoolSize" value="20" />
        <property name="minPoolSize" value="1" />
        <property name="initialPoolSize" value="3" />
        <property name="maxIdleTime" value="15" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:sqlMapConfig.xml" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.pwc.dao.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />

    </bean>

</beans>

1.该配置活动扫描单例化采取代理格局的Mapper,单例化的Mapper的bean名为Mapper接口首个字母为小写的名。
2.千万要留心sqlSessionFactory的bean中的configLocation属性,其value值务必记得加上classpath:前缀,不然无法加载MyBatis配置文件

第二步——整合Service层(Spring)

MyBatis,工作接口和作业实现

UserService.java

package cn.pwc.service;
import java.util.List;
import cn.pwc.pojo.User;

public interface UserService {
    public void add(User user) throws Exception;
    public void delete(User user) throws Exception;
    public User getUserById(int id) throws Exception;
    public List<User> listUserByAge(int age) throws Exception;
}

UserServiceBean.java

package cn.pwc.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.pwc.dao.mapper.UserMapper;
import cn.pwc.pojo.User;
import cn.pwc.service.UserService;


@Service @Transactional
public class UserServiceBean implements UserService{

    @Resource(name="userMapper")
    private UserMapper mapper;

    @Override
    public void add(User user) throws Exception {
        mapper.insert(user);
    }

    @Override
    public void delete(User user) throws Exception {
        mapper.deleteById(user.getId());
    }

    @Override
    public User getUserById(int id) throws Exception {
        User user=null;
        user=mapper.findById(id);
        if(user==null){
            throw new Exception("User is not existed!");
        }
        return user;
    }

    @Override
    public List<User> listUserByAge(int age) throws Exception {
        List<User> list=null;
        list=mapper.findByAge(age);
        if(list==null){
            throw new Exception("List is empty!");
        }
        return list;
    }
}

本实例接纳电动扫描加载的艺术,因而该事情bean需注明@瑟维斯(Service)
本实例交由Spring管理作业,因而该业务bean需声明@Transactional

applicationContext-service.xml

    <context:component-scan base-package="cn.pwc.service" />

其三步——添加事务管理

applicationContext-transaction.xml

    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />

    </bean>

    <tx:annotation-driven transaction-manager="txManager" />

第四步——整合视图层(SpringMVC)

springmvc.xml

    <context:component-scan base-package="cn.pwc.controller"/>

    <mvc:annotation-driven />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

运用mvc:annotation-driven标签自动装载视图控制器处理器解析器等

视图Controller(HelloController.java)

package cn.pwc.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.pwc.pojo.User;
import cn.pwc.service.UserService;

@Controller
public class HelloController {

    @Resource(name="userServiceBean")
    private UserService service;

    @RequestMapping("/hello")
    public ModelAndView sayHello(){
        User user=null;
        User user2=null;
        User user3=null;
        try {
            user = service.getUserById(1);
            user2=service.getUserById(1);
            user3=service.getUserById(1);
            System.out.println("OK!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ModelAndView view=new ModelAndView("hello");
        view.addObject("user", user);
        return view;
    }
}

该Controller类需讲明@Controller
视图控制措施需声明@RequestMapping,作为url请求处理办法

第五步——将有着配置装载到Spring容器中

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">
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-*.xml</param-value>
    </context-param>

    <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:springmvc.xml</param-value>
        </init-param>

    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

总得注意servlet-mapping中url-pattern属性值无法为/*
加载的布局文件路径必须有classpath:前缀


测试

MyBatis 4

版权阐明:本文为博主原创作品,未经博主允许不得转载。

 

网站地图xml地图