您的位置:首页 > 编程语言 > Java开发

JavaEE-1-JavaWeb项目的部分思考总结

2015-03-21 09:15 232 查看
一、说明

本文没有Struts2、Hibernate、Spring,但本文有自己封装的一个BaseServlet(使用Java动态代理)、自己写的DAO工具TxQueryRunner(借助Apache commons dbutils包)、自己模拟的Spring框架(使用Java反射)。

另,为了解决GET请求乱码问题,封装类GetRequest(装饰者模式的具体体现);再附上一个类CommonUtils(实现将Map集合封装到指定类中)。

二、依赖jar包

commons-beanutils-1.8.3.jar

commons-dbutils-1.4.jar

三、代码实现

3.1.1、BaseServlet

package cn.yjx.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* BaseServlet用来作为其它Servlet的父类
* 一个类多个请求处理方法,每个请求处理方法的原型与service相同! 原型 = 返回值类型 + 方法名称 + 参数列表
*/
public class BaseServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(request.getMethod().equalsIgnoreCase("get")) {
request = new GetRequest(request); // 处理get请求编码
} else {
request.setCharacterEncoding("utf-8"); // 处理post请求编码
}
response.setContentType("text/html;charset=UTF-8");//处理响应编码

/**
* 1. 获取method参数,它是用户想调用的方法 2. 把方法名称变成Method类的实例对象 3. 通过invoke()来调用这个方法
*/
String methodName = request.getParameter("method");
System.out.println("--实际运行的request类 :" + request.getClass().getName());
Method method = null;
/**
* 2. 通过方法名称获取Method对象
*/
try {
method = this.getClass().getMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("要调用的方法:" + methodName + "不存在", e);
}

/**
* 3. 通过method对象来调用它
*/
try {
String result = (String)method.invoke(this, request, response);
if(result != null && !result.trim().isEmpty()) {
String[] strs = result.split(":");
if(strs[0].equals("f")) {
request.getRequestDispatcher(strs[1]).forward(request, response);
} else if(strs[0].equals("r")) {
response.sendRedirect(request.getContextPath() + strs[1]);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}


3.1.2、测试BaseServlet

package cn.yjx.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServletTest extends BaseServlet {
public String add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("add()...");
System.out.println("name: " + request.getParameter("username"));
return "f:/index.jsp";
}
public String update(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("update()...");
return "r:/index.jsp";
}
}


3.4、GetRequest

package cn.yjx.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

/**
* 对GET请求参数加以处理
*/
public class GetRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;

public GetRequest(HttpServletRequest request) {
super(request);
this.request = request;
}

@Override
public String getParameter(String name) {
// 获取参数
String value = request.getParameter(name);
if(value == null) return null;//如果为null,直接返回null
try {
// 对参数进行编码处理后返回
return new String(value.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}

@Override
public Map getParameterMap() {
Map<String,String[]> map = request.getParameterMap();
if(map == null) return map;
// 遍历map,对每个值进行编码处理
for(String key : map.keySet()) {
String[] values = map.get(key);
for(int i = 0; i < values.length; i++) {
try {
values[i] = new String(values[i].getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
map.put(key, values);
}
return map;
}
}
3.5.1、CommonUtils

package cn.yjx.commons;

import java.util.Map;
import java.util.UUID;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

public class CommonUtils {

public static String uuid() {
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}

/**
* 把Map转换成指定类型对象
*/
@SuppressWarnings("rawtypes")
public static <T> T toBean(Map map, Class<T> clazz) {
try {
/*
* 1. 通过参数clazz创建实例
* 2. 使用BeanUtils.populate把map的数据封闭到bean中
*/
T bean = clazz.newInstance();
ConvertUtils.register(new DateConverter(), java.util.Date.class);
BeanUtils.populate(bean, map);
return bean;
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
3.5.2、DateConverter
package cn.yjx.commons;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.Converter;

/**
* 把String转换成java.util.Date的类型转换器
*/
public class DateConverter implements Converter {

@Override
public Object convert(Class type, Object value) {
if(value == null) return null;
if(!(value instanceof String)) {
return value;
}
String val = (String) value;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date r = sdf.parse(val);
System.out.println("r: " + r);
return r;
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
3.5.3、测试CommonUtils
@Test
public void fun2(){
Map<String,String> map = new HashMap<String,String>();

map.put("username", "张三");
map.put("password", "123");
map.put("age", "55");
map.put("birthday", "2015-02-28");

User user = CommonUtils.toBean(map, User.class);
System.out.println(user);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: