浅谈servlet的生命周期 ,以及【Request请求】

版权声明:本站所提供的文章资讯、软件资源、素材源码等内容均为本作者提供、网友推荐、互联网整理而来(部分报媒/平媒内容转载自网络合作媒体),仅供学习参考,如有侵犯您的版权,请联系我,本作者将在三个工作日内改正。 https://blog.csdn.net/weixin_42323802/article/details/82889642

 servlet 的生命周期,从创建到销毁;

在接收request的时候Tomcat调用init方法创建servlet,service对request 或response 进行处理,关闭服务器时候调用destory方法,servlet销毁;【多次请求 init()方法仅仅被调用一次】;


 request 常用到的方法:

//       请求头key         请求头value
//       referer       浏览器通知服务器,当前请求来自何处,如果是直接访问,则不会有这个头。常用于:防盗链
//  If-modified-Since  浏览器通知服务器,本地缓存的最后变更时间。与另一个响应头组合控制浏览器页面的缓存。
//       cookie        与会话有关技术,用于存放浏览器缓存的cookie信息。
//     user-agent      浏览器通知服务器,客户端浏览器与操作系统相关信息
//     connection      保持连接状态。Keep-Alive 连接中,close 已关闭
//        host         请求的服务器主机名
//   content-length    请求体的长度
//    content-type     如POST请求,response.setHeader("content-type", "text/html;charset=UTF-8");
//       accept        浏览器可支持的MIME类型。文件类型的一种描述方式。
//       mime格式        浏览器请求数据的类型,例如:   text/html ,html文件   text/css,css文件
//                       text/javascript,js文件   image/*,所有图片文件
//   accept-encoding   浏览器通知服务器,浏览器支持的数据压缩格式。如:GZIP压缩
//   accept-language   浏览器通知服务器,浏览器支持的语言。各国语言(国际化i18n)

 怎么判断请求的方式:

使用  getMethod()方法,来判断请求是post还是get;

package com.baidu;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "ServletDemo2", urlPatterns = "/ServletDemo2")
public class ServletDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        doGet(request, response);//
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //String getMethod()获取请求方式的类型
        //StringBuffer getRequestURL()获取客户端发出请求完整URL
        //String getRemoteAddr()获取IP地址
        //String getProtocol()获取当前协议的名称和版本
        sop(request.getMethod());
        sop(request.getRequestURL());
        sop(request.getRemoteAddr());
        sop(request.getProtocol());
        System.out.println("-------------------------------");
        sop(request.getHeader("user-agent"));//操作系统相关信息;
    }
    public void sop(Object obj){
        System.out.println(obj);
    }
}

请求域【  转发,servlet 中的数据共享】:

//RequestDispatcher  getRequestDispatcher(String path)获取请求转发器(request对象方法)
//将请求转发到另一个资源(Servlet)上
//void forward(ServletRequest request, ServletResponse response)
//获取请求体:
//String  getParameter(String name)
//getParameter获得指定参数名对应的值。如果没有返回null,如果只有多个获得第一个。  例如:username=jack
//String[] getParameterValues(name)
//getParameterValues[] 获取请求数据key相同的多个数据

// request  的生命周期  innit-->destroy
//void   setAttribute(String name, Object o)往request域中设置值
//Object  getAttribute(String name)从request域中取值
//void  removeAttribute(String name)从request域中移除值

请求转发:

ServletDemo4 转发至 urlPatterns=" / post " 的   ServletDemo3,然后获取request 域中的数据;

package com.baidu;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "ServletDemo4", urlPatterns = "/ServletDemo4")
public class ServletDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);//
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("forwardName", "王五");
        //现在把demo4  的请求转发到demo3 上request域中
        request.getRequestDispatcher("/post").forward(request, response);
    }
}
package com.baidu;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
@WebServlet(name = "ServletDemo3", urlPatterns = "/post")
public class ServletDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);//
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //存在乱码打开下面编码集
        // request.setCharacterEncoding("UTF-8");
        //response.setContentType("text/html;charset=utf-8");
        //response.setHeader("content-type", "text/html;charset=UTF-8");
        String username = request.getParameter("username");//获取value
        String password = request.getParameter("password");
        String[] hobbies = request.getParameterValues("hobby");//hobby 拥有多个parameters
        System.out.println(username+password+ Arrays.toString(hobbies));
        //
        request.setAttribute("name","张三" );
        request.setAttribute("age","18" );
        Object name = request.getAttribute("name");
        Object age = request.getAttribute("age");
        System.out.println(name+"="+age);

        //  从servletDemo4中接收到转发的请求,从请求域request中取出来
        Object forwardName = request.getAttribute("forwardName");
        System.out.println(forwardName);
    }
}

然后请求ServletDemo4, 在ServletDemo3中通过request域 获取属性,结果如下:


 测试ServletDemo3的post请求:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>post的方式提交</title>
</head>
<body>
<form action="http://localhost:8080/post" method="post">
    用户名:<input type="text" name="username"/><br/>
    密码:<input type="text" name="password"/><br/>
    爱好:<input type="checkbox" name="hobby"value="smoking"/> 抽烟
    <input type="checkbox" name="hobby"value="drinking"/> 喝酒
    <input type="checkbox" name="hobby" value="tangtou"/> 烫头  <br/>
    <select name="education">
        <option value="gaozhong">高中</option>
        <option value="dazhuan">大专</option>
        <option value="benke">本科</option>
    </select><br/>
    <input type="submit"value="post的方式提交" />
</form>
</body>
</html>

启动Tomcat服务器,点击提交按钮:

发现存在乱码,设定编码集即可【上面讲过】;

request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");

再次部署项目运行:

猜你喜欢

转载自blog.csdn.net/weixin_42323802/article/details/82889642