1 / 9

Java Servlet 技术

Java Servlet 技术. 1. 返回. 5.1 Servlet 的概念. Servlet 是用 Java 编写的 Server 端程序,它与协议和平台无关。 Servlet 运行于请求 / 响应模式的 Web 服务器中。 Java Servlet 可以动态地扩展 Server 的能力,由于 Servlet 本身就是一个 Java 类,所以基于 Java 的全部特性(面向对象、数据库访问、多线程处理)都能够访问。而这些特性是我们编写高性能 Web 应用程序的关键。

Download Presentation

Java Servlet 技术

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Servlet 技术 1 返回

  2. 5.1 Servlet的概念 Servlet是用Java编写的Server端程序,它与协议和平台无关。Servlet运行于请求/响应模式的Web服务器中。Java Servlet可以动态地扩展Server的能力,由于Servlet本身就是一个Java类,所以基于Java的全部特性(面向对象、数据库访问、多线程处理)都能够访问。而这些特性是我们编写高性能Web应用程序的关键。 Servlet的运行方式和CGI很相似。它们都是被来自于客户端的请求所唤醒。但是二者之间又存在着差别,在传统的CGI中,每个请求都要启动一个新的进程,如果CGI程序本身的执行时间较短,启动进程所需要的开销很可能反而超过实际执行时间。而Servlet引擎为每个客户的请求创建一个线程而不是进程,由于线程本身不分配资源而是从进程那里继承资源,显然,Servlet相对CGI而言效率要高的多。 2

  3. 5.2 JSP与Servlet 用户在JSP页面里可以使用以下两种方法实现这一过程。 1、通过表单调用Servlet 2、要实现在JSP页面中调用Servlet,我们还可以采取在页面中设置超级链接的方法来实现。 下面我们给出例程,其中定义了一个表单,要求用户输入一个正整数。其源程序如下。 3

  4. <%@ page contentType="text/html;charset=GB2312" %> <html> <head> <title>post-方式数字提交ex8-1.jsp </title> </head> <body> <p> <h1>请在下面的输入框中给Servlet输入一个正整数:</h1> <br> <br> </p> <form method="POST" action="examples/servlet/deal"> <input type="text" name="number" size="20"> <input type="submit" value=" 提交给Servlet"> </form> </body> </html> 程序运行效果如下 4

  5. 5

  6. 程序中所调用的Servlet源文件deal.java,其源程序如下所示程序中所调用的Servlet源文件deal.java,其源程序如下所示 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class deal extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html;charset=GB2312"); // 取得一个向客户输出数据的输出流。 PrintWriter out=response.getWriter(); // 设置响应的MIME类型。 out.println("<html>"); out.println("<body>"); String number=request.getParameter("number"); //利用getParameter方法获取客户信息 6

  7. int m=0; try { m=Integer.parseInt(number); out.println("<h2>不超过"+m+"的偶数</h2>如下:"); for(int i=1;i<m;i++) { if(i%2==0) out.println(i); } } catch(NumberFormatException e) { out.println("<h1>您输入的数字格式有误!</h1>"); } } } 当我们在文本框中输入66时,按提交按钮程序运行效果如下图所示 7

  8. 8

  9. 当我们在文本框中输入格式不正确的数据(如66ab)时,程序运行效果如下图所示当我们在文本框中输入格式不正确的数据(如66ab)时,程序运行效果如下图所示 9

More Related