学习笔记归纳 2010-9-5.1-9

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;

}

}

你可能感兴趣的:(apache,时间,职场,学习笔记,休闲)