我的第一个struts程序(Struts1.X实现MVC框架)

 

我的第一个struts程序(Struts1.X实现MVC框架)

我对struts的理解是从看了陈宝峰老师的视频到我的第一个struts程序的产生之后得来的,struts是基于MVC模式的一种框架,struct分为两种,struct1.xstruct2.x

下面是struts的框架图和struts的原理,本人觉得这个图能够很好的表明struts的原理。

一:struts原理(struts1.x

 

 Struts原理图

                               Struts工作的原理图(终于把图片给传上来了) 

浏览器将请求发送到服务端,进入到了servlet容器,容器将请求送到控制器,控制器只有一个,而请求有很多,这时struts提供给我们的一个配置文件struts-config.xmlstruts是通过该配置文件知道是哪个用户的请求和该请求所对应的动作所执行的任务之间进行配对,通过配对,这时控制器就能知道这个请求应该由哪个任务来执行。Struct将用户请求所对应的每个动作该执行的任务封装成一个javaBean,这个javaBeanstruct里称为Action,也就是说当请求被控制器截获的时候, 当控制器受到请求的时候,应该根据请求去执行哪个任务呢?通过对配置文件的阅读,就知道执行那个任务。当Action在执行任务的时候就需要调用一些服务,这些服务被称为模型层,不管它调用什么,它都要完成任务,不管成功或者失败,控制器都要进行请求转发,吧请求转发给jsp页面,当成功/失败时,只要读取配置文件就知道要转给哪个jsp页面输出结果,最后某一个jsp页面收到请求之后执行任务,然后将结果输给浏览器。

因为就是说我们是在一个固定的流程当中写我们自己的程序。这个框架称之为FrameWork图中蓝色的字的部分为自己要编写的。

编写struct的过程如下:

一:环境的搭建

包括eclipse的安装,jdktomcateclipse中的配置

1:在www.eclipse.org 这个网站上下载最新的eclipse for javaBean EE,该工具是专门为用来开发java web的。比起在普通eclipse中安装Myeclipsetomcat插件的方法要方便的多。将下载下来的eclipse安装包解压后放在你自己的硬盘上就可以用了。我下载的是

2:当然还要在eclipse中配置jdktomcat。首先你得安装好jdktomcat,再在windows->preforance->server中选择jdktomcat的安装目录就可以了。

3:建立一个项目project。名字就做HelloWeb。将下载好的struts打开,我下载的是struts-1.3.10-all.zip。在app/struts-blank-1.3.10.war/WEB-INF/lib中将要用到的strutsjar文件全部拷贝到自己的web目录下:

二:创建web项目(项目的需求)

1:需求分析:

     在输入框中输入一个名字后XX,点击提交按钮出现:XX你好

     当没有输入任何的人名点击提交的时候出现错误信息:名字为空

     当输入的名字是god的时候,出现错误信息“不能和god打招呼”

2struts的编写流程中的重点:

     提取参数放在form类当中,

     执行form类中的validate方法进行验证

验证成功后将请求转发给Action

     Action成功/或者失败后将请求转到某一个jsp页面,有这个jsp页面收到请求之后执行任务,最后将结果输给浏览器。

3:分析:

首先要编写一个jsp输入页面,名字为hello.jsp

一个接收参数的form。名字为HelloForm.java

一个Action类。名字为FromAction.java

一个web.xmlstruts-config.xml配置文件

 

三:创建视图组件(包括struct的程序流程)

     Hello.jsp代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<div style="color:red"><html:errors/></div>

<form name="hello_form" method="post" action="hello.do">

your name:<input type="text" name="name"/>

<input type="submit" value="submit"/>

</form>

</body>

</html>

一个接收参数的form。名字为HelloForm.java

package com.web.action;

 

import javax.servlet.http.HttpServletRequest;

 

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionMessage;

 

public class HelloForm extends ActionForm {

   private String name;

 

public String getName() {

     return name;

}

 

public void setName(String name) {

     this.name = name;

}

 

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

     ActionErrors errors=new ActionErrors();

     if(name==null||name.length()==0){

          errors.add("hello_error",new ActionMessage("error.hello.namenull"));

     }

     if(errors.isEmpty())

          return null;

     return errors;

}

  

}

一个Action类。名字为FromAction.java

package com.web.action;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionMessage;

 

public class FormAction extends Action {

 

     public ActionForward execute(ActionMapping mapping, ActionForm form,

                HttpServletRequest request, HttpServletResponse response)

                throws Exception {

          HelloForm hf=(HelloForm)form;

          ActionErrors errors=new ActionErrors();

          if(hf.getName().equals("god")){

                errors.add("action_error",new ActionMessage("error.hello.nameinvalidate"));

              this.saveErrors(request, errors);

              return mapping.getInputForward();

          }

          return mapping.findForward("success");

     }

 

}

 一个请求成功后的页面:ok.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

Hello,${param.name} !

</body>

</html>

程序中用到的资源文件为ApplicationResources.properties内容为:

error.hello.namenull=Name should not be null

error.hello.nameinvalidate=Name is invalidate

四:配置web.xmlstruts-config.xml文件

 

Web.xml

程序员自己要写的东西

    <servlet>

    <servlet-name>action</servlet-name>

    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

    <init-param>

      <param-name>config</param-name>

      <param-value>/WEB-INF/struts-config.xml</param-value>

    </init-param>

    <load-on-startup>2</load-on-startup>

 </servlet>

 

 

  <!-- Standard Action Servlet Mapping -->

  <servlet-mapping>

    <servlet-name>action</servlet-name>

    <url-pattern>*.do</url-pattern>

  </servlet-mapping>

 

