Servlet中 请求转发:

请求转发和重定向的区别:
重定向最少两次请求两次响应,转发只有一次请求一次响应
重定向地址栏发生变化,转发地址栏不变
重定向是响应对象(response)的方法,请求转发是请求对象(request)的方法




在index.HTML中输入:
<a href="/day36/sd5?money=20">请求转发</a><br />


在web.xml中输入:
<servlet>
    <description></description>
    <display-name>ServletDemo05</display-name>
    <servlet-name>ServletDemo05</servlet-name>
    <servlet-class>cn.itcast.web.ServletDemo05</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ServletDemo05</servlet-name>
    <url-pattern>/sd5</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>ServletDemo06</display-name>
    <servlet-name>ServletDemo06</servlet-name>
    <servlet-class>cn.itcast.web.ServletDemo06</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ServletDemo06</servlet-name>
    <url-pattern>/sd6</url-pattern>
  </servlet-mapping>


在src下输入程序:


package cn.itcast.web;


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ServletDemo05 extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("我说:借钱饿了"+request.getParameter("money")+"走不动了");
System.out.println("他说:先坐着我出去一趟");

request.setAttribute("msg", "hahahha");
//请求转发
request.getRequestDispatcher("/sd6").forward(request, response);
}


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


}




package cn.itcast.web;


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ServletDemo06 extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object value = request.getAttribute("msg");
System.out.println("小亮送钱"+request.getParameter("money")+value);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值