SpringMVC+Spring+MyBatis+MySql环境搭建

本文介绍如何在Spring MVC框架下集成MyBatis ORM工具,实现前后端分离的Java Web应用。涵盖web.xml配置、Spring MVC配置、数据库连接设置、MyBatis配置等关键步骤。
摘要由CSDN通过智能技术生成

1、配置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"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
  <!-- 加载spring容器 -->
  <listener>
      <display-name>Spring</display-name>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
 
  <!-- 配置spring -->
  <context-param>
      <description>Spring</description>
    <param-name>contextConfigLocation</param-name>

    <!-- 根据自己文件路径配置 -->
    <param-value>classpath:spring/applicationContext.xml</param-value>
  </context-param>
 
  <!-- 配置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:springmvc/springmvc.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>
      <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>
  </filter>
     
  <filter-mapping>
      <filter-name>characterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
 
</web-app>

 

2、配置springmvc.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:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
   
    <!-- 配置Spring MVC注解驱动 -->
    <mvc:annotation-driven/>
   
    <!-- 自动扫描Controller和Service -->

    <!-- 根据自己类文件包名称配置 -->
    <context:component-scan base-package="com.weibo.controller,com.weibo.service" />
   
    <!-- 配置静态资源,用以加载html,css,js,图片文件 -->
    <mvc:default-servlet-handler />
   
    <!-- 配置一个springmvc框架的视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 通过setter方法注入前缀 -->
        <property name="prefix" value="/html/" />
        <!-- 通过setter方法注入后缀 -->
        <property name="suffix" value=".html" />
    </bean>
   
    <!-- 支持文件上传
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>
     -->
</beans>

 

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:mvc="http://www.springframework.org/schema/mvc" 
    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-3.2.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> 
           
    <!-- 分解配置 jdbc.properites -->
    <context:property-placeholder location="classpath:jdbc/jdbc.properties" />
   
    <!-- 数据源c3p0 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClassName}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxPoolSize" value="${c3p0.pool.size.max}" />
        <property name="minPoolSize" value="${c3p0.pool.size.min}" />
        <property name="initialPoolSize" value="${c3p0.pool.size.ini}" />
        <property name="acquireIncrement" value="${c3p0.pool.size.increment}" />
    </bean>
   
    <!-- sessionFactory 将spring和mybatis整合 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
        <property name="mapperLocations" value="classpath:mapper/*.xml" />    <!-- 加载mapper文件 -->
    </bean>
   
    <!-- mapper接口不能直接被注入到Spring当中,因此在此处进行扫描注入 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
        <property name="basePackage" value="com.weibo.mapper"></property> 
    </bean>
   
    <!-- 事务 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="select*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="find" read-only="true" />
            <tx:method name="get" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
   
   
    <!-- 面向切面编程 -->
    <aop:config>
        <aop:pointcut expression="execution(* service.*.*(..))" id="pointCut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut" />
    </aop:config>
   
</beans>     

 

4、配置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>
    <!-- 定义别名 -->
    <typeAliases>
        <typeAlias type="com.weibo.model.User" alias="User"/>
    </typeAliases>
    <!-- 这里不需要再注册mybatis的SQL映射文件 ,因为在Spring的配置文件中配置sqlSessionFactory时注册了mapper的路径-->
</configuration>    

 

5、定义数据库连接文件jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123
c3p0.pool.size.max=20
c3p0.pool.size.min=5
c3p0.pool.size.ini=3
c3p0.pool.size.increment=2

 

6、定义mapper文件User.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.weibo.mapper.UserMapper">
    <select id="login" parameterType="User" resultType="User">
        select id from t_user where username = #{username} and password = #{password}
    </select>

</mapper>

 

7、测试

 

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

    @Autowired
    private UserService userService ;
   
    /**
     * 用户登录接口
     * @param user
     * @return
     */
    @RequestMapping(value="login",method=RequestMethod.POST)
    @ResponseBody
    public Json login(User user){
        Json json = new Json() ;
       
        try{
            User userResult = userService.login(user) ;
           
            if(userResult!=null){
                json.setBool(true) ;
                json.setMsg("登陆成功") ;
            }else{
                json.setBool(false) ;
                json.setMsg("用户名或密码错误") ;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
       
        return json ;
    }
}

@Service
public class UserService {
   
    @Autowired
    private UserMapper userDao ;
   
    public User login(User user)throws Exception{
        return userDao.login(user) ;
    }
}

public interface UserMapper{
   
    public User login(User user)throws Exception ;
}

public class User {
    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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值