Spring+Struts2+MyBatis(mybatis有代理)整合增删改查

1.创建如下项目结构
Spring+Struts2+MyBatis(mybatis有代理)整合增删改查_第1张图片
2.在项目的WebRoot下的WEB-INF下的lib下添加自己的架包
3.在src下的com.bean包下创建UserInfo.java

package com.bean;

  public class UserInfo {
      private Integer id;
      private String name;
      private String password;
     private String telephone;
      private String isadmin;

     public UserInfo() {

     }
     public UserInfo(Integer id, String name, String password, String telephone,
             String isadmin) {
         this.id = id;
         this.name = name;
         this.password = password;
         this.telephone = telephone;
         this.isadmin = isadmin;
     }
     public Integer getId() {
         return id;
     }
     public void setId(Integer id) {
         this.id = id;
     }
     public String getName() {
         return name;
     }
     public void setName(String name) {
         this.name = name;
     }
     public String getPassword() {
         return password;
     }
     public void setPassword(String password) {
         this.password = password;
     }
     public String getTelephone() {
         return telephone;
     }
     public void setTelephone(String telephone) {
         this.telephone = telephone;
     }
     public String getIsadmin() {
         return isadmin;
     }
     public void setIsadmin(String isadmin) {
         this.isadmin = isadmin;
     }
     @Override
     public String toString() {
         return "UserInfo [id=" + id + ", isadmin=" + isadmin + ", name=" + name
                 + ", password=" + password + ", telephone=" + telephone + "]";
     } 
 }

4.在src下的com.dao包下创建UserInfoDao.java

package com.dao;

  import java.util.List;

  import com.bean.UserInfo;
  /**
   * mybatis映射文件的dao接口
   * @author pc
   *
  */
 public interface UserInfoDao {
     public List findAll();
  //查所有
 public UserInfo findUser(UserInfo    user);
     //条件查询
public void insertUser(UserInfo user);
 //插入对象
 public void updateUser(UserInfo user);
  //修改对象
  public void deleteUser(int id); 
  //条件删除
 }

