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
网友评论