Friday 1 August 2014

getRealPath (String path)

public String getRealPath(String path)
getRealPath method declared in ServletContext interface. The getRealPath method takes a String argument and returns a String representation of a file on the local file system to which a path corresponds.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="get" action="/servlet/GetRealPath">
            <input type="submit">
        </form>
    </body>
</html>

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>GetRealPath</servlet-name>
        <servlet-class>GetRealPath</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>GetRealPath</servlet-name>
        <url-pattern>/GetRealPath</url-pattern>
    </servlet-mapping>
</web-app>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetRealPath extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
       try(PrintWriter out = res.getWriter()) {
            res.setContentType("text/html");
            ServletContext context = req.getServletContext();
            String realPath = context.getRealPath("main.jsp");
            
            String str = "<html>" +
                         "<head>" +
                         "<title> Hello World </title>" +
                         "</head>" +
                         "<body>" +
                         "<h1>  <br />" + realPath +
                         "</h1> </body>" +
                         "</html>";
            out.println(str);
       }
   } 
}



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment