Spring整合MyBatis案例練習筆記

需求:
css

 用戶登陸html

技術需求:java

  Servlet+Spring+Mybatis+MVC+jsp+css+html+jquerymysql

數據庫設計:jquery

  用戶表web

Sql語句設計:spring

  select * from t_user where uname=#{0} and pwd=#{1}sql

實現:數據庫

  mapper層apache

package com.bjsxt.mapper;

import com.bjsxt.pojo.User;

public interface UserMapper {
    //用戶登陸
    User selUser(String uname,String pwd);
}

  UserMapper.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.bjsxt.mapper.UserMapper">
    <!-- 用戶登陸sql配置 -->
      <select id="selUser" resultType="com.bjsxt.pojo.User">
          select * from t_user where uname=#{arg0} and pwd=#{arg1}
      </select>
  </mapper>

  pojo層

package com.bjsxt.pojo;
/**
 * 用戶實體類
 * @author Yancy
 *
 */
public class User {
    private int uid;//用戶ID
    private String uname;//用戶名稱
    private String pwd;//用戶密碼
    public int getUid() {
        return uid;
    }
    public void setUid(int uid) {
        this.uid = uid;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public User(int uid, String uname, String pwd) {
        super();
        this.uid = uid;
        this.uname = uname;
        this.pwd = pwd;
    }
    @Override
    public String toString() {
        return "User [uid=" + uid + ", uname=" + uname + ", pwd=" + pwd + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((pwd == null) ? 0 : pwd.hashCode());
        result = prime * result + uid;
        result = prime * result + ((uname == null) ? 0 : uname.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (pwd == null) {
            if (other.pwd != null)
                return false;
        } else if (!pwd.equals(other.pwd))
            return false;
        if (uid != other.uid)
            return false;
        if (uname == null) {
            if (other.uname != null)
                return false;
        } else if (!uname.equals(other.uname))
            return false;
        return true;
    }
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    
}

  service層

package com.bjsxt.service;

import com.bjsxt.pojo.User;

public interface UserService {
    //用戶登陸
    User checkUserInfoService(String uname,String pwd);
}

  service.impl層 

package com.bjsxt.service.impl;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bjsxt.mapper.UserMapper;
import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;

public class UserServiceImpl implements UserService {
    private UserMapper um;
    
    public UserMapper getUm() {
        return um;
    }

    public void setUm(UserMapper um) {
        this.um = um;
    }

    //用戶登陸
    @Override
    public User checkUserInfoService(String uname, String pwd) {
        //使用對象完成數據庫操做
        return um.selUser(uname, pwd);
        
    }
    

}

   servlet層

package com.bjsxt.servlet;

import java.io.IOException;

import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;

public class UserServlet extends HttpServlet{
    UserService us;
    @Override
    public void init() throws ServletException {
        //傳統方式
//        //獲取Spring容器對象
//        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//        //獲取業務層對象
//        us = (UserService) ac.getBean("us");
        //優化方式
        ApplicationContext ac=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        us = (UserService) ac.getBean("us");
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //請求編碼格式
        req.setCharacterEncoding("utf-8");
        //設置響應編碼格式
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //獲取請求信息
        String uname=req.getParameter("uname");
        String pwd=req.getParameter("pwd");
        //處理請求信息
            
            //調用方法處理請求
            User u = us.checkUserInfoService(uname, pwd);
        //處理響應結果
            if(u!=null) {
                resp.sendRedirect(req.getContextPath()+"/success.jsp");
            }
    }
}

  配置文件src目錄下

  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" 
      xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
      <!-- 配置數據源 -->
      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="com.mysql.jdbc.Driver" />
          <property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property>
          <property name="username" value="root"></property>
          <property name="password" value="123456"></property>
      </bean>
      <!-- 配置工廠bean -->
      <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref="dataSource"></property>
      </bean>
      <!-- 配置mapper掃描bean -->
      <bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
          <property name="sqlSessionFactory" ref="factory"></property>
          <property name="basePackage" value="com.bjsxt.mapper"></property>
      </bean>
      <!-- 配置業務層bean -->
      <bean id="us" class="com.bjsxt.service.impl.UserServiceImpl">
          <property name="um" ref="userMapper"></property>
      </bean>
      
</beans>

log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.bjsxt=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

   web.xml在WEB-INF下

<?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" version="3.0"> <!-- 配置Spring文件路徑 --> <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 --> <servlet> <servlet-name>user</servlet-name> <servlet-class>com.bjsxt.servlet.UserServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>user</servlet-name> <url-pattern>/user</url-pattern> </servlet-mapping> </web-app>

 

整合問題及其解決方案:

  問題一:

    傳統方式是在service層直接經過mybatis對象完成數據的操做,業務層和mapper層的耦合性很是高.

  解決一:

    使用SpringIOC技術和service層和mapper層進行解耦.

  方案一:

    直接從Spring容器對象中獲取Mapper對象

      --->Spring容器還管理SqlSession對象

        --->Spring容器還管理DataSource對象

  實現一:

    參照配置文件

  問題二:

    若是在Servlet層中直接new建立業務層對象,雖然能夠正常使用,可是會形成Servlet層和業務層的耦合性較高,不易於後期的的迭代升級.

  解決二:

    使用SpringIOC將Servlet層和service層進行解耦.

  實現二:

    將Service對象配置成bean,交由Spring容器管理.在Servlet中經過Spring容器對象獲取業務層對象

   問題三:

    咱們實現的登陸代碼,若是放在高併發環境,咱們發現Spring容器對象一個線程中會被建立兩次,這樣形成佔據的內存過多.

  解決三:

    ①在service層中咱們使用Spring容器對象獲取Mapper接口對象,Mapper接口對象自己就在Spring容器中,可是咱們把Service也配置成bean了,那麼是否是能夠使用依賴注入呢.直接在Spring的配置文件中經過依賴注入將Mapper對象注入給service對象

    ②使用init方法,將獲取us對象的動做放到服務器啓動是完成.

  問題四:

    Spring容器在獲取的代碼的路徑在init方法中耦合性較高.

  解決四:

    將Spring容器相關路徑信息配置到web.xml中

  實現四:

    在web.xml中配置全局參數代表Spring路徑

    配置Spring監聽器

相關文章
相關標籤/搜索