1.
import org.apache.commons.beanutils.BeanUtils;
//將頁面表單提交來的數據注入到action中的屬性上。
BeanUtils.populate(action, req.getParameterMap());
處理表單提交過來的數據,但不可以處理時間類型的數據,要特殊處理
2.
import org.apache.commons.beanutils.ConvertUtils;
// 註冊一個類型轉換器
ConvertUtils.register(new DataTypeConvert(), java.util.Date.class);
處理時間數據
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.beanutils.Converter;
public class DataTypeConvert implements Converter {
public Object convert(Class arg0, Object arg1) {
Object value = null;
if (arg0 == java.util.Date.class) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
value = sdf.parse((String) arg1);
} catch (ParseException e) {
e.printStackTrace();
}
}
return value;
}
}
3. 文件上傳和處理文件的編碼方式
//文件上傳 表單所有的數據 又分爲兩塊 一個普通數據 另一個數據爲文件類型的數據
//如果爲普通數據isFormField爲TRUE則做普通數據處理 爲FALSE則作爲文件數據處理
//編碼有三個地方 第一是頁面裏的charset=utf-8 第二是表單提交的enctype="multipart/form-data",application/x-www-form-urlencoded,text/plain
//第三是過濾器的編碼方式request.setCharacterEncoding(encoding);
String contentType = req.getContentType();
if (contentType != null && contentType.startsWith("multipart/form-data")) {
// multipart/form-data文件方式提交數據
doFileUpload(req, action);
ServletFileUpload fileUpload = new ServletFileUpload(
new DiskFileItemFactory());
try {
List<FileItem> list = fileUpload.parseRequest(req);
for (FileItem item : list) {
try {
if (item.isFormField()) {
// 如果爲普通的input表單元素,直接將值注入到Action中
String oldValue = item.getString();
String encoding = req.getCharacterEncoding();
if(encoding == null || encoding.equals("")){
encoding = "utf-8";
}
// 因爲過濾器可能有設置,儘量使用過濾器的編碼方式,如果沒有,使用缺省的編碼方式
String newValue = new String(oldValue
.getBytes("iso8859-1"), encoding);
BeanUtils.copyProperty(action, item.getFieldName(), newValue);
} else {
// 如果是文件類型的輸入框,先判斷是否有文件上傳
if (item.getName() == null || item.getName().equals("")) {
continue;
}
// 如果有文件上傳,把它保存到tomcat的臨時目錄中去。
String fileName = String.format("%s//%s.tmp",
System.getProperty("java.io.tmpdir"),
new Random().nextLong());
File file = new File(fileName);
item.write(file);
// 把臨時目錄的文件對象注入到action中,讓action能對他靈活操作。
BeanUtils.copyProperty(action,
item.getFieldName(),
file);
// 將客戶端的原始文件名也傳遞到action中
BeanUtils.copyProperty(action,
item.getFieldName() + "FileName",
item.getName());
}
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (Exception e) {
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
4. 過濾器 文件編碼過濾器和錄入過濾器
//配置編碼過濾器
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>com.softeem.blog.filter.SetCharacterEncoding</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
public class CharacterEncodingFilter implements Filter {
String encoding;
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)arg0;
request.setCharacterEncoding(encoding);
arg2.doFilter(arg0, arg1); //放行
}
public void init(FilterConfig arg0) throws ServletException {
this.encoding=arg0.getInitParameter("encoding");
}
//配置錄入過濾器
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.softeem.blog.filter.LoginFilter</filter-class>
<init-param>
<param-name>except</param-name>
<param-value>login.jsp,login.action,user_list.action</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
public class LoginFilter implements Filter {
String excepts;
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)arg0;
HttpServletResponse response=(HttpServletResponse)arg1;
//--------URI=/blog/article_list.action
String uri=request.getRequestURI();
String cmd=uri.substring(uri.lastIndexOf("/")+1);
String[] ex=excepts.split(",");
for(String except:ex){
if(except.equalsIgnoreCase(cmd)){
arg2.doFilter(request, response);
return;
}
}
Object obj=request.getSession().getAttribute("USER");
if(obj==null){
response.sendRedirect("login.jsp");
return;
}
arg2.doFilter(request, response); //放行
}
public void init(FilterConfig filterConfig) throws ServletException {
excepts=filterConfig.getInitParameter("except");
}
}
5.
// 讀配置文件struts.xml 在init()方法裏讀
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/struts.xml");
6.用dom4j解析struts.xml
// Map<String, ActionConfig> maps = new HashMap<String, ActionConfig>(); 用來保存解析好的strust.xml裏的值 反射所需要的值
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
SAXReader reader = new SAXReader();
Document document = reader.read(in);
List<Element> actions = document.selectNodes("/struts/package/action");
for(Element element : actions){
String methodName = element.attributeValue("method");
if(StringUtils.isEmpty(methodName)){
methodName="execute";
}
ActionConfig aconfig = new ActionConfig(
element.attributeValue("class"),
methodName,
element.attributeValue("name"));
//// ActionConfig的屬性是
////String className;
////String methodName;
////Map<String, ResultConfig> results = new HashMap<String, ResultConfig>();
////String uriName;
List<Element> results = element.selectNodes("result");
for(Element result : results){
String name = result.attributeValue("name");
if(StringUtils.isEmpty(name)){
name = "success";
}
ResultConfig rconfig = new ResultConfig(
name, result.attributeValue("type"), result.getText());
//// ResultConfig的屬性是
//// String name;
//// String type;
//// String pageUri;
aconfig.getResults().put(name, rconfig);
}
maps.put(element.attributeValue("name"), aconfig);
}
7.我們的action.servlet
// 得到URI,根據URI實例化對應的Action
String cmd = getURI(req);
ActionConfig config = maps.get(cmd);
String clzName = config.getClassName();
String methodName = config.getMethodName();
// 實例化Action
Action action = getAction(clzName);
// 將頁面傳遞過來的值裝配到Action中
formAware(req, action);
// 將session傳遞到action中
doAware(req, resp, action);
// 在action上面調用它的方法
Object resultName = invokeAction(methodName, action);
ResultConfig rConfig = config.getResults().get(resultName);
// 把action裏的所有屬性放置到request中
saveActionProperties(req, action);
// 如果跳轉頁面不爲空,根據跳轉類型調用跳轉方法
String address = rConfig.getPageUri();
if (StringUtils.isNotEmpty(address)) {
if ("forward".equals(rConfig.getType())) {
req.getRequestDispatcher(address).forward(req, resp);
} else {
resp.sendRedirect(address);
}
}
8.需要request的地方可以繼承request的接口 session和response
/**
* 將HttpServletRequest, Httpsession, HttpServletResponse傳遞到action中 如果action
* 沒有實現SessionAware, ResponseAware, RequestAware接口
* 就不將request,response,session注入
*
* @param req HttpServletRequest
* @param response HttpServletResponse
* @param action 需要注入3個變量的Action
*/
private void doAware(HttpServletRequest req, HttpServletResponse response,
Action action) {
/* 實現了SessionAware接口 */
if (action instanceof SessionAware) { // instanceof 判斷a是否是b的實例
SessionAware sa = (SessionAware) action;
sa.setHttpSession(req.getSession());
}
/* 實現了ResponseAware接口 */
if (action instanceof ResponseAware) {
ResponseAware ra = (ResponseAware) action;
ra.setResponse(response);
}
/* 實現了RequestAware接口 */
if (action instanceof RequestAware) {
RequestAware ra = (RequestAware) action;
ra.setRequest(req);
}
}
9.適配器action接口;actionsupport實現action 以後所有要實現action的類就可以繼承actionsupport; action的強制性被解除
public interface Action {
String execute();
}
public class ActionSupport implements Action {
public String execute() {
return null;
}
}