8.struts2应用demo(struts2笔记)

说明:这是一个论坛后台管理的一个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使用方法的理解。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,806评论 18 399
  • 概述 什么是Struts2的框架Struts2是Struts1的下一代产品,是在 struts1和WebWork的...
    inke阅读 2,283评论 0 50
  • 一. Java基础部分.................................................
    wy_sure阅读 3,854评论 0 11
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,170评论 19 139
  • 近年来,多部大热影视剧作品由网文作品改编而来,包括《寻龙诀》、《花千骨》、《琅琊榜》等。作为IP主要来源地之一,布...
    泛娱乐浪潮下的泥石流阅读 1,991评论 0 0