zoukankan      html  css  js  c++  java
  • [java]struts2入门

     

    摘要

    本文是struts2入门,配置教程。如何在IntelJ Idea中进行手动配置。在使用idea新建struts2web项目的时候,在下载jar包的过程中,下载失败,没办法就直接手动进行下载jar包。

    步骤

    1. 从官网下载jar包,这里下载的是struts-2.3.34.zip,下载之后,解压
    2. 在struts-2.3.34apps下找到
    3. struts2-blank.war 文件,通过修改扩展名,改为struts2-blank.zip,解压,找到lib下的所有jar包,如下图所示:

    将其,拷贝到idea的demo项目下,如图

    4、添加包引用 File>Project structure>Library>+

    5、将struts-2.3.34appsstruts2-blankWEB-INFclassesstruts.xml文件拷贝到项目的src目录下,如图

    保留struts节点,将其内部的节点都删除。

    6、在src目录下添加包com.demo.action,并添加第一个action类

    package com.demo.action;
    
    public class HelloAction {
        public String helloWord() {
    
        return "200";
        }
    }

    7、在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>
        <package name="hello" namespace="/" extends="struts-default">
            <!--配置action类 name 这里配置xxx,使用的时候 xxx.action 或者xxx,class 类的全路径(包+类名) method 要调用的方法-->
            <action name="hello" class="com.demo.action.HelloAction" method="helloWord">
                <!--配置得到action返回值,之后的跳转或者转发页面-->
                <result name="200">/success.jsp</result>
            </action>
        </package>
    </struts>

    其中extends常用struts-default。namespace:相当于访问的action所在的目录,如果配置成/ 可以通过/hello.action 访问,如果配置成/aaa,那么需要通过/aaa/hello.action进行访问。

    8、配置struts控制器,也就是过滤器

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
        <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>

    9、添加测试页面在index.jsp中,通过跳转,跳转到我们的hello.action

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>首页</title>
    </head>
    <body>
    
    <a href="${pageContext.request.contextPath}/hello.action">第一个struts2 web应用</a>
    </body>
    </html>

    注意这里使用el表达式和jsp,需要添加包,添加tomcat自带的即可。

    测试

    跳转

     到这里,我们的第一个struts2 web应用demo已经成功了。

    那么,hello.action 必须得.action吗?

    如果我们改成其他的可以吗,比如.dd,如下图所示:

    当然,也可以不带action

    如下

  • 相关阅读:
    语言基础
    进制转换
    ado属性扩展
    ado数据模型和数据访问类,泛型集合
    完整的修改和删除
    完整的删除
    修改
    类库
    接口
    抽象类
  • 原文地址:https://www.cnblogs.com/wolf-sun/p/9092214.html
Copyright © 2011-2022 走看看