- public class BaseServlet extends HttpServlet {
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
- //页面的编码处理
- req.setCharacterEncoding("utf-8");
- res.setContentType("text/html;charset=utf-8");
- //获取页面要调用的method参数
- String methodName = req.getParameter("method");
- if(methodName==null || methodName.trim().isEmpty()){
- throw new RuntimeException("您未指定要调用的方法!");
- }
- //反射得到要调用的反射方法
- Class clazz = this.getClass();//所访问servlet的字节码文件对象
- Method method = null;
- try {
- method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
- }
- catch (Exception e) {
- throw new RuntimeException("您要调用的方法"+methodName+"(HttpServletRequest,HttpServletResponse)不存在");
- }
- //执行方法
- try {
- String result = (String)method.invoke(this, req,res);
- if(result==null || result.trim().isEmpty()){
- return;
- }
- if(result.contains(":")){
- int addr = result.indexOf(":");
- String bef = result.substring(0,addr);
- String aft = result.substring(addr+1);
- if(bef.equalsIgnoreCase("r")){
- res.sendRedirect(req.getContextPath()+aft);
- }else if(bef.equalsIgnoreCase("f")){
- req.getRequestDispatcher(aft).forward(req, res);
- }else{
- throw new RuntimeException("您指定的操作有误");
- }
- }else{
- req.getRequestDispatcher(result).forward(req, res);
- }
- } catch (Exception e) {
- throw new RuntimeException("方法内部错误"+e);
- }
- }
- public class MyFileServlet extends BaseServlet {
- MyService service = new MyService();
- public String findAll(HttpServletRequest req,HttpServletResponse res){
- List<MyFile> list = service.findAll();
- req.setAttribute("list", list);
- return "f:/day22/list.jsp";
- }
- public String downLoad(HttpServletRequest req,HttpServletResponse res) {
- String fid = req.getParameter("fid");
- MyFile myfile = service.load(fid);
- try {
- //获取文件资源名称
- String path = req.getParameter("path");
- //解析路径
- String fname = myfile.getFilename();
- String name = myfile.getName();
- name = new String(name.getBytes("iso-8859-1"),"utf-8");
- //封装文件
- File file = new File(path,fname);
- if(!file.exists()){
- req.setAttribute("msg", "您要下载的资源不存在");
- return "f:/day22/msg.jsp";
- }
- int cnt = myfile.getCnt();
- /*
- 其中MyFile 类型的cnt属性是Integer的int cnt = myfile.getCnt();
- * myfile.setCnt(cnt+1);
- * service.edit(myfile);
- * 加入此句后会报出 方法内部错误
- * java.lang.reflect.
- * InvocationTargetException
- * 后来将接口参数由myfile对象换成两个
- * 需要的直接参数,而不是由myfile间接
- * 获取,问题解决,仔细思考之后发现其实是反射方法的
- 内部出了问题,也就是说baseservlet反射调用了我的这个
- 方法,而我这个方法内部有可能在处理或调用其他方法时出现问题
- * */
- service.edit(cnt+1,fid);
- name = new String(name.getBytes("GBK"),"iso-8859-1");
- res.addHeader("content-disposition", "attatchment;filename="+fname);
- IOUtils.copy(new FileInputStream(file), res.getOutputStream());
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- return null;
- }