Java Web学习(31): Servlet学习(四)

Servlet路径

绝对路径:一个资源的完整路径;

相对路径:相对于当前资源的路径;

在进行路径说明的时候首先声明一点,如果新建的项目工程中带有WebRoot目录,那么js、css、img都应该放

到WebRoot目录下,否则访问会有问题。千万不要放在WEB-INF下,因为WEB-INF下的内容只有服务器转发可以访

问到,处于安全考虑;如果新建的项目工程中不带有WebRoot目录,那么可以放在WEB-INF外面建立的文件夹中。

那么使用Eclipse创建的Web工程项目是下面的目录结构:

JSP中的路径问题

在JSP页面中加入basePath:

<%
  //获取项目名
  String path = request.getContextPath();
  /* http://localhost:8080/项目名/ */
  String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

在JSP页面中的<head>标签中加入:

<!-- 相当于所有的href相对路径前面都加入了:http://localhost:8000/项目名/ -->
<base href="<%=basePath%>">

创建一个PathServlet

package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class PathServlet
 */
@WebServlet(name="PathServlet" ,urlPatterns={"/PathServlet"})
public class PathServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PathServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print("<h1>Hello PathServlet!</h1>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

创建一个default.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
      //获取项目名
      String path = request.getContextPath();
      /* http://localhost:8080/项目名/ */
      String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- 相当于所有的href相对路径前面都加入了:http://localhost:8000/项目名/ -->
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Servlet</title>
</head>
<body>
       <h1>Servlet路径问题</h1>
       <hr/>
       <%-- href属性中隐含了basePath,因为<base href="<%=basePath%>"> --%>
       <!-- 使用相对路径访问PathServlet -->
       <a href="PathServlet">get方式请求PathServlet</a>    
</body>
</html>

运行结果:

跳转的路径:http://localhost:8080/ServletDemo1/PathServlet

修改default.jsp页面:

运行结果:

跳转的路径:http://localhost:8080/PathServlet

因为在JSP页面中第一个斜线表示服务器的根目录,也就是http://localhost:8080/,所以会报404错误,因此找

不到路径。

继续修改default.jsp页面:

运行结果:

跳转的路径:http://localhost:8080/ServletDemo1/PathServlet

request.getContextPath()得到的是项目的根目录,同样表单中的action属性的URL地址的写法与超链接相同。

注解中的路径问题

注解中的路径也就是我们通常所说的web.xml配置文件中的<url-pattern></url-pattern>标签之间的路径问

题。只不过是Servlet3.0更简单了。

我们上面的例子中的注解为:

@WebServlet(name="PathServlet" ,urlPatterns={"/PathServlet"})

注解中的urlPatterns中的第一个斜线表示项目的根目录,如果不加会报很严重的错误。这里需要我们小心谨慎一

定不要忘了加。Servlet3.0以下的版本只能在web.xml中配置,同样是小心。

Servlet中的路径问题

新建一个test.jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
      //获取项目名
      String path = request.getContextPath();
      /* http://localhost:8080/项目名/ */
      String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- 相当于所有的href相对路径前面都加入了:http://localhost:8000/项目名/ -->
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>跳转页面</title>
</head>
<body>
     <h1>我是test.jsp页面!</h1>
</body>
</html>

继续修改default.jsp页面代码:

新建的TestServlet:

package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet(name="TestServlet" ,urlPatterns={"/TestServlet"})
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//使用请求重定向方式跳转到test.jsp页面
		/*
		 * 请求重定向,将方法中的地址参数传递给浏览器,让浏览器重新发送请求,
		 * "/"代表(相对于)服务器根目录http://localhost:8000/
		 * 所以相当于浏览器重新请求了绝对路径http://localhost:8000/项目名/test.jsp
        */
		//使用request.getContextPath()获取项目名
		response.sendRedirect(request.getContextPath() +"/test.jsp");
		//response.sendRedirect("/test.jsp");//错误的
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

运行结果:

跳转路径为:http://localhost:8080/ServletDemo1/test.jsp

修改TestServlet:

运行结果:

跳转路径为:http://localhost:8080/ServletDemo1/TestServlet

因此我们推荐使用的是:

*************************************************************************************

请求重定向

response.sendRedirect(request.getContextPath() +"/test.jsp");

服务器内部转发

request.getRequestDispatcher("/test.jsp").forward(request.response)

*************************************************************************************

推荐的关于路径问题的博文:

http://blog.csdn.net/app19830306/article/details/8510545

时间: 2024-07-29 03:29:04

Java Web学习(31): Servlet学习(四)的相关文章

JavaWeb学习之Servlet(四)----ServletConfig获取配置信息、ServletContext的应用(转)

JavaWeb学习之Servlet(四)----ServletConfig获取配置信息.ServletContext的应用 [声明] 欢迎转载,但请保留文章原始出处→_→ 文章来源:http://www.cnblogs.com/smyhvae/p/4140877.html [正文] 一.ServletConfig:代表当前Servlet在web.xml中的配置信息(用的不多) String getServletName()  -- 获取当前Servlet在web.xml中配置的名字 String

java web.xml listener servlet 和filter的加载顺序

在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是,加载顺序与它们在 web.xml 文件中的先后顺序无关.即不会因为 filter 写在 listener 的前面而会先加载 filter. 最终得出的结论是:listener -> filter -> servlet 同时还存在着这样一种配置节:context-param,它用于向 Servle

java web (j2ee)学习路线 —— 将青春交给命运

RESON TO DO JAVA WEB:1.JAVA WEB(企业级)  2.Android和iOS过于火爆并且不兼容 一.JAVA WEB开发需要的知识储备 1.      基本的网页设计语言:HTML.JavaScript.CSS 2.      制作动态网站:Java.JSP(servelt) 3.      数据库:MySQL.SQL Server.SQL Lite.Access.Oracle 4.      流行的框架:MVC思想和原理——了解Struts.Spring.Hibern

Java Web:使用Servlet生成网页随机图片验证码

最近在学习Java Web开发,做了一个生成网页随机图片验证码的例子,在此记录. 一.新建Servlet项目: 在MyEclipse中新建Servlet项目,一步步操作就OK,在此不再赘述.建好之后文件目录树如下图: 二.源代码实现: (1)java代码: package com.zdt.identity; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.

Gradle构建Java Web应用:Servlet依赖与Tomcat插件(转)

Gradle的官方tutorial介绍了构建Java Web应用的基本方法.不过在使用Servlet做上传的时候会碰到问题.这里分享下如何通过Servlet上传文件,以及如何使用Gradle来构建相应的Java Web工程. 参考原文:How to Build Web Scanning Application with Gradle Servlet文件上传 使用Servlet文件上传,可以参考Oracle的官方文档The fileupload Example Application.这里需要注意

Java Web开发之Servlet、JSP基础

有好多年不搞Java Web开发了,这几天正好国庆放假,放松之余也有兴趣回头看看Java Web开发技术的基础. 我们都知道,Servlet是Java Web开发的重要基础,但是由于Servlet开发相对繁琐,代码量庞大而且不易维护,美工无法参与界面设计开发等不足,于是就诞生了jsp.jsp是对servlet开发模型的重要升级.有了jsp,Java Web开发技术才真正被广泛使用. 一.Servlet 在Java Web开发当中,新建一个类继承(派生)自HttpServlet类即可创建一个Ser

Gradle构建Java Web应用:Servlet依赖与Tomcat插件

Gradle的官方tutorial介绍了构建Java Web应用的基本方法.不过在使用Servlet做上传的时候会碰到问题.这里分享下如何通过Servlet上传文件,以及如何使用Gradle来构建相应的Java Web工程. 参考原文:How to Build Web Scanning Application with Gradle Servlet文件上传 使用Servlet文件上传,可以参考Oracle的官方文档The fileupload Example Application.这里需要注意

Java web 实验五 Servlet过滤器

loginform.html <html> <head> <title>使用过滤器改变请求编码</title> <meta http-equiv="Content-Type" content="text/html;charset=GB2312"> </head> <body> <center> <h2>请输入用户名和口令:</h2> <for

JavaWeb学习之Servlet(四)----ServletConfig获取配置信息、ServletContext的应用

[声明] 欢迎转载,但请保留文章原始出处→_→ 文章来源:http://www.cnblogs.com/smyhvae/p/4140877.html 联系方式:[email protected] [正文] 一.ServletConfig:代表当前Servlet在web.xml中的配置信息(用的不多) String getServletName()  -- 获取当前Servlet在web.xml中配置的名字 String getInitParameter(String name) -- 获取当前S

Java web的一些总结(四:关于servlet)

servlet是干什么的? 这部分内容较为底层,可能在使用spring框架后不一定要手写,但作为基础,有必要好好了解下. 是sun公司开发的,目的是开发动态web 具体使用时是:在API中为我们提供了一个接口(我们一般实现HTTPServlet接口),我们需要编写一个类来实现该接口,并在这个类中处理request和response即可. servlet运行原理 在浏览器中输入请求地址后,浏览器会依据IP地址及端口号找到对应的Web服务器,如果请求的是静态资源,Web服务器直接提供响应:如果请求的