servlet

servlet 生命周期:

1.实例化:当servlet第一次被调用的时候,就会被实例化,有且只有实例化一次,所以servlet是单实例的

2.初始化:在构造方法后,servlet继承HttpServlet,init(ServletConfig) 是父类的方法,此方法执行一次

3.提供服务:service判断是Post还是Get

4.销毁:两种情况

              1.该Servlet所在的web应用重新启动

               2.关闭tomcat的时候 destroy()方法会被调用,但是这个一般都发生的很快,不易被发现

5.回收:GC 回收


获取提交的参数:request.getParameter("参数标号") 

返回响应:回写html 

String html = null;
html = "<div style='color:green'>something to  show</div>"
PrintWriter pw = response.getWriter();
pw.println(html);

哪些提交属于POST:1.在form上显示设置 method="post"的时候

                                 2.ajax指定post方式的时候

哪些提交属于GET:  1.form默认的提交方式

                                2.如果通过一个超链访问某个地址

                                3.如果在地址栏直接输入某个地

                                4.ajax指定使用get方式的时候


service(HttpServletRequest , HttpServletResponse )方法: 在进入在执行doGet()或者doPost()之前,都会先执行service()。由service()方法进行判断,到底该调用doGet()还是doPost()。所以,有时候也会直接重写service()方法,在其中提供相应的服务,就不用区分到底是get还是post了。


对于中文的处理:

 1.设置html中提交中文的编码格式<meta charset="UTF-8">

 2.servlet接受数据中文数据前,设置中文的编码方式与被提交的数据一致:request.setCharacterEncoding("UTF-8")

 3.返回中文响应前,设置返回内容以及浏览器已有内容中文编码格式:response.setContentType("text/html; charset=UTF-8")   ,  response.setCharacterEncoding("UTF-8")仅仅设置返回内容的中文编码格式

                                

服务器跳转与客户端跳转

服务器跳转:服务器自动跳转界面,客户端不知道发生了跳转,可以发现浏览器地址栏地址没有变,但已经不是你实际访问的地方了,客户端只请求了一次。request.getRequestDispatcher("URL").forward(request, response);

客户端跳转:服务器将要跳转的地址给客户端,让客户端再去请求,浏览器地址栏变成了新的地址,客户端相当于请求了两次。response.sendRedirect("URL");


Request获取参数:1.request.getParameter(): 是常见的方法,用于获取单值的参数
                              2.request.getParameterValues(): 用于获取具有多值得参数,比如注册的时候提交的爱好,可以使多选的。

                              3.request.getParameterMap(): 用于遍历所有的参数,并返回Map类型。

<!DOCTYPE html>
 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
<form action="register" method="get">
    名字 : <input type="text" name="name"> <br>
    Hobit : LOL<input type="checkbox" name="hobits" value="lol">
        DOTA<input type="checkbox" name="hobits" value="dota"> <br>
       
         <input type="submit" value="done">
</form>

servlet

protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        System.out.println("获取单值参数name:" + request.getParameter("name"));
 
        String[] hobits = request.getParameterValues("hobits");
        System.out.println("获取具有多值的参数hobits: " + Arrays.asList(hobits));
 
        System.out.println("通过 getParameterMap 遍历所有的参数: ");
        Map<String, String[]> parameters = request.getParameterMap();
 
        Set<String> paramNames = parameters.keySet();
        for (String param : paramNames) {
            String[] value = parameters.get(param);
            System.out.println(param + ":" + Arrays.asList(value));
        }
 
    }


猜你喜欢

转载自blog.csdn.net/qq_27469549/article/details/80069931