package cn.itcast.tool.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作为其他类的父类
* 简单实现类似于struts2的作用
* @author Administrator
*
*/
public class BaseServlet extends HttpServlet {
private static final long serialVersionUID = -9085388180868618165L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse rsponse)
throws ServletException, IOException {
if(request.getMethod().equalsIgnoreCase("post")){
request.setCharacterEncoding("utf-8");
}else if(request.getMethod().equalsIgnoreCase("get")){
request = new GetRequest(request);
}
rsponse.setContentType("text/html;charset=utf-8");
String methodName=request.getParameter("action");
Method method=null;
//System.out.println(this.getClass().getName());
try {
method=this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("您要调用的方法'"+methodName+"'它不存在!");
}
try {
String result=(String) method.invoke(this, request,rsponse);
if(result!=null && !result.trim().isEmpty()){
String[] strs=result.split(":");
if(strs.length==1){
request.getRequestDispatcher(strs[0]).forward(request, rsponse);
}else if(strs.length==2){
if(strs[0].equals("f")){
request.getRequestDispatcher(strs[1]).forward(request, rsponse);
}else if(strs[0].equals("r")){
rsponse.sendRedirect(request.getContextPath()+strs[1]);
}else{
throw new RuntimeException("本公司暂未开发此服务!");
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package cn.itcast.tool.servlet;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class GetRequest extends HttpServletRequestWrapper{
public GetRequest(HttpServletRequest request) {
super(request);
}
@Override
public String getParameter(String name) {
String value=super.getParameter(name);
try {
if(value==null) return null;
return new String(value.getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings({ "rawtypes", "unused","unchecked" })
@Override
public Map getParameterMap() {
Map<String,String[]> map=new HashMap<String,String[]>(super.getParameterMap());
if(map==null) return null;
for(String name:map.keySet()){
String[] values=map.get(name);
for(int i=0;i<values.length;i++){
try {
values[0]=new String(values[0].getBytes("iso-8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
map.put(name, values);
}
return map;
}
}