JavaEE---------SSH使用實例

今天講的是整合SSH框架,用一個圖書信息小系統來實現,快速幫你構建網站後臺css

首先咱們應該把相應的Struts 2,Hibernate,Spring導入到你的工程中去,下面給出我用的庫集合html

http://sdrv.ms/178GAJIjava

把庫添加到Build path中去,mysql

先改web.xml,它是整個web應用的核心,不要說不知道在哪裏,指明使用Struts2 攔截請求,Spring監聽web

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    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_3_0.xsd">
  <display-name></display-name>    
  <welcome-file-list>
    <welcome-file>index.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>
  <!-- 指明spring配置文件在何處 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- 加載spring配置文件applicationContext.xml -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>    
  </web-app>

 

在src目錄下建立applicationContext.xml,在鏈接數據庫的時候不要再建立hibernate.cfg.xml,直接用Spring提供的鏈接方法就好,要否則可能出錯(本人經驗)spring

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="myDataSource" />
        </property>
        <property name="mappingResources">
            <list>
                <value>com/bq/Book.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    
    <bean id="myDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver">
        </property>
        <property name="url"
            value="jdbc:mysql://127.0.0.1:3306/booksale?useUnicode=true&amp;characterEncoding=UTF-8">
        </property>
        <property name="username" value="root"></property>
        <property name="password" value=""></property>
    </bean>
    
    <bean id="userDao" class="com.bq.DAOImplement">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>

    <bean id="service" class="com.bq.BookService">
        <property name="bookDao">
            <ref bean="userDao" />
        </property>
    </bean>

    <bean id="query" class="com.bq.QueryBook">
        <property name="service">
            <ref bean="service" />
        </property>
    </bean>

</beans>

 

建立Struts 2核心配置文件,不要噴我,我喜歡一個個類那樣寫,你也能夠在一個類中指定不一樣的方法來處理不一樣的請求sql

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.i18n.encoding" value="GB2312" />
    <package name="default" namespace="/" extends="struts-default">
    
        <action name="query" class="com.bq.QueryBook">
            <result name="success">/show.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
        
        <action name="getBook" class="com.bq.GetBook">
            <result name="success">/book.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
        
        <action name="changeBook" class="com.bq.ChangeBook">
            <result name="success" type="redirectAction">query</result>
            <result name="input">/book.jsp</result>
        </action>
        
        <action name="delBook" class="com.bq.DelBook">
            <result name="success" type="redirectAction">query</result>
            <result name="input">/show.jsp</result>
        </action>
            
        <action name="addBook" class="com.bq.AddBook">
            <result name="success" type="redirectAction">query</result>
            <result name="input">/show.jsp</result>
        </action>
    </package>
</struts> 
   

總體框架就有了,下來就是各個類了數據庫


 

先看實體類及其Hibernate映射文件apache

Book.javasession

package com.bq;

/**
 * @author 白強
 *
 */
public class Book {
    private int id;
    private String name;
    private String detail;
    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 getDetail() {
        return detail;
    }
    public void setDetail(String detail) {
        this.detail = detail;
    }
    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + ", detail=" + detail
                +  "]";
    }
}

Book.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping 
    package="com.bq">

    <class name="com.bq.Book" table="book">
        <id name="id">
            <generator class="increment"/>
        </id>
        <property name="name"/>
        <property name="detail"/>
    </class>
</hibernate-mapping>

 


 

而後是寫DAO層

接口BookDAO.java

package com.bq;

import java.util.List;

public interface BookDAO  {
    
    List getAll();//得到全部記錄
    
    List getBook(int pageSize, int startRow);//得到全部記錄
    
    List queryBook(String fieldname,String value);//根據條件查詢
    
    Book getBook(int id);//根據ID得到記錄
    
    void addBook(Book book);//添加記錄
    
    void updateBook(Book book);//修改記錄
    
    void deleteBook(Book book);//刪除記錄

}

 

DAO實現類

DAOImplement.java,裏面用到

this.getHibernateTemplate()的方法來自Spring

能夠利用它來完成數據庫操做

package com.bq;

import java.util.List;

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

/**
 * @author 白強
 *
 */
public class DAOImplement extends  HibernateDaoSupport implements BookDAO{
    
    public DAOImplement() {
        
    }

    @Override
    public List getAll() {
        
        String sql="from Book";
        return this.getHibernateTemplate().find(sql);
    }

    @Override
    public List getBook(int pageSize, int startRow) {
        return null;
    }

