zoukankan      html  css  js  c++  java
  • SSH(Struts、Spring、Hibernate)三大框架整合

    1. 新建数据库ssh_db -> 新建表user_tbid为主键,自动递增)

      

      2. 导入jar包(strutshibernate spring

       

    3. 注册页面reg.jsp,将表单的 action 属性设置为 handleActioninput 元素的 name 属性值加上前缀“user.”,如user.username

    <%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding= "UTF-8"%> 
    <!DOCTYPE  html  PUBLIC  "-//W3C//DTD  HTML  4.01  Transitional//EN"  "http://www.w3.org 
    /TR/html4/loose.dtd"> 
    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>账号注册</title> 
    </head> 
    <body> 
         <form action="handleAction" method="post">&nbsp;&nbsp;&nbsp;&nbsp;号:<input name="user.username"/><br/> <br/>
              密&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="user.password"/><br/> <br/>
          <input type="submit" value="注册"/> <input type="submit" value="登录">
         </form> 
    </body> 
    </html> 

    4.数据处理及输出页面handledata.jsp,当Action中返回的user对象为空时,页面输出“注册失败”,不为空时输出注册信息

     

    <%@page import="java.sql.*"%> 
    <%@page import="indi.wt.ssh.pojo.*"%> 
    <%@page language="java" contentType="text/html; charset=UTF-8" 
            pageEncoding="UTF-8" import="java.sql.*"%> 
    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>数据处理</title> 
    </head> 
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <body> 
        <%
             User user = (User) request.getAttribute("user");
             if (user != null) {
                 out.print("<p>恭喜你,注册成功!以下是你的注册信息:</>");
                 out.print("<p>账号:" + user.getUsername() + "</>");
                 out.print("<p>密码:" + user.getPassword() + "</>"); 
             } else {
                 out.print("<p>注册失败!</>");
             }
         %> 
    </body> 
    </html> 

    5.实体层:根据数据库表结构生成 User 类,并生成对应字段的 set get 方法(id为主键,生成策略为自动增长,usernamepassword为属性)-> hibernate注解如下

       

    package indi.wt.ssh.pojo;
    
    import javax.persistence.*;
    import org.hibernate.annotations.Where;
    
    @Entity
    @Table(name="user_tb")
    @Where(clause = "")
    public class User {
        @Column(name="username")
        private String username;
        @Column(name="password")
        private String password; 
        @Id  
        @GeneratedValue(strategy = GenerationType.IDENTITY) //主键生成策略
        private int id; 
        
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
    }

    6. 数据访问层,加入insertUsergetUser方法

     

    package indi.wt.ssh.dao;
    
    import indi.wt.ssh.pojo.User;
    
    import org.hibernate.*; 
    import org.hibernate.cfg.*; 
    
    public class UserDao {
        public int insertUser(User user) {
            //System.out.println("insertUser");
            Configuration config = new Configuration().configure();
            SessionFactory sf = config.buildSessionFactory();
            Session session = sf.openSession();
            Transaction tx = session.beginTransaction();
            session.save(user);
            tx.commit();
            session.close();
            sf.close();
            return user.getId();
        }
    
        public User getUser(int id) {
    
            User user = null;
            Configuration config = new Configuration().configure();
            SessionFactory sf = config.buildSessionFactory();
            Session session = sf.openSession();
            Transaction tx = session.beginTransaction();
    
            Object obj = session.createQuery("from User u where u.id=" + id).uniqueResult();
            tx.commit();
            user = (User) obj;
    
            session.close();
            sf.close();
            return user;
        }
    }

     

    7. Action层:注入UserUserDao对象 -> 生成相应地getset方法 -> 重写execute方法

     

    package indi.wt.ssh.action;
    
    
    
    import org.apache.struts2.ServletActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    
    import indi.wt.ssh.dao.UserDao;
    import indi.wt.ssh.pojo.User;
    
    public class HandleDataAction extends ActionSupport {
        
        User user = null;
        UserDao userDao = null;
    
    
        public UserDao getUserDao() {
            return userDao;
        }
    
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
    
        public User getUser() {
            return user;
        }
    
        public void setUser(User user) {
            this.user = user;
        }
    
        public String execute() {
            if(userDao == null) System.out.println("userdao = null");
            int id = userDao.insertUser(user);
            System.out.println("id = "+id);
            if (id > 0) {
                ServletActionContext.getRequest().setAttribute("user",user);
                return SUCCESS;
            } else {
                return "error";
            }
            
        }
    
    }

     

    8. 配置web.xml,加入Spring监听器和Struts过滤器

     

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
      <display-name>SSHIntegrationPrj</display-name>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      <filter> 
        <filter-name>Struts2</filter-name> 
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</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>
    </web-app>

     

     

    9. 配置struts文件struts.xml,放在src目录下

     

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    
    <struts>
    
        <constant name="struts.enable.DynamicMethodInvocation" value="false" />
        <constant name="struts.devMode" value="true" />
    
        <package name="default" namespace="/" extends="struts-default">
    
            <default-action-ref name="index" />
    
            <global-results>
                <result name="error">/WEB-INF/jsp/error.jsp</result>
            </global-results>
    
            <global-exception-mappings>
                <exception-mapping exception="java.lang.Exception" result="error"/>
            </global-exception-mappings>
            
            <action name="RegAction" > 
                <result>/reg.jsp</result> 
            </action>
            
            <action name="handleAction" class="indi.wt.ssh.action.HandleDataAction"> 
                <result name="success">/handledata.jsp</result>        
            </action> 
            
        </package>
    
    
    </struts>

     

     

    10. 配置hibernate文件hibernate.cfg.xml,放在src目录下

     

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory>
            <!-- 数据库JDBC驱动类名 -->
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.url">jdbc:mysql://127.0.0.1:3306/ssh_db</property>
            <property name="connection.username">wt</property>
            <property name="connection.password">123456</property>
            
            <!-- 数据库方言 -->
            <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
            <!-- ddl语句自动建表 -->
            <property name="hbm2ddl.auto">none</property>
    <!--输出sql语句 -->
            <property name="show_sql">true</property>
            <property name="format_sql">true</property>
            <!-- 连接池配置 -->
            <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
            <property name="hibernate.c3p0.max_size">20</property>
            <property name="hibernate.c3p0.min_size">5</property>
            <property name="hibernate.c3p0.timeout">120</property>
            <property name="automaticTestTable">Test</property>
            <property name="hibernate.c3p0.max_statements">100</property>
            <property name="hibernate.c3p0.idle_test_period">120</property>
            <property name="hibernate.c3p0.acquire_increment">1</property>
            <property name="c3p0.testConnectionOnCheckout">true</property>
            <property name="c3p0.idleConnectionTestPeriod">18000</property>
            <property name="c3p0.maxIdleTime">25000</property>
            <property name="c3p0.idle_test_period">120</property>
    
            <!-- 注册ORM映射文件 -->
            <mapping class="indi.wt.ssh.pojo.User"/>
        </session-factory>
    </hibernate-configuration>

     

    11. 配置spring文件applicationContext.xml,放在web-inf目录下 (因UserDaoHandleDataAction之间存在依赖关系,故将到 dao 对象的配置放在前面。特别要注意的是,系统默认采用的自动装配策略是 byName 方式,所以此处 dao id 值必须和 action 中的属性名一致,action id 值要和 Struts.xml 文件中配置的 action 名一致)

     

    <?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:util="http://www.springframework.org/schema/util"
     xmlns:p="http://www.springframework.org/schema/p"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-4.0.xsd">
     <!-- 配置一个 bean -->
    <bean id="userDao" class="indi.wt.ssh.dao.UserDao"></bean>
    <bean id="handleAction" class="indi.wt.ssh.action.HandleDataAction"></bean>
    </beans>

     

  • 相关阅读:
    jQuery return false
    js获取拼音
    jQuery.getScript加载同域JS
    清除浮动,clearfix的bug
    chrome本地文件加载跨域请求
    中间容器宽度自适应的三栏布局
    mac安装nginx
    弹出一次“设为主页”和“加入收藏”代码
    未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序
    IIS7/IIS7.5下轻松配置PHP利器(微软PHP Manager for IIS 7)
  • 原文地址:https://www.cnblogs.com/unknownname/p/10742641.html
Copyright © 2011-2022 走看看