Struts1.3——Struts入门

1.Struts的几个基本概念

1.struts是一个开源框架(frameset)
2.struts是一个Web框架
3.struts是一个基于MVC的Web框架

2.为什么有struts

因为我们对MVC的理解不同,可能造成不同公司写程序的时候,规范不统一,这样不利于程序的维护和扩展以及提高开发效率,所以我们有必要用一个统一的规范来开发项目。所以出现了struts.

struts是通过采用Java的Servlet/JSP技术,实现了基于Java EE Web应用的Model-View-Controller(MVC)设计模式的应用框架,是MVC经典设计模式中的一个经典产品

struts的优缺点如下:
1.struts的好处:

程序更加规范化
程序开发的效率提高了
程序的可读性增加
程序的可维护性增加

2.struts的不足之处:

form表单有点鸡肋
action是单态(对网站并发性的处理有影响)

这些内容后面会介绍。

我们要知道的是:框架在提高了程序的规范的同时,也约束了程序员的自由。

3.struts的原理

以一个用户登录验证的例子说明。

3.1.时序图

时序图

1.ActionServlet是总控制器,它是struts给我们提供的,我们无需自己写,只需要配置即可。ActionServlet管理struts-config.xml文件,而这个文件是struts的核心文件,该文件配置了ActionForm,还配置了Action,以及它们的对应关系等。
2.ActionForm是表单,用于存放数据。开发ActionFrom必须要继承ActionForm类,这是规范。
3.Action是分控制器,在Struts中,Action可以有多个.它的本质就是Servlet。开发一个Action也要继承Action类。
4.Model(Java类,Service类,ejb等)

3.2.struts入门案例

以上述用户登录验证来演示,并且使用手动配置的方式来开发第一个struts项目,项目名称为strutslogin。
首先,项目目录结构如下所示:

项目目录结构

【步骤】:
1.在开发struts的时候,需要struts的开发包

struts的开发包可到官网下载【下载地址】,它的最新版本是2.5.1(2016年6月21日)。由于目前所学为1.3的版本,所以我下载Struts 1.3.10。并把所有的jar包加入到当前项目的lib文件夹。


2.先写出login.jsp

写最简单的登录页面login.jsp,如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
  </head>
  <body>
    <form action="/strutslogin/login.do" method="post">
        UserName:<input type="text" name="username"/><br><br>
        Password:<input type="password" name="password"/><br><br>
        <input type="submit" value="Login"/>    
    </form>
  </body>
</html>
  • 注意,为了安全起见,login.jsp放在WEB-INF目录下,在WEB-INF目录外通过index.jsp转发到login.jsp。
  • 注意form中的action跳转地址,是我们的web应用下的login.do页面,这里在稍后介绍的struts-config.xml配置中会再说明。

3.编写ActionForm和Action

(1)首先需要编写ActionForm,即用户登录所用的表单,用于填充用户输入的数据。我们取名为UserForm,它继承自ActionForm类,如下:

public class UserForm extends ActionForm {

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

其实这就是一个很简单的JavaBean,它和login.jsp中的表单对应,我们在这个UserForm中定义属性usernamepassword,并生成它们的settergetter方法。
这里需要注意的是:

<1>.一般的规范:定义属性名称的时候应该和jsp页面的控件名称一样。
<2>.但其实,属性的名称并非一定要一致,而真正要保持一致的是settergetter方法。也就是说,如果你在jsp中定义的控件名称为username和password,那么setter方法的名称一定是setUsernamesetPassword,同理,getter方法的名称一定是getUsernamegetPassword。属性可以换其他的名字,但是这几个方法的名称一定要固定格式:get/set+控件名称并且首字母大写
<3>.但我们遵守一般的规范最好。
<4>.ActionForm一定要按照上述规范写好,才能保证数据能够正确填充,才能保证work

(2)然后,编写Action,即登录的Action,我们取名为LoginAction,它必须继承自Action类,如下:

public class LoginAction extends Action {
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 把form转成对应的UserForm对象
        UserForm userForm = (UserForm)form;
        System.out.println("用户名="+userForm.getUsername());
        System.out.println("密码="+userForm.getPassword());
        // 简单验证
        if("123".equals(userForm.getPassword())){
            // 如果用户密码为123,则为合法
            return mapping.findForward("ok");
        }else{
            return mapping.findForward("error");
        }
    }
}

