標籤:調用 訪問 sub 需要 ret context servlet files 解析
- 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間接
- * 擷取,問題解決
- * */
- 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;
- }
練習上傳下載時遇到的問題