Servlet介绍(7)-----HttpServletRequest、HttpSession、ServletContext、RequestDispatcher

Servlet中的几个对象:

HttpServletRequestHttpSessionServletContext,这三个对象都有

void setAttribute(String name,  Object o)void removeAttribute(String name)

这两个方法,通过这两个方法我们可以很方便的进行参数的传递。

三个对象的作用域的大小分别由小到大。当我们把一个对象通过void setAttribute(String name,  Object o)添加到这三个对象中的时候,除非我们显示的调用void removeAttribute(String name)或者当这三个对象自己销毁否则不会释放这些对象占用的空间,所以我们在将一个对象通过setAttribute添加到这三个对象时,需要注意用完了就remove(当然用完以后这个添加到的对象本身就快销毁时,我们也没必要多此一举)。而且尽量当对象存放在HttpServletRequest,然后才是HttpSession最后才是ServletContext。尽量不要把大对象存放在这些对象中,因为一个进程占用的资源毕竟是有限的。

 

 

Servlet中路径跳转的问题:

   

让我们先通过一个例子来看一下HttpServletRequest的获取路径的一些方法的返回值。

 

ServletPath:

package  squall.servlet.path;

 

import  java.io.IOException;

import  java.io.PrintWriter;

 

import  javax.servlet.ServletException;

import  javax.servlet.http.HttpServlet;

import  javax.servlet.http.HttpServletRequest;

import  javax.servlet.http.HttpServletResponse;

 

 

public   class  ServletPath  extends  HttpServlet

{

 

       
protected void doGet(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              showParam(req,resp);

       }


 

       
protected void doPost(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              showParam(req,resp);

       }


       
private void showParam(HttpServletRequest req, HttpServletResponse resp) throws IOException

       
{

              resp.setContentType(
"text/html");

              PrintWriter out 
= resp.getWriter();

              String docType 
= "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ";

 

              

              out.println(docType 
+ "<HTML> " + "<HEAD><TITLE> pathshow" 

                            
+ "</TITLE></HEAD> " + "<BODY BGCOLOR="#FDF5E6"> "

                            
+"getContextPath():  " + req.getContextPath() + "   </br>"

                            
+"getPathInfo():        " + req.getPathInfo() + "   </br>"

                            
+"getRequestURI():   " + req.getRequestURI()+ "   </br>"

                            
+"getRequestURL():   " + req.getRequestURL()+ "   </br>"

                            
+"getServletPath():   " + req.getServletPath()+ "   </br>"

                            
+"getQueryString():  " + req.getQueryString()+ "   </br>"

                            );

 

          out.println(
"</body></html>");

       }


       

}


 

