美文网首页Servlet实例专题
在Servlet中获取Web路径和真实路径

在Servlet中获取Web路径和真实路径

作者: 神坛下的我 | 来源:发表于2018-08-21 09:58 被阅读0次

    UseServlet.java

    @WebServlet("/user.do")
    public class UseServlet extends HttpServlet{
    
        private static final long serialVersionUID = 1L;
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            //设置字符集格式为utf-8
            //req.setCharacterEncoding("UTF-8");
            String scheme=req.getScheme();//获取请求协议http
            String serverName=req.getServerName();//获取服务器名称localhost
            int serverPort = req.getServerPort();
            String contextPath=req.getContextPath();//返回Web应用的URL入口
            String path=scheme+"://"+serverName+":"+serverPort+"/"+contextPath+"/";
            //getRealPath返回一个给定虚拟路径的真实路径
            String realPath=this.getServletContext().getRealPath("index.jsp");
            req.setAttribute("path", path);
            req.setAttribute("realPath", realPath);
            
            req.getRequestDispatcher("index.jsp").forward(req, resp);
            
        }
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            doPost(req, resp);
        }
    }
    
    

    index.jsp

    <form action="user.do" method="post">
            <table align="center">
                <tr>
                    <td>Web路径:</td>
                    <td><%=(String)request.getAttribute("path") %></td>
                </tr>
                <tr>
                    <td>真实路径:</td>
                    <td><%=(String)request.getAttribute("realPath") %></td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                    <input type="submit" value="获取路径"/>
                    <input type="reset" value="重置"/>
                    </td>
                </tr>
            </table>
        </form>
    
    26.PNG

    相关文章

      网友评论

        本文标题:在Servlet中获取Web路径和真实路径

        本文链接:https://www.haomeiwen.com/subject/bwrdiftx.html