hyy9512

导航

文件1. 查看文件是否存在

通过servlet判断本机中是否含有所给的文件路径。

.jsp界面

 1   <form action="<%=basePath %>fileAction" method="get" >
 2         <table>
 3             <tr>
 4                 <td>输入文件路径</td>
 5                 <td><input type="text" name="filePath" /></td>
 6             </tr>
 7             <tr>
 8                 <td colspan="2">
 9                    <input type="submit" value="查找"/>
10                 </td>
11             </tr>
12             <tr>
13                 <td colspan="2">
14                    <input type="hidden" name="method" value="file"/>
15                 </td>
16             </tr>
17         </table>
18     </form>                    

servlet层中FileAction.java代码

 1 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
 2             throws ServletException, IOException {
 3         req.setCharacterEncoding("utf-8");
 4         resp.setCharacterEncoding("utf-8");
 5         resp.setContentType("text/html;charset=utf-8");
 6         PrintWriter out=resp.getWriter();
 7         String method=req.getParameter("method");
 8         
 9         if(method.equals("file")) {
10             
11 //对文件进行操作
12             
13             
14     /*
15      * 判断文件是否存在
16      */
17 //          1. 获取请求中的文件路径(get方式,获得表单中的含有中文的值,方式如下)
18 //                    若是英文,则直接用req.getParameter("name");
19             String filePath=new String(req.getParameter("filePath").getBytes("iso8859-1"),"utf-8");
20 //          2. 根据路径定义相应的文件
21             File file=new File(filePath);
22 //          3. 使用exists();函数,判断生成的文件是否存在
23             boolean bool=file.exists();
24             if(bool==true) {
25          out.write("<script>alert('文件存在!');</script>");
26        }else {
27          out.write("<script>alert('文件不存在!');</script>");
28        }
    }

web.xml配置

1 <servlet>
2       <servlet-name>fileAction</servlet-name>
3       <servlet-class>servlet.FileAction</servlet-class>
4   </servlet>
5   <servlet-mapping>
6       <servlet-name>fileAction</servlet-name>
7       <url-pattern>/fileAction</url-pattern>
8   </servlet-mapping>

 

posted on 2017-12-16 15:10  hyy9512  阅读(211)  评论(0编辑  收藏  举报