5.在src下的com.dao包下创建UserInfoDao.xml


  
  <mapper namespace="com.dao.UserInfoDao">
    <select id="findAll" resultType="user">
      select * from userinfo
    select>
    <select id="findUser" resultType="user" parameterType="user">
       select * from userinfo where name=#{name} and password=#{password}
    select>
   <insert id="insertUser" parameterType="user">
     insert into userinfo values(seq_userinfo.nextval,#{name},#{password},#{telephone},#{isadmin})
   insert>
   <update id="updateUser" parameterType="user">
     update userinfo set name=#{name},password=#{password},telephone=#{telephone},isadmin=#{isadmin} where id=#{id}
   update>

   <delete id="deleteUser" parameterType="int">
     delete from userinfo where id=#{id}
   delete>
 mapper>

6.在src下创建mybatis-config.xml


  
  <configuration>
    
    <typeAliases>
      <typeAlias type="com.bean.UserInfo" alias="user"/>
    typeAliases>

    
   <mappers>
     <mapper resource="com/dao/UserInfoDao.xml"/>
   mappers>
 configuration>

7.在src下的com.dao.impl包下创建UserInfoDaoImpl.java

package com.dao.impl;

   import java.util.List;

   import org.mybatis.spring.SqlSessionTemplate;

   import com.bean.UserInfo;
   import com.dao.UserInfoDao;
   /**
   * 数据dao接口实现类
   * @author pc
   *
   */
  public class UserInfoDaoImpl implements UserInfoDao {
      private SqlSessionTemplate sqlSession;
      /**
       * 根据id删除
       */
      public void deleteUser(int id) {
          //获取代理对象
        UserInfoDao dao=sqlSession.getMapper(UserInfoDao.class);
          try {
              dao.deleteUser(id); //调用代理对象映射的dao接口删除
              sqlSession.commit(); //提交事务
             System.out.println("删除成功");
          } catch (Exception e) {
              System.out.println("删除失败");
              e.printStackTrace();
          }
      }
      /**
       * 查询所有
       */
      public List findAll() {
       //获取代理对象
         UserInfoDao dao=sqlSession.getMapper(UserInfoDao.class);
          List list=null;
          try {
               list=dao.findAll();
              System.out.println("查询所有成功");
          } catch (Exception e) {
              System.out.println("查询所有失败");
              e.printStackTrace();
         }
          return list;
      }

      /**
      * 条件查询
       */
      public UserInfo findUser(UserInfo user) {
          //获取代理对象
          UserInfoDao dao=sqlSession.getMapper(UserInfoDao.class);
          UserInfo userinfo=null;
          try {
              if(user!=null){
                  userinfo=dao.findUser(user);
                  System.out.println("条件查询成功");
              }else{
                  System.out.println("条件查询参数为空");
              }
          } catch (Exception e) {
              System.out.println("条件查询失败");
             e.printStackTrace();
          }
          return userinfo;
      }
  /**
   *添加
   */
      public void insertUser(UserInfo user) {
          //获取代理对象
          UserInfoDao dao=sqlSession.getMapper(UserInfoDao.class);
          try {
              if(user!=null){
                 dao.insertUser(user); 
                  sqlSession.commit(); //提交事务
                  System.out.println("添加成功");
             }else{
                 System.out.println("添加参数为空");
              }
          } catch (Exception e) {
              System.out.println("添加失败");
             e.printStackTrace();
         }

     }
    /**
     * 修改对象
     */
      public void updateUser(UserInfo user) {
         //获取代理对象
          UserInfoDao dao=sqlSession.getMapper(UserInfoDao.class);
        try {
             if(user!=null){
                 dao.updateUser(user); 
                sqlSession.commit(); //提交事务
                  System.out.println("修改成功");
            }else{
                 System.out.println("修改参数为空");
             }
         } catch (Exception e) {
             System.out.println("修改失败");
             e.printStackTrace();
         }
     }
 public SqlSessionTemplate getSqlSession() {
    return sqlSession;
 }
 public void setSqlSession(SqlSessionTemplate sqlSession) {
    this.sqlSession = sqlSession;
}
 }

8.在src下的com.service包下创建UserInfoService.java

package com.service;

import java.util.List;

import com.bean.UserInfo;
/**
 * 服务接口
 * @author pc
 *
 */
public interface UserInfoService {
    public List findAll();  //查所有
    public UserInfo findUser(UserInfo user);//条件查询
    public void insertUser(UserInfo user); //插入对象
    public void updateUser(UserInfo user); //修改对象
    public void deleteUser(int id); //条件删除


}

UserInfoService.java

9.在src下的com.service.impl包下创建UserInfoServiceImpl.java

package com.service.impl;

import java.util.List;

import com.bean.UserInfo;
import com.dao.UserInfoDao;
import com.dao.impl.UserInfoDaoImpl;
import com.service.UserInfoService;

public class UserInfoServiceImpl implements UserInfoService{
    //引入数据层接口
    UserInfoDao dao=new UserInfoDaoImpl();
    /**
     * 删除
     */
    public void deleteUser(int id) {
         dao.deleteUser(id);
    }
    /**
     * 查所有
     */
    public List findAll() {
        return dao.findAll();
    }
  /**
   * 条件查询
   */
    public UserInfo findUser(UserInfo user) {
        return dao.findUser(user);
    }
   /**
    * 插入对象
    */
    public void insertUser(UserInfo user) {
        dao.insertUser(user);
    }
    /**
     * 修改对象
     */
    public void updateUser(UserInfo user) {
        dao.updateUser(user);
    }


    public UserInfoDao getDao() {
        return dao;
    }
    public void setDao(UserInfoDao dao) {
        this.dao = dao;
    }

}

UserInfoServiceImpl.java

10、在src下的com.action包下创建UserInfoAction.java

package com.action;

import com.bean.UserInfo;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.service.UserInfoService;
import com.service.impl.UserInfoServiceImpl;
/**
 *
 * @author pc
 * ActionSupport可以最数据校验
 */
public class UserInfoAction extends ActionSupport  {

    /**
     * 引用服务层对象
     */
    private UserInfoService service=new UserInfoServiceImpl();
    /**
     * 对象用于接收请求中的值
     * 必须创建setter和getter方法,代理对象才能获取或设置
     */
    private UserInfo user;
    /**
     * 登录
     * @return
     */
    public String login(){

        if(user!=null){
            System.out.println("登录表单值接收到");
            UserInfo userinfo=service.findUser(user);
            if(userinfo!=null){
                System.out.println("登录陈宫");
                return SUCCESS;

            }else{
                return ERROR;
            }


        }else{
            System.out.println("登录表单值没有接收到");
            return ERROR;

        }
    }

    /**
     * 注册
     * @return
     */
    public String register(){
        if(user!=null){
            System.out.println("注册表单值接收到");
            service.insertUser(user);
            System.out.println("action注册成功");
            return SUCCESS;

        }else{
            System.out.println("注册表单值没有接收到");
            return ERROR;

        }
    }

    public UserInfoService getService() {
        return service;
    }

    public void setService(UserInfoService service) {
        this.service = service;
    }

    public UserInfo getUser() {
        return user;
    }

    public void setUser(UserInfo user) {
        this.user = user;
    }



}

UserInfoAction.java

11、在src下创建applicationContext.xml


<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.xsd ">
  
  <bean id="oracleDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
    <property name="username" value="scott"/>
    <property name="password" value="tiger"/>
  bean>

  
  
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="oracleDataSource"/>
    bean>

  
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     
     <property name="dataSource" ref="oracleDataSource"/>

     
     <property name="configLocation">
       <value>classpath:mybatis-config.xmlvalue>
     property>
  bean>



  
  <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
     <constructor-arg ref="sqlSessionFactory"/>
  bean>

  
  <bean id="userdao" class="com.dao.impl.UserInfoDaoImpl">
    <property name="sqlSession" ref="sqlSessionTemplate"/>
  bean>

  
  <bean id="servicedao" class="com.service.impl.UserInfoServiceImpl">
    <property name="dao" ref="userdao"/>
  bean>

  
  <bean id="userAction" class="com.action.UserInfoAction">
    <property name="service" ref="servicedao"/>
  bean>
beans>

applicationContext.xml

12、在src下创建struts.xml



<struts>
  
  <constant name="struts.i18n.encoding" value="UTF-8"/>


    <package name="default" namespace="/" extends="struts-default">


       
        
        <action name="*" class="userAction" method="{1}">
          <result name="input">{1}.jspresult>
          <result name="success">success.jspresult>
          <result name="error">error.jspresult>      
       action>


    package>
struts>

struts.xml

13、编辑WebRoot下的WEB-INF下的web.xml


<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <context-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:applicationContext.xmlparam-value>
    context-param>
     <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    <filter>
        <filter-name>struts2filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
    filter>

    <filter-mapping>
        <filter-name>struts2filter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    <welcome-file-list>
        <welcome-file>login.jspwelcome-file>
    welcome-file-list>

web-app>

web.xml

14、在WebRoot下创建register.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting pagetitle>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    
  head>

  <body>
    <center>
      <fieldset style="width:400px;">
        <legend>注册legend>
        <form action="registerUser.action" method="post">
            <table>
              <tr>
                  <td>用户名:td>
                  <td><input type="text" name="user.name"/>td>
              tr>
              <tr>
                   <td>密码:td>
                   <td><input type="password" name="user.password"/>td>
               tr>
              <tr>
                   <td>电话号码:td>
                   <td><input type="text" name="user.telephone"/>td>
               tr>
              <tr>
                   <td>是否是管理员:td>
                   <td>
                   <input type="radio" name="user.isadmin" value="是">
                   <input type="radio" name="user.isadmin" value="否" checked="checked"/>
                   td>
               tr>
              <tr>
                   <td><input type="submit" value="提交"/>td>
                   <td><input type="reset" value="重置"/>td>
               tr>
            table>

        form>
      fieldset>
    center>
  body>
html>

register.jsp

15、在WebRoot下创建login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting pagetitle>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    
  head>

  <body>
    <center>
      <fieldset style="width:400px;">
        <legend>登录legend>
        <form action="login.action" method="post">
            <table>
              <tr>
                  <td>用户名:td>
                  <td><input type="text" name="user.name"/>td>
              tr>
              <tr>
                   <td>密码:td>
                   <td><input type="password" name="user.password"/>td>
               tr>
              <tr>
                   <td><input type="submit" value="提交"/>td>
                   <td><input type="reset" value="重置"/>td>
               tr>
            table>

        form>
      fieldset>
    center>
  body>
html>

16、在WebRoot下创建success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting pagetitle>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    
  head>

  <body>
   <h1>操作成功h1>
   <s:if test="user.name eq 'holly'">
      holly你来啦?
   s:if>
   <s:else>
      我不认识你?你是谁?
   s:else>       
  body>
html>

17、在WebRoot下创建error.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting pagetitle>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    
  head>

  <body>
      操作失败!
  body>
html>

error.jsp

18.运行

你可能感兴趣的:(Spring+Struts2+MyBatis(mybatis有代理)整合增删改查)