spring-sprinMVC-mybatis集成(普通javaWeb项目)

本文介绍了如何在JavaWeb项目中整合Spring、SpringMVC和Mybatis。从创建项目开始,逐步讲解了导入所需jar包、配置spring核心文件(包括数据源、SqlSessionFactory、领域模型、DAO、Service、事务)、设置SpringMVC配置文件(扫描包、静态资源、注解支持、视图解析器)、web.xml配置(启动Spring和SpringMVC容器,解决POST乱码问题),最后展示了项目的目录结构和部分关键文件如index.jsp。
摘要由CSDN通过智能技术生成

1、思路

  1. 使用idea新建普通的javaWeb项目

  2. 导入jar包

  3. 配置spring的核心配置文件
       引入jdbc.properties
       配置dataSource
       配置SqlSessionFactory
       domain、dao(mapper)
       service
       事物tx

  4. controller

  5. springMvc核心配置文件
       扫描包
       静态资源放行
       开启注解支持
       配置视图解析器

  6. web.xml配置
       启动spring容器
       启动springMvc容器
       解决post提交乱码问题

  7. jsp完成

项目结构
在这里插入图片描述

2、使用idea新建普通的javaWeb项目

在这里插入图片描述

3、 导入jar包

在这里插入图片描述

3、配置spring的核心配置文件

3.1、applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/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
    ">
    <!--引入数据库-->
    <context:property-placeholder location="classpath:jdbc.properties"/>


    <!-- 扫描service层-->
    <context:component-scan base-package="com.xuxusheng.ssm.service"/>

    <!--配置数据库连接对象-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
    </bean>
    <!--创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--加载所有的mapper-->
        <property name="mapperLocations" value="classpath:com/xuxusheng/ssm/mapper/*.xml"/>
        <!--定义公共的基础的包-->
        <property name="typeAliasesPackage">
            <value>
                com.xuxusheng.ssm.query
                com.xuxusheng.ssm.domain
            </value>
        </property>
    </bean>
    <!--dao即mapper配置 两种方式-->
    <!--方式1:如果有很多个mapper,需要每个都配置。比较麻烦,使用另一种方式-->
   <!-- <bean id="employeeMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="mapperInterface" value="com.xuxusheng.ssm.mapper.EmployeeMapper"/>
    </bean>-->
    <!--方式2-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--只要扫描到该包下所有的接口,我都使用代理模式进行实现-->
        <property name="basePackage" value="com.xuxusheng.ssm.mapper"/>
    </bean>
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 开启事务注解的支持-->
    <tx:annotation-driven/>
</beans>

3.2、jdbc.properties

jdbc.username=root
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm?createDatabaseIfNotExist=true
jdbc.password=123456

3.3、log4j.properties

###全局 配置根
##log4j常见的日志等级: trace<debug<info<warn<error
log4j.rootLogger = ERROR,console 
##输出局部的日志信息    打印的日志等级要大于或者等于trace等级
log4j.logger.com.xuxusheng=trace
##打印的日志规则    日志信息打印在控制台里面
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=%d %p [%c] - %m%n

3.4、domain

public class Employee {
    private Long id;
    private String name;
    private Integer age;
    //set get toString
}

3.5、dao(mapper)

public interface EmployeeMapper {
    void save(Employee employee);

    List<Employee> selectAll();
}

3.5、service

IEmployeeService

public interface IEmployeeService {
    void save(Employee employee);

    void update(Employee employee);

    void delete(Long id);

    Employee selectById(Long id);

    List<Employee> selectAll();
}

EmployeeServiceImpl

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    @Transactional
    public void save(Employee employee) {
        employeeMapper.save(employee);
        System.out.println(1/0);
    }

    @Override
    @Transactional
    public void update(Employee employee) {

    }

    @Override
    @Transactional
    public void delete(Long id) {

    }

    @Override
    public Employee selectById(Long id) {
        return null;
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }
}

4、controller

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/index")
    public String index(Model model) {
        model.addAttribute("employees", employeeService.selectAll());
        return "employee/index";
    }
}

5、applicationContext-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    ">
<!-- 扫描service层-->
    <context:component-scan base-package="com.xuxusheng.ssm.web.controller"/>

    <mvc:annotation-driven/>

    <mvc:default-servlet-handler/>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="suffix" value=".jsp"/>
        <property name="prefix" value="/WEB-INF/views/"/>
    </bean>
</beans>

6、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!--在指定的位置加装applicationContext.xml文件-->
    <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>
    <servlet>
        <!--启动springMvc容器-->
        <servlet-name>springMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-mvc.xml</param-value>
        </init-param>
        <!--初始化就加载-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <!--解决post提交乱码问题-->
        <filter-name>CharacterEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

7、employee/index.jsp

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值