問了我同學現在JavaWeb主流框架是哪些。他說基本框架是SSH,struts2+spring+hibernate,流行的是SSM,springmvc+spring+mybatis,原本計划學下Struts1框架呢,這樣就不學了,先學下Struts2,首先就是eclipse配置Struts2.
一、下載Struts2
從http://struts.apache.org/download.cgi#struts25101下載struts2的包,這里我選的是min的下載的
二、導入Struts2
下載之后解壓,將lib下的所有文件復制到已創建的Struts2項目中。
三、strut2配置
1.在src下創建struts.xml文件,在xml中做如下配置,xml里引入的<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">,這個dtd是用來校驗這個xml的內容格式的,如果缺少節點,會跟dtd里的東西對不上,從而報錯,這里還要注意一下根節點是<struts></struts>,今天配置的時候就忘記加根結點了。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="default" extends="struts-default"> <default-action-ref name="hello" /> <action name="hello"> <result>/hello.jsp</result> </action> </package> </struts>
2.在WEB-INF/web.xml中配置如下,這里filter和filter-mapping是一一對應的,用各自的filter-name對應,我開始配置的時候定義了兩個filter:struts-execute、struts-prepare但只定義了一個filter-mapping:struts-prepare,其實這兩個filter的class是可以和到一起的,使用下面的org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter類。
<filter> <filter-name>struts-prepare</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts-prepare</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3.在WebContext下新建hello.jsp文件,因為在上面的struts.xml中配置的action的result是/hello.jsp。如果hello.jsp放在WEB-INF下,result應該是/WEB-INF/hello.jsp.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="default" extends="struts-default"> <default-action-ref name="hello" /> <action name="hello"> <result>/WEB-INF/hello.jsp</result> </action> </package> </struts>
四、運行
在hello.jsp文件中的body中輸入一行<h2>Hello,Strut2!</h2>。重啟Tomcat,在瀏覽器輸入http://localhost:8088/MyStruts2/hello。
這里要感謝下我的同學也是我大學室友張蒙,這么晚了還幫忙解決問題。