Welcome 微信登录

首页 / 操作系统 / Linux / struts2简单示例

今天写一个struts2的例子,目的是为了让大家明白struts2的基本流程,其实框架没有大家想象的那么难,说白了struts2的本质就是一个大的Servlet,即原本需要提交到Servlet处理的部分现在通过配置文件将其交给普通的Class类进行处理。首先新建一个javaWeb项目,然后把struts2所依赖的包导入到lib下(可以百度一下也可以直接到官网上下载),然后在web.xml中对struts2进行配置,添加的内容如下:<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>在index.jsp中写如下代码:1 <form method="post" action="testAction">2 名称:<input type="text" name="name"/>3 <input type="submit" value="提交"/>4 </form>接下来是写struts的配置文件struts.xml,内容如下:<?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>
    <package name="testaction" namespace="/" extends="struts-default">
        <action name="testAction" class="com.struts.action.TestAction">
            <result name="success">/success.jsp</result>
            <result name="error">/index.jsp</result>
        </action>
    </package>
</struts>其中一个action对应一个响应,在index.jsp中action="testAction"所以此处action的name="testAction"这是一一对应的关系。然后此处的class对应的则是交给谁去处理,根据配置文件我们在com.struts.action包中新建一个TestAction的类,此类的内容如下:package com.struts.action;public class TestAction {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String execute(){
        if ("username".equals(name)) {
            return "success";
        } else {
            return "error";
        }
       
    }
}在这里我们需要写一个返回值为String类型的execute方法,这里的return对应struts.xml中的result的name属性,而struts.xml中的result的内容这对应相应的页面。这里的字段名称则是对应index.jsp中的name,一般我们在servlet中是用request.getParameter("name")得到的,但是在struts2中我们只需要把字段封装一下,剩下的交给struts2去做。当然还有一个问题就是execute方法是默认的方法,如果我们的方法名称不为execute则需要在struts.xml中的action中加一个属性:method="对应方法名称",这样struts2就会调用对应类的对应方法。在TestAction中的第12行这里我只是进行了简单的判断,大家可以根据自身情况连接数据库来做一个登陆的例子锻炼一下。推荐阅读:Struts中异步传送XML和JSON类型的数据 http://www.linuxidc.com/Linux/2013-08/88247.htmStruts2的入门实例 http://www.linuxidc.com/Linux/2013-05/84618.htmStruts2学习笔记-Value Stack(值栈)和OGNL表达式  http://www.linuxidc.com/Linux/2015-07/120529.htm struts2文件上传(保存为BLOB格式) http://www.linuxidc.com/Linux/2014-06/102905.htmStruts2的入门实例 http://www.linuxidc.com/Linux/2013-05/84618.htmStruts2实现ModelDriven接口 http://www.linuxidc.com/Linux/2014-04/99466.htm遇到的Struts2文件下载乱码问题 http://www.linuxidc.com/Linux/2014-03/98990.htmStruts2数据验证机制  http://www.linuxidc.com/Linux/2016-10/135995.htmStruts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htmStruts2 注解模式的几个知识点 http://www.linuxidc.com/Linux/2013-06/85830.htmStruts 的详细介绍:请点这里
Struts 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-11/137146.htm