Struts2 学习笔记的第一篇:环境搭建及HelloWorld的实现。
1、搭建Struts2 的环境。在Myeclipse里新建一个WEB工程,我起名为:Struts2_01。由于要用到一些Struts的类库,这里我新建了一个用户定义的类库文件:struts,并引入相应的jar包。具体步骤不详细说了。
2、配置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>indx.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>
对于具体的内容可以到struts目录下的文件夹下copy一份,自己修改。这里面主要是设置了一个过滤器,过滤所有的URL请求。
3、配置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.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <default-action-ref name="index" > </default-action-ref> <action name="index" class="com.xiyang.Action.Hello"> <result>/index.jsp</result> </action> </package> <!-- Add packages here --> </struts>
这个文件也是copy过来的,注意修改devMode为true,即打开开发模式。在这个文件里面定义了一个action,要设定相应的类目录:com.xiyang.Action.Hello,所以需要新建一个类文件,位于com.xiyang.Action这个包下面,Action实现一般是继承自ActionSupport,然后重写里面的execute方法。当然针对于这个项目,我并没有改变里面的内容。
package com.xiyang.Action;
import com.opensymphony.xwork2.ActionSupport;
public class Hello extends ActionSupport{
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return super.execute();
}
}
然后可以建立index.jsp文件,使之显示Hello World!。
4.将写好的项目,部署到Tomcat服务器上。然后打开浏览器输入地址:http://localhost:8080/Struts2_01/,如果不出意外的话你就能够看到HelloWold了。
注意问题:struts.xml不自动提示。
解决方案:
1.window – preferences – 搜索 catalog – add
2.选择key type为URI
3.key: http://struts.apache.org/dtds/struts-2.0.dtd
4.location: 对应的dtd文件,位于struts-core包中,解压开,指定相应位置,如:D:\struts-2.1.6\lib\struts2-core-2.1.6\struts-2.0.dtd