struts-config.xml文件

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!--

    Licensed to the Apache Software Foundation (ASF) under one or more

    contributor license agreements.  See the NOTICE file distributed with

    this work for additional information regarding copyright ownership.

    The ASF licenses this file to You under the Apache License, Version 2.0

    (the "License"); you may not use this file except in compliance with

    the License.  You may obtain a copy of the License at

  

         http://www.apache.org/licenses/LICENSE-2.0

  

    Unless required by applicable law or agreed to in writing, software

    distributed under the License is distributed on an "AS IS" BASIS,

    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

    See the License for the specific language governing permissions and

    limitations under the License.

-->

 

<!DOCTYPE struts-config PUBLIC

          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"

          "http://struts.apache.org/dtds/struts-config_1_3.dtd">

 

<!--

     This is a blank Struts configuration file with an example

     welcome action/page and other commented sample elements.

 

     Struts Validator is configured using the factory defaults

     and is ready-to-use.

 

     NOTE: If you have a generator tool to create the corresponding Java classes

     for you, you could include the details in the "form-bean" declarations.

     Otherwise, you would only define the "form-bean" element itself, with the

     corresponding "name" and "type" attributes, as shown here.

-->

 

<struts-config>

 

<!-- ======================================== Form Bean Definitions -->

 

    <form-beans>

    <form-bean name="helloform" type="com.web.action.HelloForm"/>

    <!-- sample form bean descriptor for an ActionForm

        <form-bean

            name="inputForm"

            type="app.InputForm"/>

    end sample -->

 

    <!-- sample form bean descriptor for a DynaActionForm

        <form-bean

            name="logonForm"

            type="org.apache.struts.action.DynaActionForm">

            <form-property

                name="username"

                type="java.lang.String"/>

            <form-property

                name="password"

                type="java.lang.String"/>

       </form-bean>

    end sample -->

    </form-beans>

 

 

<!-- ========================================= Global Exception Definitions -->

 

    <global-exceptions>

        <!-- sample exception handler

        <exception

            key="expired.password"

            type="app.ExpiredPasswordException"

            path="/changePassword.jsp"/>

        end sample -->

    </global-exceptions>

 

 

<!-- =========================================== Global Forward Definitions -->

 

    <global-forwards>

        <!-- Default forward to "Welcome" action -->

        <!-- Demonstrates using index.jsp to forward -->

        <forward

            name="welcome"

            path="/Welcome.do"/>

    </global-forwards>

 

 

<!-- =========================================== Action Mapping Definitions -->

 

    <action-mappings>

    <action path="/hello"

            name="helloform"

            type="com.web.action.FormAction"

            input="/hello.jsp"

            validate="true"

    >

    <forward name="success" path="/ok.jsp"/>

    </action>

            <!-- Default "Welcome" action -->

            <!-- Forwards to Welcome.jsp -->

        <action

            path="/Welcome"

            forward="/pages/Welcome.jsp"/>

 

    <!-- sample input and input submit actions

 

        <action

            path="/Input"

            type="org.apache.struts.actions.ForwardAction"

            parameter="/pages/Input.jsp"/>

 

        <action

            path="/InputSubmit"

            type="app.InputAction"

            name="inputForm"

            scope="request"

            validate="true"

            input="/pages/Input.jsp"/>

 

            <action

                path="/edit*"

                type="app.Edit{1}Action"

                name="inputForm"

                scope="request"

                validate="true"

                input="/pages/Edit{1}.jsp"/>

 

    end samples -->

    </action-mappings>

 

 

<!-- ======================================== Message Resources Definitions -->

 

    <message-resources parameter="ApplicationResources" />//程序中要用到的资源文件

 

 

<!-- =============================================== Plug Ins Configuration -->

 

  <!-- ======================================================= Tiles plugin -->

  <!--

     This plugin initialize Tiles definition factory. This later can takes some

     parameters explained here after. The plugin first read parameters from

     web.xml, thenoverload them with parameters defined here. All parameters

     are optional.

     The plugin should be declared in each struts-config file.

       - definitions-config: (optional)

            Specify configuration file names. There can be several comma

           separated file names (default: ?? )

       - moduleAware: (optional - struts1.1)

            Specify if the Tiles definition factory is module aware. If true

            (default), there will be one factory for each Struts module.

           If false, there will be one common factory for all module. In this

            later case, it is still needed to declare one plugin per module.

            The factory will be initialized with parameters found in the first

            initialized plugin (generally the one associated with the default

            module).

             true : One factory per module. (default)

             false : one single shared factory for all modules

       - definitions-parser-validate: (optional)

            Specify if xml parser should validate the Tiles configuration file.

             true : validate. DTD should be specified in file header (default)

             false : no validation

      Paths found in Tiles definitions are relative to the main context.

      To use this plugin, download and add the Tiles jar to your WEB-INF/lib

      directory then uncomment the plugin definition below.

 

    <plug-in className="org.apache.struts.tiles.TilesPlugin" >

 

      <set-property property="definitions-config"

                       value="/WEB-INF/tiles-defs.xml" />

      <set-property property="moduleAware" value="true" />

    </plug-in>

  --> 

 

 

  <!-- =========================================== Validator plugin -->

  <plug-in className="org.apache.struts.validator.ValidatorPlugIn">

    <set-property

        property="pathnames"

        value="/org/apache/struts/validator/validator-rules.xml,

               /WEB-INF/validation.xml"/>

  </plug-in>

 

</struts-config>

 

 

 

:发布和运行

启动tomcat,运行hello.jsp

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值