struts2框架搭建demo

虽然现在struts框架已很少单独使用,作为一个新手,本文仅已记录个人学习过程,不正确之处,欢迎指正!

  1. 新建一个WEB项目,并导入核心jar包,jar包可以在官网上下载,个人网盘分享链接:https://pan.baidu.com/s/1nuO8sPj 密码:gnif,
  2. 在项目src目录下新建struts.xml,然后加入xml配置文件的头文件说明
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

    这段代码可以在struts2-core.jar 的 struts-default.xml这个文件直接复制,GBK是防止中文乱码,然后在web.xml中进行配置刚才新建的struts.xml配置如下

    struts2
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter


    struts2
    /*

    这段代码的作用是配置系统的哪些请求交给struts框架进项处理,filter-class中的这个class文件是struts核心jar包中的
    struts2框架搭建demo_第1张图片
    完成这些基本配置后,可以写一个demo页面来进行测试,页面内容为一个简单的login页面
 <s:form action="login" method="post">
        username:<s:textfield name="username">s:textfield><br>
        password:<s:password name="password">s:password><br>
        <s:submit value="登陆">s:submit>
    s:form>

这是需要注意的是页面使用struts的页面便签是需要在struts.xml配置文件中加上

在struts框架中有定义各种页面风格的,这个是说明忽略框架的页面风格struts2框架搭建demo_第2张图片
但是这种页面标签有个好处,就是在出现验证错误,需要返回时,可以根据前后台页面自动匹配,不需要另外返回参数,
action包中定义个LoginAction,用来处理本次的登录逻辑

private String username;
    private String password;
    public String login(){
        System.out.println("用户名:"+username);
        System.out.println("密码:"+password);
        return "success";
    }
    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;
    }

在控制层上,也可以看出使用框架的好处,只需要声明一个和页面一样的变量即可获取到它的参数值,request、response作用域是不需要声明的,同理也可以使用对象进行传参,此处不再赘述,在进行请求结果转发时我们只需要在struts中加上result即可

<struts>
    
    <constant name="struts.i18n.encoding" value="UTF-8">constant>
    
    <constant name="struts.ui.theme" value="simple">constant> 
    <package name="default" namespace="/" extends="struts-default">
        <action name="login" class="strutsTest.action.LoginAction" method="login">
            <result name="index">index.jspresult>
            <result name="success">success.jspresult>
        action>
    package>
struts>

你可能感兴趣的:(框架)