循循渐进01篇 HttpServlet 请求转发

set类
public class Servletset extends HttpServlet { //继承HttpServlet 重写 dopost doget 方法
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext(); //获取Context
String str = "mszoor";
context.setAttribute("aa",str);//添加属性

context.getRequestDispatcher("/get").forward(req,resp);//请求转发
//显示 转发页面的数据加上转发之前的数据 直接访问本页面地址


PrintWriter writer = resp.getWriter();//响应流
writer.print("Hello,servlet");//写入数据

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
get类
public class Servletget extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String string =(String) this.getServletContext().getAttribute("aa");
String url =this.getServletContext().getInitParameter("url");//获取xml 参数

resp.setContentType("text/html");//设置响应数据格式
resp.setCharacterEncoding("utf-8");//设置响应数据编码
PrintWriter writer = resp.getWriter();//响应流
writer.print("名字是:"+string+"<br/>地址是:"+url);


}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}

备注: 请求转发 访问请求类地址,显示转移类页面数据+转移前代码数据

猜你喜欢

转载自www.cnblogs.com/huhao2000/p/11920469.html