    @Override
    public List queryBook(String fieldname, String value) {
        System.out.println("value: "+value);
        String sql="FROM Book where "+fieldname+" like '%"+value+"%'";
        return this.getHibernateTemplate().find(sql);
    }

    @Override
    public Book getBook(int id) {
        
        return (Book)this.getHibernateTemplate().get(Book.class,id);
    }

    @Override
    public void addBook(Book book) {
        this.getHibernateTemplate().save(book);        
    }

    @Override
    public void updateBook(Book book) {
        this.getHibernateTemplate().update(book);
        
    }

    @Override
    public void deleteBook(Book book) {
        this.getHibernateTemplate().delete(book);
    }

}

 


 

 

寫Service層

BookService.java

package com.bq;

import java.util.List;

/**
 * @author 白強
 *
 */
public class BookService {
    private BookDAO bookDao;
    
    public BookDAO getBookDao() {
        return bookDao;
    }

    public void setBookDao(BookDAO bookDao) {
        this.bookDao = bookDao;
    }
    /**
     * 函數說明:得到一條的信息 參數說明: ID 返回值:對象
     */
    public Book getBook(int bookId) {
        return bookDao.getBook(bookId);
    }

    /**
     * 函數說明:修改信息 參數說明: 對象 返回值:
     */
    public void updateBook(Book book) {
        bookDao.updateBook(book);
    }

    /**
     * 函數說明:查詢信息 參數說明: 集合 返回值:
     */
    public List queryBook(String fieldname, String value) {
        return bookDao.queryBook(fieldname, value);
    }
    
    public List queryBook() {
        return bookDao.getAll();
    }
    
    public void addBook(Book book) {
        bookDao.addBook(book);
    }
    
    public void delBook(Book book) {
        bookDao.deleteBook(book);
    }
    
}

這個時候咱們的Service就寫好了,而後再在控制Action中調用Service的方法就能夠了

 


 

 

QueryBook.java 查詢獲得List

package com.bq;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author 白強
 *
 */
public class QueryBook extends ActionSupport {
    private Book book;
    private BookService service;
    private List<Book> list;
    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public BookService getService() {
        return service;
    }

    public void setService(BookService service) {
        this.service = service;
    }
    public List<Book> getList() {
        return list;
    }

    public void setList(List<Book> list) {
        this.list = list;
    }

    @Override
    public String execute() throws Exception {
        if(service.queryBook()!=null){
            list=service.queryBook();
            return SUCCESS;
        }
        else{
        return INPUT;
        }
    }
    
}

添加Book

AddBook.java

package com.bq;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author 白強
 *
 */
public class AddBook extends ActionSupport{
    private Book book;
    private BookService service;
    public Book getBook() {
        return book;
    }
    public void setBook(Book book) {
        this.book = book;
    }
    public BookService getService() {
        return service;
    }
    public void setService(BookService service) {
        this.service = service;
    }
    @Override
    public String execute() throws Exception {
        System.out.println(book.toString());        
            service.addBook(book);
            return SUCCESS;
    }
}

 

根據id獲得Book

GetBook.java

package com.bq;

import com.opensymphony.xwork2.ActionSupport;

public class GetBook extends ActionSupport {
    private int id;
    private Book book;
    private BookService service;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Book getBook() {
        return book;
    }
    public void setBook(Book book) {
        this.book = book;
    }
    public BookService getService() {
        return service;
    }
    public void setService(BookService service) {
        this.service = service;
    }
    @Override
    public String execute() throws Exception {
        if(service.getBook(getId())!=null){
            book=service.getBook(getId());
            //service.updateBook(b);
            return SUCCESS;
        }
        else{
        return INPUT;
        }
    }
    
}

 

根據id更新Book

ChangeBook.java

package com.bq;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author 白強
 *
 */
public class ChangeBook extends ActionSupport{
    private Book book;
    private BookService service;
    public Book getBook() {
        return book;
    }
    public void setBook(Book book) {
        this.book = book;
    }
    public BookService getService() {
        return service;
    }
    public void setService(BookService service) {
        this.service = service;
    }
    @Override
    public String execute() throws Exception {
        System.out.println(book.toString());
        if(service.getBook(book.getId())!=null){
            Book b=service.getBook(book.getId());
            service.updateBook(book);
            return SUCCESS;
        }
        else{
        return INPUT;
        }
    }
}

根據id刪除Book

DelBook.java

package com.bq;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author 白強
 *
 */
