泛型编程实例之(二)
基本泛型类:
public abstract class SessionServiceBase<T> {
public abstract String getStringFromEntry(T entry);
/**
* 存储介质的存储string,比如cookie里、threadlocal里等
*
* @param value
* @param seconds
*/
public abstract void setString(String value, int seconds);
public void set(T entry) {
// 写入cookie
set(entry, 3600 * 24 * 30); // 默认30天
}
public final void set(T entry, int seconds) {
String value = getStringFromEntryInternal(entry);
setString(value, seconds);
}
String getStringFromEntryInternal(T entry) {
String s = getStringFromEntry(entry);
return StringUtil.signContent(s, getSalt());
}
}
抽象泛型类的实现类:
public class CookieSessionService extends SessionServiceBase<User> {
private tools.web.CookieUtil cookie = null;
。。。
@Override
public void setString(String arg0, int arg1) {
try {
cookie.set(name, URLEncoder.encode(arg0, ENCODING), domain, null,
arg1);
} catch (UnsupportedEncodingException e) {
}
}
}
调用它的类:
public class Request extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
long startTime = System.currentTimeMillis();
request.setCharacterEncoding("GBK");
String action = request.getParameter("action");
....
if ("auth".equalsIgnoreCase(action)) {
auth(request, response);
return;
....
private void auth(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
CookieSessionService cs = CookieSessionService.create(request,
response, "auth", null);
User u = new User();
u.setUserId(0);
u.setUserName(name);
u.setData(request.getParameter("data"));
cs.set(u);
}
}