Struts2入門實例

步驟:
1、拷貝struts的jar到項目中(apps中的blank項目中可以找到這些jar包)
2、將struts2的過濾器添加到web.xml3、配置struts2的配置文件(在src目錄中創建struts.xml文件)
4、創建action(action就是一個POJO類)
    4.1、爲action編寫execute方法
    4.2、在struts.xml文件中配置action和返回結果集
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="default" namespace="/" extends="struts-default">
        <action name="hello" class="itat.org.zttc.action.HelloAction">
            <result name="success">/hello.jsp</result>
        </action>
    </package>
</struts>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <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>
處理請求的action
package itat.org.zttc.action;

public class HelloAction {
    public String execute() {
        System.out.println("hello struts");
        return "success";
    }

}
最終視圖頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Hello Struts2</h1>
</body>
</html>

結果:
Hello Struts2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章