Struts2学习1-使用struts2写一个helloword

 

  1. 使用struts2的准备
    1. Struts2jar包

       下载地址:https://struts.apache.org/download.cgi#struts2520

  1. 使用struts2的步骤
    1. 新建一个web工程
    2. 在WEB-INF/lib中导入相关jar包

不能够导入lib下的全部jar包,可以在下载好的struts.2.x.x.zip中的apps文件夹内解压一个war文件,在解压的WEB-INF目录下找到lib导入里面的全部包。

    1. 在web.xml配置核心控制器

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_9"

   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4">

   <display-name>struts01</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>

   <welcome-file-list>

      <welcome-file>index.jsp</welcome-file>

   </welcome-file-list>

</web-app>

红色部分是固定写法。有2中方式可以找到这个固定的写法。

 

 
 


第一种:在apps解压的war文件的WEB-INF目录下的web.xml里复制

第二种:在core核心包中找到filter结尾的包里面文件名最长的class复制路径到web.xml的filter中

    1. 在src下创建struts.xml配置文件

Struts.xml必须在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="hello" class="com.action.HelloAction">

   <!-- result返回集,name是方法返回的返回值

          根据返回值跳转到哪个页面 ,默认type是转发-->

      <result name="success">/index.jsp</result>

      </action>

   </package>

</struts>

Doctype可以在在struts2-core包最下面的struts-default.xml文件中复制

      

到此处struts2框架就搭建起来可以使用了。

 

    1. action类

 

public class HelloAction {

   /*

    * servlet 请求servlet会去执行一个service

    * action action默认是执行execute

    * */

   public String execute() {

      System.out.println("this is action");

      return "success";

   }

}

写好这些之后将项目部署到tomcat,启动tomcat在浏览器输入localhost:8080/struts01/hello

打开控制台

控制台预期输出我们写好的字符串,浏览器也跳转到了index.Jsp,到这里就完成了第一个struts2的web程序。

 

 

              总结几个我在第一次用struts2常犯的错误

  1. struts.xml名字写错,或者没有创建在src下面
  2. struts.xml中packge没有继承struts-defoult或者写错,漏掉namespace
  3. web.xml没有创建在WEB-INF目录下
  4. action方法中的execute()不能写错。

猜你喜欢

转载自blog.csdn.net/u012777599/article/details/88809652
今日推荐