SpringMVC_Mybatis 使用mysql数据库

使用springmvc注解的形式 整合mybatis 使用mysql数据库 实现一个注册和登录的小例子

一,所需要的jar包

二,web.xml的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    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_2_5.xsd">
    <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet

    </servlet-class>
    <!-- 可以修改spring-servlet的路径  默认在web-inf下面 使用默认的时候可以不写-->

    <!-- <init-param>
            <param-name>contextConfigLocation</param-name>         
            <param-value>/WEB-INF/spring-servlet.xml</param-value>  默认
    </init-param> -->

   <load-on-startup>1</load-on-startup>
   </servlet>
   <!-- 拦截.action的请求 -->
   <servlet-mapping>
      <servlet-name>spring</servlet-name>
      <url-pattern>*.do</url-pattern>
   </servlet-mapping>
  <!-- spring的配置 -->
  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
 <!-- 指定加载spring的配置文件 -->
 <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:applicationContext*.xml</param-value>
  </context-param>
        
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


三,web-inf下面spring-servlet.xml的配置

<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: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.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">    

    <!-- 启动spring mvc的注解 -->
    <context:annotation-config/>
    
    <!-- 设置使用注解的类所在的jar包 -->
    <context:component-scan base-package="com.demo"/>   
 
    <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"p:prefix="/" p:suffix=".jsp" />
    
</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:aop="http://www.springframework.org/schema/aop" 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.0.xsd
         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">


     <!-- 加载jdbc的配置文件 -->
     <context:property-placeholder location="classpath:jdbc-mysql.properties" />
 
     <!-- com.demo包下面的类标记spring注解的类自动转化Bean 同时完成Bean的注入 -->
     <context:component-scan base-package="com.demo" />

     <!-- 配置数据源DataSource -->
     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="driverClass">
            <value>${jdbc.driverClassName}</value>
        </property>
        <property name="jdbcUrl">
            <value>${jdbc.url}</value>
        </property>
        <property name="user">
            <value>${jdbc.username}</value>
        </property>
        <property name="password">
            <value>${jdbc.password}</value>
        </property>
        <property name="maxPoolSize">
            <value>${jdbc.maxPoolSize}</value>
        </property>
        <property name="minPoolSize">
            <value>${jdbc.minPoolSize}</value>
        </property>
        <property name="initialPoolSize">
            <value>${jdbc.initialPoolSize}</value>
        </property>
        <property name="idleConnectionTestPeriod">
            <value>${jdbc.idleConnectionTestPeriod}
            </value>
        </property>
        <property name="maxIdleTime">
            <value>${jdbc.maxIdleTime}</value>
        </property>
     </bean>
     
    <!-- 配置mybitasSqlSessionFactoryBean -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <property name="configLocation" value="classpath:mybatis.xml"></property>  
    </bean>
    
    <!-- 配置SqlSessionTemplate -->  
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">  
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />  
    </bean>
 
      
    <!-- 事务配置 -->  
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  

      
    <!-- 使用annotation注解方式配置事务 -->  
    <tx:annotation-driven transaction-manager="transactionManager"/>  

    
</beans>


五,mybatis.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.demo.pojo.Shop" alias="shop"/>  
     </typeAliases>
    
    <!-- 映射配置文件 -->
     <mappers>
        <mapper resource="com/demo/persistence/ShopMapper.xml"/>
     </mappers>
</configuration>


六 ,连接数据源的jdbc-mysql.properties配置

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=123456
jdbc.maxPoolSize=15
jdbc.minPoolSize=1
jdbc.initialPoolSize=1
jdbc.idleConnectionTestPeriod=1800
jdbc.maxIdleTime=3600


七,实体类

package com.demo.pojo;

import java.io.Serializable;

@SuppressWarnings("serial")
public class Shop implements Serializable {

    private int id;//编号
    private String name;//姓名
    private String pwd;//密码
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public Shop() {
        super();
    }
    public Shop(String name, String pwd) {
        super();
        this.name = name;
        this.pwd = pwd;
    }
   
}


八,定义的Shop接口类

public interface IShopMapper {
    //添加   

    public void insert(Shop shop);
    //根据id查询   

    public Shop getByid(int id);
}


九,IShopMapper.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.demo.persistence.IShopMapper">
     <!-- 使实体类的属于跟表中的字段想对应 -->    

     <resultMap type="shop" id="shopResultMap">
       <id  column="id" property="id" javaType="int"/>
       <result column="name" property="name" javaType="String"/>
       <result column="pwd" property="pwd" javaType="String"/>
     </resultMap>
     
    <!-- 注册 -->
     <insert id="insert" parameterType="shop">
        insert into shop(id,name,pwd) values(#{id},#{name},#{pwd})
     </insert> 

    <!-- 根据id查询parameterType是指参数类型resultMap是指返回类型-->
     <select id="getempid" resultMap="shopResultMap" parameterType="int">
       select * from shop where id=#{id}
     </select>

     
</mapper>


十,shopDao类的代码

import com.demo.pojo.Shop;

@Repository("shopDao")
public class ShopDao {
    
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    //注册
    //这里的insert是配置文件对应的id
    public void insert(Shop shop){
        sqlSessionTemplate.insert("insert", shop);   
    }
    //根据id查询 返回Shop对象
    public Shop getById(int id){
       return (Shop) sqlSessionTemplate.selectOne("getempid", id);    
    }
 }


十一,ShopServlet类的代码
@Service("shopServlet")
public class ShopServlet {

    @Autowired
    private ShopDao shopDao;
    //注册
    public void AddShop(Shop shop){    
        shopDao.insert(shop);
    }
    //登录
    public Shop getById(int id){    
        return  shopDao.getById(id);
    }
}


十二,action类的代码

@Controller
@RequestMapping("/Shop.do")
public class Add_Shop {
    @Autowired
    private ShopServlet shopServlet;

    //注册的方法

    @RequestMapping(params="method=add")
    public String add(String name,String pwd){
        Shop shop=new Shop(name, pwd);
          shopServlet.AddShop(shop);
          return "scce";
        
    }

    //根据id查询的方法

    @RequestMapping(params="method=all")
    public String All(int id){
         Shop shop=shopServlet.getById(id);
         HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
         request.setAttribute("shop", shop);
         return "select";
    }

}


十三,一个注册的index.jsp页面

<body>
    <center>
     <form action="/SpringMVC_Mybatis/Shop.do?method=add" method="post">
                用户名:<input type="text" name="name"><br>
                密&nbsp;码:<input type="text" name="pwd"><br/>
      <input type="submit" value="注册">
     </form>
    </center>
  </body>


十四,登录成功之后跳到scce.jsp页面  根据id查询的页面

  <body>
    <center>
       <form action="/SpringMVC_Mybatis/shop.do?method=all" method="post">
            编号:<input type="text" name="id" id="id"> <input type="submit" value="查询">
       </form>
    </center>
  </body>


十五,查询之后跳到查询结果的页面select.jsp

  <body>
    <center>
      编号:${shop.name}
      密码:${shop.pwd}

    </center>
  </body>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值