• struts2--入门


    使用Struts 2 开发程序的基本步骤:

         加载Struts2 类库

         配置web.xml文件

           开发视图层页面

         开发控制层Action

         配置struts.xml文件

           部署、运行项目

    Struts2框架中所需的jar包   pox.xml:

       <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.3</version>
    
            </dependency>
    
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-core</artifactId>
                <version>2.3.4.1</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.struts.xwork</groupId>
                <artifactId>xwork-core</artifactId>
                <version>2.3.4.1</version>
            </dependency>
    
        </dependencies>

    步骤1: 配置web.xml文件:

    <web-app>
      <display-name>Archetype Created Web Application</display-name>
      <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>
    </web-app>

    步骤2:在src下创建名称为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>
        <!--该属性设置Struts 2是否支持动态方法调用,该属性的默认值是true。如果需要关闭动态方法调用,则可设置该属性为false。-->
        <constant name="struts.enable.DynamicMethodInvocation" value="true"/>
        <!-- 配置文件中只要添加以下配置,那么以后修改配置文件不用重启tomcat -->
        <constant name="struts.devMode" value="true"/>
        <!--对默认主题风格修改 -->
        <constant name="struts.ui.theme" value="simple"/>
    
        <package name="default" namespace="/" extends="struts-default  ">
            <action name="helloWorld" class="cn.happy.entity.HelloWorldAction">
                <result name="success">success.jsp</result>
                <result name="errow">index.jsp</result>
                <result name="input">index.jsp</result>
            </action>
        </package>
    </struts>

     namespace 和 action的name属性,决定 Action的访问路径 (以/开始 ) 
    extends 继承哪个包,通常开发中继承 struts-default 包 (struts-default包在 struts-default.xml定义 ) 
    继承struts-default包后,可以使用 包中定义拦截器和结果类型 
    action元素配置默认值 
    package 的namespace 默认值‘’‘’ 
    action 的class 默认值 ActionSupport 类 
    result 的 name 默认值 success

    步骤3:编写HelloWorldAction:

    package cn.happy.entity;
    
    
    import com.opensymphony.xwork2.Action;
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    
    import java.util.Map;
    
    /**
     * Created by CKW on 2017/2/28.
     */
    public class HelloWorldAction extends ActionSupport implements Action{
       private Users user;
       private String message;
    
       public void validate(){
           if (this.user.getUname().length()==0){
               addFieldError("uname","用户名不能为空");
    
           }
           if (this.user.getUpassword().length()==0){
               addFieldError("upwd","密码不能为空!");
           }
       }
    
        public String execute() throws Exception {
            if ("111".equals(user.getUname())&&"111".equals(user.getUpassword())){
                Map<String,Object> session=null;
                session= ActionContext.getContext().getSession();
                session.put("aa",this.user.getUname());
                //this.setMessage(this.user.getUname());
                return "success";
            }else{
                addFieldError("cc","用户名或者密码不正确");
                return "errow";
            }
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        public Users getUser() {
            return user;
        }
    
        public void setUser(Users user) {
            this.user = user;
        }
        
    }

    步骤4:创建index.jsp页面:

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%--<%--%>
        <%--String path = request.getContextPath();--%>
        <%--String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";--%>
    <%--%>--%>
    <%@ page isELIgnored="false"%>
    <%@taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
        <title>登录</title>
        <div>
            <h2><s:property value="message"/> </h2>
        </div>
    
    </head>
    <body>
    <h1>登录</h1>
    <s:fielderror fieldName="cc"></s:fielderror>
    
    <s:debug></s:debug>
    <s:form action="helloWorld" method="POST">
        <div>
            姓名:<s:textfield name="user.uname"><s:fielderror fieldName="uname"></s:fielderror></s:textfield>
        </div>
        <br>
        <div>
            密码:<s:textfield name="user.upassword"><s:fielderror fieldName="upwd"></s:fielderror></s:textfield>
        </div>
       <br>
        <s:submit value="提交"></s:submit>
    </s:form>
    <%--<form action="helloWorld" method="post">--%>
        <%--姓名:<input type="text" name="user.uname"/>--%>
        <%--密码:<input type="text" name="user.upassword"/>--%>
        <%--<input type="submit" value="提交"/>--%>
    <%--</form>--%>
    </body>
    </html>

    为空判断:

    错误判断:

    登录正确页面:

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%--<%--%>
        <%--String path = request.getContextPath();--%>
        <%--String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";--%>
    <%--%>--%>
    <%@ page isELIgnored="false"%>
    <%@taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
        <title>成功</title>
    </head>
    <body>
    <h1>登录成功!欢迎${sessionScope.aa} </h1>
    </body>
    </html>

    步骤6.使用Servlet API去向Session中放入数据:
    *解耦方案
    ActionContext类 :
    Map<> map= ActionContext.getContext().getSession();
    map.put()

    *耦合方案
    HttpSession session=ServletActionContext.getRequest().getSession();
    session.setAttribute();

            =====常用常量:

    <constant name="struts.i18n.encoding" value="UTF-8"/>  ----- 相当于request.setCharacterEncoding("UTF-8"); 解决post请求乱码 
    <constant name="struts.action.extension" value="action"/>  --- 访问struts2框架Action访问路径 扩展名 (要求)
    struts.action.extension=action, 默认以.action结尾扩展名 和 不写扩展名 都会分发给 Action
    <constant name="struts.serve.static.browserCache" value="false"/> false不缓存,true浏览器会缓存静态内容,产品环境设置true、开发环境设置false 
    <constant name="struts.devMode" value="true" />  提供详细报错页面,修改struts.xml后不需要重启服务器 
    <constant name="struts.ui.theme" value="simple"/>对默认主题风格修改

    Action

    Action书写的的三种格式

    第一种

    Action可以是 POJO ((PlainOldJavaObjects)简单的Java对象) —- 不需要继承任何父类,实现任何接口 
    * struts2框架 读取struts.xml 获得 完整Action类名 
    * obj = Class.forName(“完整类名”).newInstance(); 
    * Method m = Class.forName(“完整类名”).getMethod(“execute”); m.invoke(obj); 通过反射 执行 execute方法

    第二种

    编写Action 实现Action接口 
    Action接口中,定义默认五种 逻辑视图名称 
    public static final String SUCCESS = “success”; // 数据处理成功 (成功页面) 
    public static final String NONE = “none”; // 页面不跳转 return null; 效果一样 
    public static final String ERROR = “error”; // 数据处理发送错误 (错误页面) 
    public static final String INPUT = “input”; // 用户输入数据有误,通常用于表单数据校验 (输入页面) 
    public static final String LOGIN = “login”; // 主要权限认证 (登陆页面) 
    五种逻辑视图,解决Action处理数据后,跳转页面

    第三种

    编写Action 继承ActionSupport (推荐) 
    在Action中使用 表单校验、错误信息设置、读取国际化信息 三个功能

    Action的配置method(通配符)

    1) 在配置 元素时,没有指定method属性, 默认执行 Action类中 execute方法 
    2)使用通配符* ,简化struts.xml配置

    <a href="${pageContext.request.contextPath }/user/customer_add.action">添加客户</a>
    <a href="${pageContext.request.contextPath }/user/customer_del.action">删除客户</a>
    
    struts.xml
    <action name="customer_*" class="cn.itcast.struts2.demo4.CustomerAction" method="{1}"></action>   ---  {1}就是第一个* 匹配内容
    

    动态方法调用

    访问Action中指定方法,不进行配置 
    1) 在工程中使用 动态方法调用 ,必须保证 struts.enable.DynamicMethodInvocation = true 常量值 为true 
    2) 在action的访问路径 中 使用 “!方法名”

    页面
    <a href="${pageContext.request.contextPath }/user/product!add.action">添加商品</a>
    配置
    <action name="product" class="cn.itcast.struts2.demo4.ProductAction"></action>
    执行 ProductAction 中的 add方法
    

    Action访问Servlet API

    1、 在Action 中解耦合方式 间接访问 Servlet API ——— 使用 ActionContext 对象

    在struts2 中 Action API 已经与 Servlet API 解耦合 (没有依赖关系 ) 
    * Servlet API 常见操作 : 表单提交请求参数获取,向request、session、application三个范围存取数据

    actionContext = ActionContext.getContext(); 
    1) actionContext.getParameters(); 获得所有请求参数Map集合 
    2) actionContext.put(“company”, “传智播客”); / actionContext.get(“company”) 对request范围存取数据 
    3) actionContext.getSession(); 获得session数据Map,对Session范围存取数据 
    4) actionContext.getApplication(); 获得ServletContext数据Map,对应用访问存取数据

    2、 使用接口注入的方式,操作Servlet API (耦合)

    1.要求action类必须实现提定接口。 
    ServletContextAware : 注入ServletContext对象 
    ServletRequestAware :注入 request对象 
    ServletResponseAware : 注入response对象

    2.重定接口中的方法。 
    private HttpServletRequest request; 
    3.声明一个web对象,使用接口中的方法的参数对声明的web对象赋值.

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }
    

    3、 在Action中直接通过 ServletActionContext 获得Servlet API

    ServletActionContext.getRequest() : 获得request对象 (session) 
    ServletActionContext.getResponse() : 获得response 对象 
    ServletActionContext.getServletContext() : 获得ServletContext对象 
    ServletActionContext.getPageContext().getSession(); //获取session等对象

  • 相关阅读:
    C#写文本文件,如何换行(添加换行符)
    C#使用oledb操作excel文件的方法
    winform之combobox
    vs2010快捷键
    可以下载一些书籍代码的网站
    对php和java里面的static函数和static的一些理解
    10.4-CMake find 模块
    6.25-Git 技巧
    6.4-Git Command
    2.25-CMake Tutorial
  • 原文地址:https://www.cnblogs.com/ckwblogs/p/6478907.html
Copyright © 2020-2023  润新知