您的位置:首页 > 移动开发

Struts2第1天-显示This is my first Struts Application

2011-02-23 22:01 459 查看
心得:把请求和显示的结果分开,是struts2的核心

运行原理:

①client首先发出一个请求,http://localhost:8080/Struts2_Hello/hello

②tomcat受到请求首先会参考web.xml,然后调用dofilter()交给struts2filter处理,而struts2filter文件参考struts2.xml,参考它的第一步是找到namespace,然后找到对应的action,然后再找到对应的result,当找到result的时候,就会把这个请求forward到Hello.jsp文件,这个Hello.jsp文件就会把内容反馈给客户端了

开发步骤

1、首先用myeclipse或者netbeans创建一个Java Web项目,比如项目名字是

Struts2_Hello

2、下载struts2的包,然后,将他们解压到一个目录,方便以后使用,解压后要用到如下这些



3、配置tomcat,打开Window-Preferences-MyEclipse-Servers-Tomcat-Tomcat 6.x,然后将tomcat目录填入,并选择Enable,确定即可
然后打开Window-Preferences-Installed JREs-Add-Standard VM-选择JDK目录

即可,点击确定
4、在src目录下创建一个名为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>

<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">

<action name="hello">
<result>
/Hello.jsp
</result>
</action>
</package>
<!-- Add packages here -->

</struts>

5、将struts2所需的包存放到WebRoot/WEB-INF/lib目录里

6、修改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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

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

7、创建Hello.jsp文件,如下

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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>HelloStruts2</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>
This is my first Struts Application! <br>
</body>
</html>

8、启动tomcat,运行结果如下



9、设置提示struts API的功能

首先是找到E:/JavaJars/struts2.1目录下的struts2-core-2.1.6.jar文件,解压文件,里面会有个struts-2.1.dtd

打开Window-Preferences-在文本框中输入catalog,点击Add-选择Key type为URI,Key值为http://struts.apache.org/dtds/struts-2.1.dtd,找到E:/JavaJars/struts2.1/struts2-core-2.1.6/struts-2.1.dtd文件,确定即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: