1. 程式人生 > >HelloWorld_Struts2-Struts2框架搭建

HelloWorld_Struts2-Struts2框架搭建

專案結構:


所需jar包:

       獲取方法就是下載struts2的2.1.6版本壓縮包,解壓,獲得struts-2.1.6/apps下的struts2-blank-2.1.6.war,再解壓縮,獲取struts2-blank-2.1.6\WEB-INF\lib下的全部jar包,這就是搭建基本的struts2框架所需要的jar包。

HelloWorld_Struts2.java原始碼:

package com.struts2.helloworld_struts2;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class HelloWorld_Struts2 extends ActionSupport{

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		System.out.println("This Is HelloWorld_Struts2 Page."+"\n");
		return SUCCESS;
	}

}

index.jsp頁面原始碼:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<html>
  <head>
    <base href="<%=basePath%>">
    <title>This Is Index Page</title>
  </head>
  <body>
  <h2>This Is HelloWorld_Struts2 Index Page</h2> <br>
    Welcome To
    <a href="<%=basePath%>helloworld_struts2" style="text-decoration: none">HelloWorld_Struts2</a>
    page.<br/>
  </body>
</html>

HelloWorld_Struts2.jsp頁面原始碼:
<html>
<head>
<title>This Is HelloWorld_Struts2 Page</title>
</head>
<body>
<h2>This Is <span style="color: blue">HelloWorld_Struts2</span> Page.</h2>
<br>
</body>
</html>

web.xml配置檔案原始碼:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<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>

struts.xml-Struts2配置檔案原始碼:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.devMode" value="true" />
    <package name="default" namespace="/" extends="struts-default">
        <action name="helloworld_struts2" class="com.struts2.helloworld_struts2.HelloWorld_Struts2">
            <result>/HelloWorld_Struts2.jsp</result>  
        </action>
    </package>

</struts>

訪問路徑:

http://localhost:8080/HelloWorld_Struts2/

執行結果:


點選藍色字型,進入struts2介面:


此時控制檯輸出:

This Is HelloWorld_Struts2 Page.