Servlet基础

来源:互联网 发布:临沂淘宝客服位置 编辑:程序博客网 时间:2024/06/06 00:44

Servlet是sun公司提供的一门用于开发动态web资源的技术,sun在其API中提供了一个Servlet接口,用户若想动态开发一个web资源完成以下两步即可:

1.编写一个java类,实现servlet接口

2.把编写好的servlet类部署到实现了servlet规范的服务器上


Servlet

       ----> GenericServlet (Adapter)

                         |--   abastract   service(ServletRequest request, ServletResponse)

                                                                       |-HttpServletRequest         |-HttpServletResponse

             ----> HttpServlet


Servlet的调用过程及生命周期:




ServletContext:该对象实例代表着当前应用,每一个Web应用都有自己唯一的一个ServletContext对象

         ->ServletContext生命周期:应用被服务器加载时创建

                                                           应用被服务器卸载时结束

         ->ServletContext是一个域对象,可以简单理解为内部维护了一个Map<String,Object>

         ->利用ServletContext读取配置文件:

                 ·String realPath = context.getRealPath("/WEB-INF/config.properties");

                          *可以读取任何位置上的任何文件

                          *只能用在Web环境下

ServletRequest                             

        |->HttpServletRequest :服务器接收到客户端请求时创建,并传给对应的web应用。用于封装与请求相关的信息。

ServletResponse

        |->HttpServletResponse:服务器收到客户端请求时创建,赢传给对应的web应用,用于封装与响应相关的信息,最后由服务器解析被web应用处理的ServletResponse

                                                        对象,并将内容返回给客户端。 

Servlet核心结构:


              




Servlet常见的处理:

1.中文编码问题

     

                String content = "我是一个神经病";OutputStream out = resp.getOutputStream();//out.write(content.getBytes("GBK"));  // ONE resp.setHeader("Content-Type", "text/html;charset=UTF-8");  //twoout.write(content.getBytes("UTF-8"));

2.以下载的形式查看那文件

   

                String path = getServletContext().getRealPath("/images/psb.jpg");resp.setHeader("Content-Disposition", "attachment;filename=1.jpg");resp.setContentType("application/octet-stream");InputStream in = new FileInputStream(path);OutputStream out = resp.getOutputStream();int len = -1;byte[] b = new byte[1024];while((len = in.read(b)) != -1){out.write(b);}in.close();out.close();

3.生产验证码图片

  

@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {          //通知浏览器对图片不进行缓存处理   resp.setHeader("Expires", "-1");   resp.setHeader("Cache-Control", "no-cache");   resp.setHeader("Pragma", "no-cache");   //image size       int width = 120;       int height = 20;       //create BufferedImage object       BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);       //get the pen from BufferedImage       Graphics grap = bi.getGraphics();       //border       grap.setColor(Color.BLUE);       grap.drawRect(0, 0, width, height);       //background color       grap.setColor(Color.YELLOW);       grap.fillRect(1, 1, width - 2, height - 2);              //line       Random rand = new Random();       grap.setColor(Color.GRAY);       for(int i =0;i < 15;i ++){       grap.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));       }              //font property       grap.setColor(Color.RED);       grap.setFont(new Font("宋体",Font.BOLD|Font.ITALIC,18));              for(int i = 1;i < 5;i ++){       grap.drawString(rand.nextInt(10) + "", 20 * i, 15);       }              ImageIO.write(bi, "jpg", resp.getOutputStream());}


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>Verfiy Image</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page">    <script type="text/javascript">        function changeImage(){             var imgObj = documnt.getElementById("img");             imgObj.src = "/ServletDemo1/verifyImage/ServletDemo?" + new Date().getTime();        }    </script>  </head>    <body>       <form action="">             username:<input type="text" name="username"/><br/>             password:<input type="password" name="password"><br>             <input type="text" value="login"/><img id="img" src="${pageContext.request.contextPath}/verifyImage/ServletDemo">             <a href="javascript:changeImage()">看不清</a><br>             <input type="button" value="login"/>              </form>  </body></html>

4.定时刷新页面

  

@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {    //refresh current page to current pageresp.setHeader("Refresh", "2");resp.getOutputStream().write(new Random().nextInt());    //refresh current page to another pageresp.setHeader("Refresh", "2;URL=url");resp.getWriter().write("you are not login in, page will towards login in page");    }


5.解决中文请求参数的中文乱码问题

  post请求:由于用户访问的是我们站点的页面,所以,在提供页面资源的时候,我们是有权利去规定页面的Content-Type的。出现中文乱码的问题的主要原因就是在中文被编

                      码和解码的过程中查询了不同的编码表,所以,解决中文乱码问题的原则就是使中文参数在被编码和解码的过程中遵循一致的码表。既然我们已经在制作页面资源 

                      的时候指定的页面的编码格式,那么,只需要通知服务器在解析中文参数的时候去遵循和页面相同的编码表即可。

                      需要注意的是:请求和响应是两个独立的过程,他们即使采用的不同的编码表也不会出现中文乱码问题,因为请求和响应这两个过程分别对应了自己的编码和解码

                                                  的过程。虽然是这样,但是,在实际开发中,还是要使全站的编码风格一致,否则,如果在响应页面再次提交中文参数的时候还是会出现中文乱码

                                                  问题。

 ge请求:以get方式发送的中文参数和post方式在编码的过程上有所不同,get传送的中文参数不在请求正文,而是作为url的一部分,所以Content-type对此时的中文参数是不

                 生效的,默认是一个ISO-8859-1码表进行编码,所以,解决以 个get方式请求的中文乱码问题,就需要手动进行解码和重新编码。


@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {/*                POST * because of the data will be transfer in the form of binary ,  * if the character code table is different between client and server, * there will be the problem of messy code * *//* * it will get the value order by client character code table, * so, the users request out page, and we can make rule of character  * code table of the page. * so, all will be solved.  *  *///notify server analysis parameter with UTF-8req.setCharacterEncoding("UTF-8");//waring: request , response are divided resp.setContentType("text/html;charset=GBK");String username = req.getParameter("username");    resp.getWriter().write(username);/* *                     GET * The chinese will be encode by ISO-8859-1, we should decode it by ISO-8859-1 * and re-encode it                       * */String username1 = new String(req.getParameter("username").getBytes(),"UTF-8");resp.getWriter().write(username1);}


6.请求转发与重定向

    请求转发时,服务器会清空响应对象中的响应正文,即转发前后原组件的页面输出全部无效。在请求转发的过程中,可以认为是将同一个request,response对象进行转发,

    但实际上request对象不是原有对象,而是将原有对象复制到新的renquest对象中,response对象也不是原有的response对象,服务器会新创建一个response对象,并把

    原有的response对象的正文情况,剩余部分复制到新的response中,在此基础性进行请求转发的。

0 0
原创粉丝点击