将此Servlet部署后,mapping<url-pattern>/ServletPath/*</url-pattern>

在浏览器输入http://127.0.0.1:8080/train/ServletPath/a/b/c?name=1&passord=2

可以看到如下输出:

getContextPath(): /train
     getPathInfo(): /a/b/c
     getRequestURI(): /train/ServletPath/a/b/c
     getRequestURL(): http://127.0.0.1:8080/train/ServletPath/a/b/c
     getServletPath(): /ServletPath
     getQueryString(): name=1&passord=2

 

我们可以很清楚的看到各个方法的返回值的情况。

 

     一个html,Servlet,jsp访问另外一个Servlet时候可以通过相对路径(相对于当前的路径),相对于同一Web应用下的路径(比如我们的/train,通过request.getContextPath()获得)和绝对路径(直接http://...)

 

我们一般在Servlet中访问另外一个Servlet或者jsp可以通过Servlet输出中的HTML元素FORM的属性值ACTION来实现。但是我们有时候可以采用一些更加方便的方法。

 

 

 

下面简单的介绍3个方法:

RequestDispatcher

     void forward(ServletRequest request, ServletResponse response)

     void include(ServletRequest request, ServletResponse response)方法。

 HttpResponsevoid sendRedirect(String location)方法。

 

 我们先来介绍HttpResponsevoid sendRedirect(String location)方法。

这个方法将请求一个urllocation的页面, location可以是一个相对路径、相对于当前WEB应用的路径或者直接Http开头的路径,下面让我们看一个例子吧。

BeforeSendRedirect

 

package  squall.servlet.path;

 

import  java.io.IOException;

import  java.io.PrintWriter;

 

import  javax.servlet.ServletException;

import  javax.servlet.http.HttpServlet;

import  javax.servlet.http.HttpServletRequest;

import  javax.servlet.http.HttpServletResponse;

 

public   class  BeforeSendRedirect  extends  HttpServlet

{

 

       
protected void doGet(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              resp.setContentType(
"text/html");

              PrintWriter out 
= resp.getWriter();

              String docType 
= "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ";

              req.setAttribute(
"canyousee""this");

              

              out.println(docType 
+ "<HTML> " + "<HEAD><TITLE> BeforeSendRedirect" 

                            
+ "</TITLE></HEAD> " + "<BODY BGCOLOR="#FDF5E6"> "

                            
+"     <h1>BeforeSendRedirect</h1>    </br>"

                            );

                 out.println(
"</body></html>"); 

              resp.sendRedirect(
"AfterSendRedirect");

       

         System.err.println(
"canyousee " + req.getAttribute("canyousee"+ " in BeforeSendRedirect");

         System.err.println(
"end in BeforeSendRedirect");

       }


 

       
protected void doPost(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              doGet(req,resp);

       }


       

}


 

 

AfterSendRedirect

 

package  squall.servlet.path;

 

import  java.io.IOException;

import  java.io.PrintWriter;

 

import  javax.servlet.ServletException;

import  javax.servlet.http.HttpServlet;

import  javax.servlet.http.HttpServletRequest;

import  javax.servlet.http.HttpServletResponse;

 

public   class  AfterSendRedirect  extends  HttpServlet

{

       
protected void doGet(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              System.err.println(
"begin AfterSendRedirect!");

              resp.setContentType(
"text/html");

              PrintWriter out 
= resp.getWriter();

              String docType 
= "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ";

              

              out.println(docType 
+ "<HTML> " + "<HEAD><TITLE> AfterSendRedirect"

                            
+ "</TITLE></HEAD> " + "<BODY BGCOLOR="#FDF5E6"> "

                            
+ "     <h1>AfterSendRedirect</h1>    </br>");

              out.println(
"</body></html>");

              System.err.println(
"canyousee " + req.getAttribute("canyousee"+ " in AfterSendRedirect");

       }


 

       
protected void doPost(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              doGet(req, resp);

       }


}


 

 

BeforeSendRedirect mapping<url-pattern>/BeforeSendRedirect</url-pattern>

BeforeSendRedirect mapping<url-pattern>/AfterSendRedirect</url-pattern>

然后我们访问http://127.0.0.1:8080/train/BeforeSendRedirect ,可以看到页面跳转到http://127.0.0.1:8080/train/AfterSendRedirect,并且页面上显示的内容也是

AfterSendRedirect

并且tomcat控制台输出为:

canyousee this in BeforeSendRedirect

end in BeforeSendRedirect

begin AfterSendRedirect

canyousee null in AfterSendRedirect

 

可以看出使用HttpResponsevoid sendRedirect(String location)方法

1、             html页面会显示location所输出的页面

2、            浏览器上的url也为location的绝对路径

3、            servlet调用void sendRedirect(String location)方法后,剩下的代码也会执行

4、            servlet和跳转至的servletHttpServletRequest对象不是同一个对象。

 

下面该是

RequestDispatcher

     void forward(ServletRequest request, ServletResponse response)

     void include(ServletRequest request, ServletResponse response)方法的介绍。

       在这之前,我们先来看下javax.servlet.RequestDispatcher对象的获得方法。

获得这个对象的方法,存在于3个类或者接口中分别是ServletContextServletRequestServletRequestWrapper。这里我们只看ServletContextServletRequest

ServletContextServletRequest中获取RequestDispatcher都是通过方法RequestDispatcher getRequestDispatcher(String path),但是需要注意这个方法在用不同的类调用的时候存在一些差异,使用ServletContext接口的对象调用时,String path的参数必须以”/”开头,也就是说从这个web项目的根开始。而使用ServletRequest接口的对象调用这个方法时,path可以不以”/”开头,简单的说就是可以使用相对于当前请求的相对路径。

下面我们先来看RequestDispatchervoid forward(ServletRequest request, ServletResponse response)方法,按照惯例,我们还是用例子来说明问题。

 

BeforeForward

package  squall.servlet.path;

 

import  java.io.IOException;

import  java.io.PrintWriter;

import  javax.servlet.RequestDispatcher;

import  javax.servlet.ServletException;

import  javax.servlet.http.HttpServlet;

import  javax.servlet.http.HttpServletRequest;

import  javax.servlet.http.HttpServletResponse;

 

public   class  BeforeForward  extends  HttpServlet

{

       
protected void doGet(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              resp.setContentType(
"text/html");

              PrintWriter out 
= resp.getWriter();

              String docType 
= "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ";

              req.setAttribute(
"canyousee""this");

 

              out.println(docType 
+ "<HTML> " + "<HEAD><TITLE> BeforeForward"

                            
+ "</TITLE></HEAD> " + "<BODY BGCOLOR="#FDF5E6"> "

                            
+ "     <h1>BeforeForward</h1>    </br>");

              out.println(
"</body></html>");

              RequestDispatcher rd 
= this.getServletContext().getRequestDispatcher("/AfterForward");

              System.err.println(
"canyousee " + req.getAttribute("canyousee")

                            
+ " in BeforeForward");

              rd.forward(req, resp);

 

              System.err.println(
"end in BeforeForward");

       }


 

       
protected void doPost(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              doGet(req, resp);

       }


}


 

 

AfterForward

 

package  squall.servlet.path;

 

import  java.io.IOException;

import  java.io.PrintWriter;

 

import  javax.servlet.ServletException;

import  javax.servlet.http.HttpServlet;

import  javax.servlet.http.HttpServletRequest;

import  javax.servlet.http.HttpServletResponse;

 

public   class  AfterForward  extends  HttpServlet

{

       
protected void doGet(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              System.err.println(
"begin AfterForward!");

              resp.setContentType(
"text/html");

              PrintWriter out 
= resp.getWriter();

              String docType 
= "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ";

 

              out.println(docType 
+ "<HTML> " + "<HEAD><TITLE> AfterForward"

                            
+ "</TITLE></HEAD> " + "<BODY BGCOLOR="#FDF5E6"> "

                            
+ "     <h1>AfterForward</h1>    </br>");

              out.println(
"</body></html>");

              System.err.println(
"canyousee " + req.getAttribute("canyousee")

                            
+ " in AfterForward");

       }


 

       
protected void doPost(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              doGet(req, resp);

       }


}


 

BeforeForwardAfterForward分别mapping<url-pattern>/BeforeForward</url-pattern><url-pattern>/AfterForward</url-pattern>

 

可以看到控制台输出如下:

canyousee this in BeforeForward

begin AfterForward!

canyousee this in AfterForward

end in BeforeForward

 

浏览器上显示的为:

  AfterForward

浏览器上urlhttp://127.0.0.1:8080/train/BeforeForward

 

从结果我们可以看到

1、             forward会显示forward后的页面的内容

2、            forward调用后浏览器的url不会变化

3、            forward后的页面和原页面的request为同一对象

 

 

下面是RequestDispatchervoid include(ServletRequest request, ServletResponse response)例子了,这个例子里,我们使用request来获取RequestDispatcher对象,所以可以使用相对路径。

BeforeInclude

package  squall.servlet.path;

 

import  java.io.IOException;

import  java.io.PrintWriter;

 

import  javax.servlet.RequestDispatcher;

import  javax.servlet.ServletException;

import  javax.servlet.http.HttpServlet;

import  javax.servlet.http.HttpServletRequest;

import  javax.servlet.http.HttpServletResponse;

 

public   class  BeforeInclude  extends  HttpServlet

{

       
protected void doGet(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              resp.setContentType(
"text/html");

              PrintWriter out 
= resp.getWriter();

              String docType 
= "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ";

              req.setAttribute(
"canyousee""this");

 

              out.println(docType 
+ "<HTML> " + "<HEAD><TITLE> BeforeInclude"

                            
+ "</TITLE></HEAD> " + "<BODY BGCOLOR="#FDF5E6"> "

                            
+ "     <h1>BeforeInclude</h1>    </br>");

              

              RequestDispatcher rd 
= req.getRequestDispatcher(

                            
"InInclude");

              System.err.println(
"canyousee " + req.getAttribute("canyousee")

                            
+ " in BeforeInclude");

              rd.include(req, resp);

              out.println(
"     <h1>AfterInclude</h1>    </br>");

              out.println(
"</body></html>");

              System.err.println(
"end in BeforeInclude");

       }


 

       
protected void doPost(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              doGet(req, resp);

       }


}


 

InInclude

 

package  squall.servlet.path;

 

import  java.io.IOException;

import  java.io.PrintWriter;

 

import  javax.servlet.ServletException;

import  javax.servlet.http.HttpServlet;

import  javax.servlet.http.HttpServletRequest;

import  javax.servlet.http.HttpServletResponse;

 

public   class  InInclude  extends  HttpServlet

{

       
protected void doGet(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              System.err.println(
"In InInclude!");

              PrintWriter out 
= resp.getWriter();

              out.println( 
"     <h1>In InClude</h1>    </br>");

              System.err.println(
"canyousee " + req.getAttribute("canyousee")

                            
+ " in InInclude");

       }


 

       
protected void doPost(HttpServletRequest req, HttpServletResponse resp)

                     
throws ServletException, IOException

       
{

              doGet(req, resp);

       }


}


 

 

BeforeIncludeInInclude分别mapping<url-pattern>/path/BeforeInclude</url-pattern><url-pattern>/path/InInclude</url-pattern>

 

访问http://127.0.0.1:8080/train/path/BeforeInclude

可以看到浏览器显示为:

BeforeInclude

 

In InClude

 

AfterInclude

而控制台输出为:

canyousee this in BeforeInclude

In InInclude!

canyousee this in InInclude

end in BeforeInclude

 

需要注意的是上面的例子中的InInclude无法输出一个完整的html页面。

从结果可以看出:

1、             include会显示原页面中include的地方显示includeServlet输出的内容

2、            forward调用后浏览器的url不会变化

3、            forward后的页面和原页面的request为同一对象

 

还是要强调一下InInclude无法输出一个完整的html页面,它只是输出一部分东西而已。

讲到这里基本上servlet中请求的转发和跳转已经讲完了。

 
  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论 2

打赏作者

Squall1009

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值