说明:这是一个论坛后台管理的一个demo,主要是为了了解struts2的开发流程。同时这里我们使用了extJS3.0这个框架,需要在工程中引入相关的框架文件。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
)
一、建立数据库
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
二、建立相关的包
-
com.bjsxt.bbs2009.modle
存放实体 -
com.bjsxt.bbs2009.service
存放业务类 -
com.bjsxt.bbs2009.action
存放action -
com.bjsxt.bbs2009.util
存放工具类
说明:这里我们建立的包不太符合MVC开发模式,这里设计的较为简单。
三、开发
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业务
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)
- 根据id删除帖子方法:
public void deleteById(int id)
- 更新:
public void update(Category c)
- 根据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>
这是配置的用户访问界面,当我们使用地址:
http://localhost:8080/struts2_3000_BBS2009_06/Category_list
访问时可以看到相关的帖子。
- 2.在后台,我们使用地址:
http://localhost:8080/struts2_3000_BBS2009_06/admin/index.html
访问到后台首页。当我们点击首页中的Category列表
按钮时就会进行跳转,我们可以看到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。取得相关的数据后返回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>
然后就可以进行相应的管理操作。注意在此页面中我们不仅要显示相关的操作,同时还要显示出相关的信息,注意取得信息的写法。
3.4.1添加
点击添加按钮,则调用action的addInput方法,返回INPUT
,跳转到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>
输入相关的值之后跳转到Category_add.jsp
显示添加成功消息,添加成功。
3.4.2删除
点击删除按钮,调用action的delete方法,删除之后返回Category_delete.jsp
显示删除成功的消息。
3.4.3修改
点击修改按钮,调用action的updateInput方法,返回INPUT
,跳转到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>
添加之后跳转到Category_update.jsp
页面显示修改成功。
最后:
这个demo并不好看,但是主要是用来说明使用通配符配置action和了解struts2的执行流程,加深我们对struts2使用方法的理解。