在这个类中,我们需要重写一个方法:excute。这个方法会处理业务逻辑,会自动调用,它有点类似于Servlet中的service方法,或者doGet/doPost方法。


4.配置struts-config.xml文件,这个文件一般放在/WEB-INF目录下,它配置Action、ActionForm以及它们的对应关系和跳转

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Structs Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
    <!-- 配置表单 -->
    <form-beans>
        <!-- name是表单名字,可以随意写,但是建议取名规范:表单类名小写 -->
        <!-- type用于指定表单类的全路径 -->
        <form-bean name="userForm" type="com.gavin.forms.UserForm"></form-bean>     
    </form-beans>
    <!-- 配置Action -->
    <action-mappings>
        <!-- 配置一个具体的action -->
        <!-- path表示将来访问该action的资源名,http://localhost:8080/web/path -->
        <!-- name用于关联某个表单 -->
        <!-- type用于指定该Action类的全路径 -->
        <action path="/login" name="userForm" type="com.gavin.actions.LoginAction">
            <!-- 这里配置跳转关系 -->
            <!-- name表示结果名称,path表示转发到的页面地址 -->
            <forward name="ok" path="/WEB-INF/welcome.jsp"/>
            <forward name="error" path="/WEB-INF/error.jsp"/>
        </action>
    </action-mappings>
</struts-config>

(1)这个struts-config.xml引入了一个DTD文件:struts-config_1_3.dtd,这个文件可以在我们下载的jar包中找到,它定义了我们这个xml的约束,根元素为struts-config
(2)该配置文件主要通过form-beans来配置ActionForm、通过action-mappings来配置Action。
(3)我们在form-beans下用form-bean来配置具体的ActionForm,比如当前文件配置了我们写的UserForm
(4)在action-mappings下用action来配置具体的Action,比如当前文件配置了我们写的LoginAction
(5)要注意这里action中的path参数配置,它就是我们的login.jsp中的表单action提交的地址,login.jsp中写的是login.do,这个login.do会交给struts的总控制器ActionServlet来处理,最后ActionServlet将通过一定的机制找到这里的path参数配置为/login的action,再通过该action配置的type参数找到具体的类。

从这个过程中我们可以发现,login.do在通过ActionServlet的处理后,最后找到的却是路径为/login的action,这似乎和.do这个后缀没有什么关系,的确是这样的,这个后缀只是习惯上的用法,我们完全可以在web.xml文件中将这个后缀设置成其他任何的名字。
(6)最后要在具体的action下配置跳转关系。这里配置的参数和LoginAction中的excute方法所写要对应起来。


5.写出welcome.jsp和error.jsp页面

写出两个简单的界面即可。


6.在web.xml中配置ActionServlet

struts的总控制器ActionServlet本质上还是一个Servlet,所以我们要在web.xml中配置,配置如下:

<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <!-- 指定配置文件struts-config.xml的路径 -->
    <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

我们要在该配置中指定struts-config.xml文件的地址。同时可以看到,我们在这里配置的后缀为*.do,也就是说所有以.do结尾的请求都要交给ActionServlet来处理。到这里,也就明白了为什么我们的login.jsp中写的提交地址为login.do

4.总结

通过手工完成一个简单的struts项目,可以让我们对struts的工作流程和工作原理有更加深刻的认识。这个过程略微繁琐,后面会有工具直接生成,但是掌握底层原理是我们学习必不可少的一个步骤。

总结一下,其实struts是对我们通过JSP/Servlet和使用MVC模式开发项目的一个更高层次地提炼,它帮我们做了大部分工作,我们只需要按照struts框架提供的流程填充即可,简化了我们的开发的难度。

struts中的核心知识点:ActionServlet总控制器,Action分控制器,ActionForm表单,以及最重要的structs-config.xml和web.xml文件的配置。

  • 11
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
struts1.3.9 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值