在學習SSH框架之前,首先需要熟悉servlet,然後再去替代它。
Struts:
教程:
part1 基礎配置
首先去官網下載Struts,下載這個大小爲65MB的
壓縮後,就可以將其中的lib中的jar導入了,其實不用全部導入,常見的jar包如下:
然後就是編寫代碼了,
首先去web.xml配置filter,加入以下配置,這個filter配置是第一步,但是目前以我短淺的學習暫時不能說出它的作用
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
接着,假設我們有一個html頁面了,頁面裏有一個表單,表單的action屬性跳轉到一個鏈接,這個添加填上myAction,於是我們再建一個java類,名字就是myAction, extends ActionSupport,然後實現excute方法,該方法返回String值,和struts.xml中相對應。當然,光是編寫了一個myAction的類是不能將表單的鏈接和類關聯起來的,還需要struts.xml文件,其實如果熟悉servlet的xml配置,原理都差不多
html界面的表單寫法
<form action="<%=request.getContextPath() %>/loginAction" method = "post">
用戶名:<input type = "text" name = "userName"/><br/>
密碼:<input type="password" name = "password"/><br/>
<input type="submit" value="登錄"/>
struts.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 配置包名,便於區分 namespace直譯是命名空間,作用是綁定url前綴,即在訪問頁面時該加什麼前綴 -->
<package name="mypackage" extends="struts-default" namespace="/">
<!-- action的名字 對應哪一個類 method屬性指定調用類中的哪個方法處理 -->
<action name="loginAction" class="com.bowen.controller.MyAction" method="excute">
<!--配置方法的返回值-->
<result name="success">/index.jsp</result>
<result name = "fail">/login.jsp</result>
</action>
</package>
</struts>
對於該配置文件中的result標籤,它的name與你編寫的excute方法的返回值相對應,標籤內部指定跳轉的地址
result標籤還可以指定跳轉類型,比如重定向,或者再跳轉到一個action:
<result name="success" type="redirect">/index.jsp</result>
<result name = "fail" type="chain">action2</result>
之前用過servlet都知道,解決中文亂碼要加上幾句話,而struts中則是在web.xml配置文件中加入
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
part 2 參數傳遞問題
在傳統的servlet中我們採用request和response傳遞參數,但是struts2如果想用同樣的方式傳遞參數,可以:
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse resp = ServletActionContext.getResponse();
獲取request和response,再getAttribute,但實際上還有其他方式
我們一般使用ModelDriven接口,在編寫的action類裏繼承ModelDriven,然後實現getModel方法,具體的可以參考下面的網址,畢竟我也是初學者,沒有別人講的好,而modelDriven背後的機制又特別迷惑,目前我只能停留在應用的階層。
https://blog.csdn.net/weixin_39220472/article/details/80296890
此外,我們還需要request,response等對象,而在struts中,所有的這些對象都被集中在ActionContext中,你想要的對象它應有盡有,可以這樣獲得一個想要的對象
Map<String, Object> session = ActionContext.getContext().getSession();
可以看出它就是一個Map,可以通過put的方法來存值
session.put("name", "Tom");
之後就是ognl表達式和struts標籤了,和jstl表達式類似,但是又不一樣
https://www.cnblogs.com/mingforyou/p/4483945.html
上面的博客可以快速入門,如何使用struts標籤,將它和jstl做了比較