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>

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