struts2环境筹建以及第一个应用

struts2环境搭建以及第一个应用

环境搭建:

1、准备所需的JAR包:

struts2环境筹建以及第一个应用

注意,下载的sturts2下有很多的JAR包。不要全部拷过去,因为里面有很多的第三方JAR包。如果没有导入第三方JAR包导入依赖的JAR包,则会报错。

2、在WEB.XML中配置sturts2启动代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<filter>
		<filter-name>struts2</filter-name> 
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class><!-- 注意在2.1.3以上版本需使用此class -->
	</filter>
	<filter-mapping><!-- 配置url路径 -->
		<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>

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter的init方法会在web-inf/classes下寻找struts.xml配置文件。我们还未建立此文件,因此。下一步我们将建立此文件。

3、建立sturts.xml配置文件
上面说道StrutsPrepareAndExecuteFilter的Init在web-inf/calsses下寻找sturs.xml文件,而我们只需要在src目录下建立此文件即可。编译后会自动输出到classese目录下:
struts.xml配置文件:

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


启动不报错,环境搭建完成。

第一个应用:
1、配置struts.xml配置文件

<?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>
	<package name="wangfeng" namespace="/test" extends="struts-default">
		<action name="helloworld" class="com.feng.action.HelloWorldAction" method="execute">
			<result name="success">/WEB-INF/page/hello.jsp</result>
		</action>
	</package>
</struts>
2、建立action对应的类。
package com.feng.action;


public class HelloWorldAction {
	private String msg;
	
	public String getMessage() {
		return msg;
	}




	public String execute(){
		msg = "我的第一个Struts应用";
		return "success";
	}
}

3、配置视图hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'hello.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->


  </head>
  
  <body>
    ${message}  <br>
  </body>
</html>



浏览器输入:http://localhost:8080/struts2/test/helloworld



struts2环境筹建以及第一个应用