您的位置:首页 > 编程语言 > Java开发

struts2入门—输出helloworld

2016-10-08 19:04 363 查看
结构总览:



填写图片摘要(选填)



1.下载struts2(此例所用版本为struts-2.3.14-all)

2.配置struts2

    在eclipse中新建​dynamic web project

    ​在下载的struts中找到struts-2.3.14-all\struts-2.3.14\apps\struts2-blank\WEB-           INF\lib,将其中的jar包全部复制到新建项目的webcontent->WEB-INF->lib目录下,如果单纯的在build path中添加,可能会报错说找不到某个类,因为其在加载的时候默认路径为lib路径,放在其他路径下会找不到jar包从而报错

   为新建项目配置tomcat服务器

3.配置web.xml文件,如下:​

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  

  <filter>

  <filter-name>struts2</filter-name>  //struts2过滤器的名称

  <filter-class>

  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter   //struts2过滤器的类名,均为默认即可

  </filter-class>

  </filter>

//配置struts要过滤的路径​

  <filter-mapping>  

    <filter-name>struts2</filter-name>  

    <url-pattern>/*</url-pattern>    //设置所有请求都过滤

  </filter-mapping>

</web-app>

4.编写helloWorld.jsp界面

<%@ taglib prefix="s" uri="/struts-tags"%>

<html>

<head>

<title>hello world</title>

</head>

<body>

<h2>

<s:property value="message"/>    //使用proprity标签来获取action中的属性

</h2>

</body>

</html>

​5.编写action,即java类名HelloWorld.class

package struts2;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorld extends ActionSupport {

public static final String MESSAGE = "HELLO WORLD!";

private String message="hello";

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

public String execute() throws Exception {

setMessage(MESSAGE);

return SUCCESS;

}

}

6.配置struts.xml文件,在其中增加映射

struts.xml文件在struts-2.3.14\apps\struts2-blank\WEB-INF\classes​中可以获取,将其复制到java resource->src路径下,并修改为:

<?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>

    <constant name="struts.devMode" value="true" />

    <package name="struts2" extends="struts-default">

//配置类(action)HelloWorld,并设置其转向界面helloWorld.jsp​

<action name="HelloWorld" class="struts2.HelloWorld">

<result>/helloWorld.jsp</result>

</action>

    </package>

</struts>

​7.重启tomca,在浏览器中输入http://localhost:8080/Struts/HelloWorld.action,自动跳转到helloWorld.jsp文件,如下所示:





填写图片摘要(选填)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: