zoukankan      html  css  js  c++  java
  • SSH2 增删查改实例

    (一)引入包 (共73个,不一定都需要,但是我的项目是这么多,经过调试,没有包冲突)

    (二)创建数据库表

            建立数据库octtest,并创建user表,表里面一共4个字段:id,姓,名,年龄。

            语句如下:

             create database octtest;

             user octtest;

             DROP TABLE IF EXISTS `users`;
             CREATE TABLE `users` (
              `id` int(10) unsigned NOT NULL,
              `firstname` varchar(50) NOT NULL,
               `lastname` varchar(50) NOT NULL,
               `age` int(10) unsigned NOT NULL,
                PRIMARY KEY (`id`)
              ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

     

    ()myeclipse 中自带的hibernate reverse engineering 工具,根据刚才创建的user表, 自动生成实体User 和相应的User.hbm.xml配置文件。

       1)在myeclipse中的<DB Browser>视图中创建连接数据库连接,如下图:

       

          填入mysql数据库相应的路径,用户名,密码等信息。注意:这里要引入mysql-connector-javajar包,需要从外部导入。

     

    2)连接数据库正常后,选择octtest数据库中的user表,右键-hibernate reverse engineering。自动生成实体User 和相应的User.hbm.xml配置文件。(正常情况下可以生成,但是笔者生成engineer有问题,所以只能够手动创建User类和相应的User.hbm.xml,,所以如果读者顺利创建,可跳过2a,2b两部)

           2a)创建User实体类

    User.java






     package com.bean;


     public class User {
     public Integer id;


     public String firstname;
     public String lastname;
     public int age;
     public Integer getId() {
      return id;
     }
     public void setId(Integer id) {
      this.id = id;
     }
     public String getFirstname() {
      return firstname;
     }
     public void setFirstname(String firstname) {
      this.firstname = firstname;
     }
     public String getLastname() {
      return lastname;
     }
     public void setLastname(String lastname) {
      this.lastname = lastname;
     }
     public int getAge() {
      return age;
     }
     public void setAge(int age) {
      this.age = age;
     }
    }

        2b)创建User实体类对应的映射文件,这个映射文件作用是告诉hibernate要把这个User对象和数据库中的user表联系起来。

    User.hbm.xml:






    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">style="COLOR: #383838">http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


    <hibernate-mapping>
     <class name="com.bean.User" table="users">
      <id name="id" type="java.lang.Integer" column="id">
       <generator class="increment"/>
      </id>
      <property name="firstname" type="string" column="firstname"/>
      <property name="lastname" type="string" column="lastname"/>
      <property name="age" type="java.lang.Integer" column="age"/>
     </class>
    </hibernate-mapping>

     

     

    (三)编写底层dao操作:对User实体操作,主要还是 增删查改4个。养成好习惯,无论是dao操作还是业务逻辑,最好都先用接口写好要用到的方法,再用实现类去实现。

    dao接口:






    package com.dao;


    import java.util.List;


    import com.bean.User;


    public interface UserDAO {
     public void saveUser(User user);
     
     public void removeUser(User user);
     
     public User findUserById(Integer id);
     
     public List<User> findAllUser();
     
     public void updateUser(User user);
    }

     

    dao实现:






    package com.dao.impl;


    import java.util.List;


    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


    import com.bean.User;
    import com.dao.UserDAO;


    public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {
     
     @SuppressWarnings("unchecked")
     public List<User> findAllUser() {
      String hql = "from User user order by user.id desc";
      return (List<User>) this.getHibernateTemplate().find(hql);
     }


     public User findUserById(Integer id) {
      User user = (User)this.getHibernateTemplate().get(User.class,id);
      return user;
     }


     public void removeUser(User user) {
      this.getHibernateTemplate().delete(user);
     }


     public void saveUser(User user) {
      this.getHibernateTemplate().save(user);
     }


     public void updateUser(User user) {
      this.getHibernateTemplate().update(user);
     }


    }

     

     (四)编写struts.xml applicationContext.xml web.xml配置文件。其中,web.xml文件是可以一次写完。struts.xmlapplicationContext.xml 需要注意保存路径。

    web.xml:(保存路径是:×××项目名/WebRoot/WEB-INF






    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5"
     xmlns="http://java.sun.com/xml/ns/javaee"> style="COLOR: #383838">http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">style="COLOR: #383838">http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee">style="COLOR: #383838">http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">style="COLOR: #383838">http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     
     <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
       org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
     </filter> 


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


     <listener>
      <listener-class>
       org.springframework.web.context.ContextLoaderListener
      </listener-class>
     </listener>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

     ————————————————————————————————————————

    applicationContext.xml (保存路径是:×××项目名/WebRoot/WEB-INF,这个是默认路径






    <?xml version="1.0" encoding="UTF-8"?>
    <beans
     xmlns="http://www.springframework.org/schema/beans">style="COLOR: #383838">http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">style="COLOR: #383838">http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.springframework.org/schema/beans">style="COLOR: #383838">http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">style="COLOR: #383838">http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">


    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
     <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
     <property name="url" value="jdbc:mysql://localhost:3306/octtest"></property>
     <property name="username" value="root"></property>
     <property name="password" value="mysql"></property>
     <property name="maxActive" value="100"></property>
     <property name="maxIdle"  value="30"></property>
     <property name="maxWait" value="500"></property>
    </bean>


    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
     <property name="dataSource" ref="dataSource"></property>
     <property name="hibernateProperties">
      <props>
       <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
       <prop key="hibernate.show_sql">true</prop>
      </props>
     </property>
     <property name="mappingResources">
      <list>
       <value>com/bean/User.hbm.xml</value>
        <!--
       <value>com/gzjs/updatewapi/entity/As_Active_CertBean.hbm.xml</value>
       <value>com/gzjs/updatewapi/entity/Cert_DataBean.hbm.xml</value>
       <value>com/gzjs/updatewapi/entity/Revoke_CertBean.hbm.xml</value>
       
       <value>com/gzjs/updatewapi/entity/User.hbm.xml</value>
       -->
      </list>
     </property>
    </bean>


    <bean id="userDao" class="com.dao.impl.UserDAOImpl" scope="singleton">
     <property name="sessionFactory">
      <ref bean="sessionFactory"/>
     </property>
    </bean>


    <bean id="userService" class="com.service.impl.UserServiceImpl">
     <property name="userDao">
      <ref bean="userDao"/>
     </property>
    </bean>


    <bean id="saveUserAction" class="com.action.SaveUserAction" scope="prototype">
     <property name="userService">
      <ref bean="userService"/>
     </property>
    </bean>


    <bean id="listUserAction" class="com.action.ListUserAction" scope="prototype">
     <property name="userService">
      <ref bean="userService"/>
     </property>
    </bean>



    <bean id="showUserRecordAction" class="com.action.ShowUserRecordAction" scope="prototype">
     <property name="userService">
      <ref bean="userService"/>
     </property>
    </bean>
    <bean id="updateUserAction" class="com.action.UpdateUserAction" scope="prototype">
     <property name="userService">
      <ref bean="userService"/>
     </property>
    </bean>


    <bean id="deleteUserAction" class="com.action.DeleteUserAction" scope="prototype">
     <property name="userService">
      <ref bean="userService"/>
     </property>
    </bean>
    </beans>

     

     ————————————————————————————————————————

    struts.xml (保存路径是:×××项目名/WebRoot/WEB-INF/classes






    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd"> style="COLOR: #383838">http://struts.apache.org/dtds/struts-2.0.dtd">


    <struts>
     <package name="user" extends="struts-default">
      <action name="saveUser" class="saveUserAction">
       <resultname="success" type="redirect">/listUser.action</result>
       <result name="input">/save.jsp</result>
      </action>
      
      <action name="listUser" class="listUserAction">
       <result name="success">/listUser.jsp</result>
      </action>
      
      <action name="showUserRecord" class="showUserRecordAction">
       <result name="success">/showRecord.jsp</result>
      </action>
      
      <action name="updateUser" class="updateUserAction">
       <result name="success" type="redirect">/listUser.action</result>
       <result name="input">/showRecord.jsp</result>
      </action>


      <action name="deleteUser" class="deleteUserAction">
       <result name="success" type="redirect">/listUser.action</result>
      </action>
     </package>
    </struts>

     

    (五)编写action类,有两种方法,一种是crud每种操作一个action,另一种是crud集成到一个UserAction中。本文采用第一种。

    SaveUserAction:






    package com.action;


    import com.bean.User;
    import com.opensymphony.xwork2.ActionSupport;
    import com.service.UserService;


    public class SaveUserAction extends ActionSupport {
     


     private User user;
     
     private UserService userService;
     
     public User getUser() {
      return user;
     }
     public void setUser(User user) {
      this.user = user;
     }
     @Override
     public String execute() throws Exception {
      this.userService.save(this.user);
      return SUCCESS;
     }
     public UserService getUserService() {
      return userService;
     }
     public void setUserService(UserService userService) {
      this.userService = userService;
     }
    }

     

    ListUserAction:






    package com.action;


    import java.util.List;


    import com.bean.User;
    import com.opensymphony.xwork2.ActionSupport;
    import com.service.UserService;


    public class ListUserAction extends ActionSupport {
     


     private List<User> list;
     
     private UserService userService;
     
     @Override
     public String execute() throws Exception {
      list = userService.findAllUser();
      return SUCCESS;
     }
     public UserService getUserService() {
      return userService;
     }
     public void setUserService(UserService userService) {
      this.userService = userService;
     }
     public List<User> getList() {
      return list;
     }
     public void setList(List<User> list) {
      this.list = list;
     }
    }

      

    DeleteUserAction:






    package com.action;


    import com.bean.User;
    import com.opensymphony.xwork2.ActionSupport;
    import com.service.UserService;


    public class DeleteUserAction extends ActionSupport {
     


     private User user;
     
     private UserService userService;
     
     public User getUser() {
      return user;
     }
     public void setUser(User user) {
      this.user = user;
     }
     @Override
     public String execute() throws Exception {
      this.userService.delete(this.user);
      return SUCCESS;
     }
     public UserService getUserService() {
      return userService;
     }
     public void setUserService(UserService userService) {
      this.userService = userService;
     }
    }

     

    ShowUserRecordAction :






    package com.action;


    import com.bean.User;
    import com.opensymphony.xwork2.ActionSupport;
    import com.service.UserService;


    public class ShowUserRecordAction extends ActionSupport {
     


     private User user;
     
     private UserService userService;
     
     public User getUser() {
      return user;
     }
     public void setUser(User user) {
      this.user = user;
     }
     @Override
     public String execute() throws Exception {
      user = this.userService.findById(user.getId());
      return SUCCESS;
     }
     public UserService getUserService() {
      return userService;
     }
     public void setUserService(UserService userService) {
      this.userService = userService;
     }
     
     
    }

     

    UpdateUserAction :






    package com.action;


    import com.bean.User;
    import com.opensymphony.xwork2.ActionSupport;
    import com.service.UserService;


    public class UpdateUserAction extends ActionSupport {
     


     private User user;
     
     private UserService userService;
     
     public User getUser() {
      return user;
     }
     public void setUser(User user) {
      this.user = user;
     }
     @Override
     public String execute() throws Exception {
      this.userService.update(user);
      return SUCCESS;
     }
     public UserService getUserService() {
      return userService;
     }
     public void setUserService(UserService userService) {
      this.userService = userService;
     }
    }

     

     

    () 编写业务逻辑

    service接口:






    package com.service;


    import java.util.List;


    import com.bean.User;


    public interface UserService {
     public List<User> findAllUser();
     
     public void save(User user);
     
     public void delete(User user);
     
     public void update(User user);
     
     public User findById(Integer id);
    }

     

     

    service实现:






    package com.service.impl;


    import java.util.List;


    import com.bean.User;
    import com.dao.UserDAO;
    import com.service.UserService;


    public class UserServiceImpl implements UserService {
     
     public UserDAO userDao;
     
     public UserDAO getUserDao() {
      return userDao;
     }


     public void setUserDao(UserDAO userDao) {
      this.userDao = userDao;
     }


     
     public void delete(User user) {
      this.userDao.removeUser(user);
     }


     public List<User> findAllUser() {
      return this.userDao.findAllUser();
     }


     public User findById(Integer id) {
      return this.userDao.findUserById(id);
     }


     public void save(User user) {
      this.userDao.saveUser(user);
     }


     public void update(User user) {
      this.userDao.updateUser(user);
     }


    }

     

    (八)页面:只是基本的展示功能,没有css美化。

    index.jsp






     <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>


    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>  
        <title>operation</title>
      </head>
     
      <body>
       <h1><font color="red">Operation List</font></h1>
      
       <s:a href="http://zy-oct.blog.163.com/blog/save.jsp">SaveUser</s:a><br><br><br>
       <s:a href="http://zy-oct.blog.163.com/blog/listUser.action">List Users</s:a>
      </body>
    </html>

     

    listUser.jsp






    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%">style="COLOR: #383838">http://java.sun.com/jsp/jstl/core"%>


    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>  
        <title>operation</title>
      </head>
      <script type="text/javascript">
       function del(){
        if(confirm("
    你真的想删除该记录吗")){
         return true;
        }
        return false;
       }
      </script>
      <body>
       <h1><font color="red">List User</font></h1>
       <hr>
     <table border="1" align="center" width="70%">
      <tr>
       <td>
    序号
       </td>
       
       <td>

       </td>
       
       <td>

       </td>
       
       <td>
    年龄
       </td>
       
       <td>
    操作
       </td>
      </tr>
      
      <c:forEach items="${list}" var="x">
       <tr>
        <td>${x.id}
        </td>
       
        <td>${x.firstname}
        </td>
        
        <td>${x.lastname }
        </td>
        
        <td>${x.age }
        </td>
        
        <td>
          <a href='http://zy-oct.blog.163.com/blog/./showUserRecord.action?user.id=${x.id}'>
    修改</a>
          <a href='http://zy-oct.blog.163.com/blog/./deleteUser.action?user.id=${x.id}' onclick="return del()">
    删除</a>
        </td>
       </tr>
      </c:forEach>
     </table>
     <a href="http://zy-oct.blog.163.com/blog/index.jsp" >
    首页</a>
     <a href="http://zy-oct.blog.163.com/blog/save.jsp" >
    添加</a>
      </body>
    </html>

     

     

    save.jsp






    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>


    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>  
        <title>operation</title>
      </head>
     
      <body>
       <h1><font color="red">Save User</font></h1>
       <hr>
       <s:form action="saveUser.action">
        <s:textfield name="user.firstname" label="
    "/>
        <s:textfield name="user.lastname" label="
    "/>
        <s:textfield name="user.age" label="
    年龄"/>
        <s:submit></s:submit>
        </s:form>
      </body>
    </html>

     

    showRecord.jsp






     <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>


    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>  
        <title>operation</title>
      </head>
     
      <body>
       <h1><font color="red">Show User Preview Records</font></h1>
       <hr>
       <s:form action="updateUser.action">
        <s:textfield name="user.firstname" label="
    " />
        <s:textfield name="user.lastname" label="
    " />
        <s:textfield name="user.age" label="
    年龄" />
        <s:set name="u_id" value="user.id"/>
      <s:hidden value="%{u_id}" name="user.id"/>
        <s:submit></s:submit>
        </s:form>
      </body>
    </html>



    魔由心生,有万境纵横,无一道清静,无量寿佛!
  • 相关阅读:
    JavaScript Window
    3.1.3 背景音乐播放技术
    6.1 多媒体相关基本概念及计算问题
    11.5 知识产权考点讲解
    第15课 TortoiseGit程序操作介绍
    第16课 “远程 Git文档库” 的基础操作
    第11课 Git GUI程序的基本功能
    第12课 使用Git GUI
    第13课 SmartGit程序操作介绍
    第14课 SourceTree程序操作介绍
  • 原文地址:https://www.cnblogs.com/qihuan/p/3778369.html
Copyright © 2011-2022 走看看