說明:這是一個論壇后臺管理的一個demo按咒,主要是為了了解struts2的開發(fā)流程。同時這里我們使用了extJS3.0這個框架乞巧,需要在工程中引入相關(guān)的框架文件洋访。webRoot/res
中有favicon.ico、forum.css斑司、read_forum.gif
這個三個文件渗饮。而在webRoot/admin/ext
中有adapter文件夾、resources文件夾宿刮、ext-all.js互站、ext-lang-zh-CN.js
,其中這里的兩個文件夾是直接從extJS3.0中拷貝過來的僵缺。(工程struts2_3000_BBS2009_06
)
一胡桃、建立數(shù)據(jù)庫
create database bbs2009;
use bbs2009;
CREATE TABLE `_category` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`description` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
二、建立相關(guān)的包
-
com.bjsxt.bbs2009.modle
存放實體 -
com.bjsxt.bbs2009.service
存放業(yè)務(wù)類 -
com.bjsxt.bbs2009.action
存放action -
com.bjsxt.bbs2009.util
存放工具類
說明:這里我們建立的包不太符合MVC開發(fā)模式谤饭,這里設(shè)計的較為簡單标捺。
三、開發(fā)
3.1實體
Category.java
package com.bjsxt.bbs2009.modle;
public class Category {
private int id;
private String name ;
private String description;
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
3.2工具類
DB.java
package com.bjsxt.bbs2009.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DB {
public static Connection createConne(){
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3305/bbs2009", "root", "walp1314");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
public static PreparedStatement prepare(Connection conn, String sql) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
public static void close(Connection conn) {
if(conn == null) return ;
try {
conn.close();
conn = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Statement stmt) {
try {
stmt.close();
stmt = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3.3業(yè)務(wù)
CategoryService.java
package com.bjsxt.bbs2009.service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.bjsxt.bbs2009.modle.Category;
import com.bjsxt.bbs2009.util.DB;
public class CategoryService {
public void add(Category c){
Connection connection = DB.createConne();
String sql = "insert into _category values(null, ?, ?)";
PreparedStatement ps = DB.prepare(connection, sql);
try{
ps.setString(1, c.getName());
ps.setString(2, c.getDescription());
ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}
DB.close(ps);
DB.close(connection);
}
public List<Category> list(){
Connection connection = DB.createConne();
String sql = "select * from _category";
PreparedStatement ps = DB.prepare(connection, sql);
List<Category> categories = new ArrayList<Category>();
try{
ResultSet result = ps.executeQuery();
while(result.next()){
Category category = new Category();
category.setId(result.getInt("id"));
category.setName(result.getString("name"));
category.setDescription(result.getString("description"));
categories.add(category);
}
}catch(SQLException e){
e.printStackTrace();
}
DB.close(ps);
DB.close(connection);
return categories;
}
public void delete(Category c){
deleteById(c.getId());
}
public void deleteById(int id){
Connection connection = DB.createConne();
String sql = "delete from _category where id = ?";
PreparedStatement ps = DB.prepare(connection, sql);
try{
ps.setInt(1, id);
ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}
DB.close(ps);
DB.close(connection);
}
public void update(Category c){
Connection connection = DB.createConne();
String sql = "update _category set name = ? , description = ? where id = ?";
PreparedStatement ps = DB.prepare(connection, sql);
try{
ps.setString(1, c.getName());
ps.setString(2, c.getDescription());
ps.setInt(3, c.getId());
ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}
DB.close(ps);
DB.close(connection);
}
public Category loadById(int id){
Connection connection = DB.createConne();
String sql = "select * from _category where id = ?";
PreparedStatement ps = DB.prepare(connection, sql);
Category category = null;
try{
ps.setInt(1, id);
ResultSet result = ps.executeQuery();
if(result.next()){
category = new Category();
category.setId(result.getInt("id"));
category.setName(result.getString("name"));
category.setDescription(result.getString("description"));
}
}catch(SQLException e){
e.printStackTrace();
}
DB.close(ps);
DB.close(connection);
return category;
}
}
說明:這里我們提供了
- 添加方法:
public void add(Category c)
- 查詢所有帖子方法:
public List<Category> list()
- 刪除帖子:
public void delete(Category c)
- 根據(jù)id刪除帖子方法:
public void deleteById(int id)
- 更新:
public void update(Category c)
- 根據(jù)id查找:
public Category loadById(int id)
3.4action
struts.xml
<?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>
<package name="admin" namespace="/admin" extends="struts-default" >
<default-action-ref name="index"/>
<action name="index">
<result>/admin/index.html</result>
</action>
<action name="*_*" class="com.bjsxt.bbs2009.action.{1}Action" method="{2}">
<result>/admin/{1}_{2}.jsp</result>
<result name="input">/admin/{1}_{2}.jsp</result>
</action>
</package>
<package name="front" namespace="/" extends="struts-default" >
<default-action-ref name="Category_list"/><!-- 默認訪問此界面 -->
<action name="Category_list" class="com.bjsxt.bbs2009.action.CategoryAction" method="list">
<result>/index.jsp</result>
</action>
</package>
</struts>
CategoryAction.java
package com.bjsxt.bbs2009.action;
import java.util.List;
import com.bjsxt.bbs2009.modle.Category;
import com.bjsxt.bbs2009.service.CategoryService;
import com.opensymphony.xwork2.ActionSupport;
public class CategoryAction extends ActionSupport{
private List<Category> categories;
//這里我們一般要使用單例揉抵,如果交給spring管理就是單例
private CategoryService service = new CategoryService();
private Category category;//struts2會將其初始化
private int id ;
public String list(){
categories = service.list();
return SUCCESS;
}
public List<Category> getCategories() {
return categories;
}
public String add(){
service.add(category);
return SUCCESS;
}
public String addInput(){
return INPUT;
}
public String update(){
service.update(category);
return SUCCESS;
}
public String updateInput(){
this.category = this.service.loadById(id);
return INPUT;
}
public String delete(){
service.deleteById(id);
return SUCCESS;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public CategoryService getService() {
return service;
}
public void setService(CategoryService service) {
this.service = service;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
說明:這里我們需要的功能就是在主頁面中能顯示出帖子的名字亡容,然后我們可以對其進行管理(添加,刪除冤今,修改)闺兢。需要注意的是我們需要保存Category對象和id,以便于之后的取值戏罢。
主頁面(admin/index.html
)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" />
<title>BBS2009論壇管理平臺</title>
<link rel="stylesheet" type="text/css"
href="ext/resources/css/ext-all.css" />
<!-- GC -->
<!-- LIBS -->
<script type="text/javascript" src="ext/adapter/ext/ext-base.js">
</script>
<!-- ENDLIBS -->
<script type="text/javascript" src="ext/ext-all.js">
</script>
<script type="text/javascript" src="ext/ext-lang-zh_CN.js">
</script>
<style type="text/css">
html,body {
font: normal 12px verdana;
margin: 0;
padding: 0;
border: 0 none;
overflow: hidden;
height: 100%;
}
.empty .x-panel-body {
padding-top: 0;
text-align: center;
font-style: italic;
color: gray;
font-size: 11px;
}
.x-btn button {
font-size: 14px;
}
.x-panel-header {
font-size: 14px;
}
</style>
<script type="text/javascript">
Ext.onReady( function() {
//Ext.Msg.alert('ext','welcome you!');
var addPanel = function(btn, event) {
var n;
n = tabPanel.getComponent(btn.id);
if(n) {
tabPanel.setActiveTab(n);
return;
}
n = tabPanel.add( {
id : btn.id,
title : btn.id,
html : '<iframe width=100% height=100% src=' + btn.id + ' />',
//autoLoad : '',
closable : 'true'
});
tabPanel.setActiveTab(n);
}
var item1 = new Ext.Panel( {
title : 'Category管理',
//html : '<empty panel>',
cls : 'empty',
items : [
new Ext.Button({
id : 'Category_list',
text : 'Category列表',
width : '100%',
listeners : {
click : addPanel
}
}),
new Ext.Button({
id : 'test',
text : 'Test',
width : '100%',
listeners : {
click : addPanel
}
})
]
});
var item2 = new Ext.Panel( {
title : 'Accordion Item 2',
html : '<empty panel>',
cls : 'empty'
});
var item3 = new Ext.Panel( {
title : 'Accordion Item 3',
html : '<empty panel>',
cls : 'empty'
});
var item4 = new Ext.Panel( {
title : 'Accordion Item 4',
html : '<empty panel>',
cls : 'empty'
});
var item5 = new Ext.Panel( {
title : 'Accordion Item 5',
html : '<empty panel>',
cls : 'empty'
});
var accordion = new Ext.Panel( {
region : 'west',
margins : '5 0 5 5',
split : true,
width : 210,
layout : 'accordion',
items : [ item1, item2, item3, item4, item5 ]
});
var tabPanel = new Ext.TabPanel( {
region : 'center',
enableTabScroll : true,
deferredRender : false,
activeTab : 0,
items : [ {
title : 'index',
//html : 'aaaaaa'
autoLoad : 'Category_add.jsp'
} ]
});
var viewport = new Ext.Viewport( {
layout : 'border',
items : [ accordion, tabPanel ]
});
});
</script>
</head>
<body>
<!-- EXAMPLES -->
</body>
</html>
說明:
- 1.在struts中:
<package name="front" namespace="/" extends="struts-default" >
<default-action-ref name="Category_list"/><!-- 默認訪問此界面 -->
<action name="Category_list" class="com.bjsxt.bbs2009.action.CategoryAction" method="list">
<result>/index.jsp</result>
</action>
</package>
這是配置的用戶訪問界面屋谭,當(dāng)我們使用地址:
http://localhost:8080/struts2_3000_BBS2009_06/Category_list
訪問時可以看到相關(guān)的帖子。
- 2.在后臺龟糕,我們使用地址:
http://localhost:8080/struts2_3000_BBS2009_06/admin/index.html
訪問到后臺首頁桐磁。當(dāng)我們點擊首頁中的Category列表
按鈕時就會進行跳轉(zhuǎn),我們可以看到index.html
中:
var item1 = new Ext.Panel( {
title : 'Category管理',
//html : '<empty panel>',
cls : 'empty',
items : [
new Ext.Button({
id : 'Category_list',
text : 'Category列表',
width : '100%',
listeners : {
click : addPanel
}
}),
這里可以看到點擊后就去找Category_list
這個action讲岁。取得相關(guān)的數(shù)據(jù)后返回Category_list.java
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Category_list</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<a href="${pageContext.request.contextPath }/admin/Category_addInput">添加Category</a>
<hr/>
<s:iterator value="categories" var="c">
<s:property value="#c.name"/> |
<s:property value="#c.description"/>|
<a href="${pageContext.request.contextPath }/admin/Category_delete?id=<s:property value="#c.id"/>">刪除Category</a>|
<a href="${pageContext.request.contextPath }/admin/Category_updateInput?id=<s:property value="#c.id"/>">更新Category</a>
<br>
</s:iterator>
<s:debug></s:debug>
</body>
</html>
然后就可以進行相應(yīng)的管理操作衬以。注意在此頁面中我們不僅要顯示相關(guān)的操作,同時還要顯示出相關(guān)的信息校摩,注意取得信息的寫法。
3.4.1添加
點擊添加按鈕衙吩,則調(diào)用action的addInput方法,返回INPUT
,跳轉(zhuǎn)到Category_addInput.jsp
坤塞,
<body>
<form action="admin/Category_add" method="post">
name:<input name="category.name" /><br>
description:<textarea name="category.description"></textarea><br>
<input type="submit" value="add" />
</form>
</body>
輸入相關(guān)的值之后跳轉(zhuǎn)到Category_add.jsp
顯示添加成功消息珠闰,添加成功。
3.4.2刪除
點擊刪除按鈕瘫辩,調(diào)用action的delete方法伐厌,刪除之后返回Category_delete.jsp
顯示刪除成功的消息。
3.4.3修改
點擊修改按鈕裸影,調(diào)用action的updateInput方法挣轨,返回INPUT
,跳轉(zhuǎn)到Category_updateInput.jsp
轩猩,
<body>
<form action="admin/Category_add" method="post">
name:<input name="category.name" /><br>
description:<textarea name="category.description"></textarea><br>
<input type="submit" value="add" />
</form>
</body>
添加之后跳轉(zhuǎn)到Category_update.jsp
頁面顯示修改成功卷扮。
最后:
這個demo并不好看,但是主要是用來說明使用通配符配置action和了解struts2的執(zhí)行流程均践,加深我們對struts2使用方法的理解晤锹。