public class DelBook extends ActionSupport {
    private int id;
    private Book book;
    private BookService service;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Book getBook() {
        return book;
    }
    public void setBook(Book book) {
        this.book = book;
    }
    public BookService getService() {
        return service;
    }
    public void setService(BookService service) {
        this.service = service;
    }
    @Override
    public String execute() throws Exception {
        if(service.getBook(getId())!=null){
            service.delBook(service.getBook(getId()));
            return SUCCESS;
        }
        else{
        return INPUT;
        }
    }
    
}

 

實現數據庫的基本操做 增刪改查 便可

最後附上全部的jsp文件

 

index.jsp

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>歡迎</title>
  </head>
  
  <body>
   <h1 align="center"> 歡迎來到SSH整合測試頁面</h1> <br>
   <div align="center">
     <a href="query">點擊進入</a>&nbsp;&nbsp;<a href="add.jsp">增長書</a>
   </div>
  </body>
 
</html>

 

add.jsp

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    

<META name="viewport" content="width=device-width, initial-scale=1">
<TITLE>添加</TITLE>        

<BODY>
<DIV data-role="header" data-position="inline"> 
<H1>增長書</H1></DIV>
<DIV data-role="content">
<FORM action="addBook" method="POST">
<s:hidden name="book.id" ></s:hidden>
<label>書名:</label>
<input name="book.name" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" />
<br> <label>詳情:</label>
<input name="book.detail" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" />
<BUTTON type="submit" data-theme="b" data-inline="true">保存</BUTTON>
<HR>
</FORM>
</DIV>
<DIV class="footer-docs" data-role="footer" data-theme="c">
<P>&nbsp;2012~2013  白強</P>
</DIV>
</BODY>
</HTML>

 

show.jsp

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>展現頁面</title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />    
  </head>
  
  <body>
   <h1 align="center"> 這裏是展現頁面</h1> <br>
   <div align="center">
   <table id="show" align="center" style="text-align: center">
<tr>
   <td>
          ID
  </td>
<td >
         名稱
</td>
<td>
     描述
</td>
<td>
操做
</td>
</tr>
<s:iterator value="list">
<tr>
   <td>
          ${id}
  </td>
<td >
         ${name}
</td>
<td>
         ${detail}
</td>
<td>
         <s:url id="get" action="getBook">
    <s:param name="id">${id}</s:param>
       </s:url>
       <s:a href="%{get}">修改</s:a>
         <s:url id="del" action="delBook">
    <s:param name="id">${id}</s:param>
       </s:url>
       <s:a href="%{del}">刪除</s:a>
</td>
</tr>
</s:iterator>
</table>
   </div>
  </body>
 
</html>

 

book.jsp

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    

<META name="viewport" content="width=device-width, initial-scale=1">
<TITLE>更改</TITLE>        

<BODY>
<DIV data-role="header" data-position="inline"> 
<H1>更改書</H1></DIV>
<DIV data-role="content">
<FORM action="changeBook" method="POST">
<s:hidden name="book.id" ></s:hidden>
<s:textfield name="book.name" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" theme="simple" label="詳情"></s:textfield>
<br> 
<s:textfield name="book.detail" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" theme="simple" label="詳情"></s:textfield>
<BUTTON type="submit" data-theme="b" data-inline="true">保存</BUTTON>
<HR>
</FORM>
</DIV>
<DIV class="footer-docs" data-role="footer" data-theme="c">
<P>&nbsp;2012~2013  白強</P>
</DIV>
</BODY>
</HTML>

 

還有一個簡單的style

style.css

@charset "UTF-8";
/* CSS Document */

table {
  border: solid 1px #D5D5D5;
  border-collapse: collapse;
    width:100%; 
}

table td {
    border:1px solid #D5D5D5;
    font-size:12px;
    padding:7px 5px;
}

table th {
    background-color:#EEE;
    border-right:1px solid #D5D5D5;
    font-size:13.5px;
    line-height:120%;
    font-weight:bold;
    padding:8px 5px;
    text-align:left;
}
.ui-resizable {
    position:relative;
}
.ui-resizable-handle {
    display:block;
    font-size:0.1px;
    position:absolute;
    z-index:99999;
}

.ui-resizable-s { 
    background:#EEEEEE url(../images/grippie.png) no-repeat scroll center 2px;
    border-top:1px solid #CCCCCC;
    bottom:-5px;
    cursor:s-resize;
    height:14px;
    left:0;width:100%; 
}

最後再附上下載地址

http://sdrv.ms/178Gr9h


就這樣吧,不清楚的還能夠問我。。。

相關文章
相關標籤/搜索