Servlets are the pure Java solution to handle web requests. Many application will use servlets instead of JSP and others will use servlets in conjunction with JSP. Experienced JSP programmers use servlets in conjunction with JSP to create clearer and simpler applications. The servlets handle Java processing: form handing, calculation and database queries. JSP formats the results.
Servlets是单纯用Java来处理web请求的一个解决方案。许多应用用Servlets替代了JSP,还有一些人整合使用Servlet与JSP。有经验的JSP开发人员用Servlets配合JSP来创建清晰简洁的应用。Servlets负责JAVA程序逻辑部分:如表单处理,计算和数据库查询等操作。而JSP负责格式化并展示Servlets处理后的结果。
Create the following servlet in
with your favorite text editor: notepad, emacs, vi, or whatever.用你最喜欢的文本编辑器notepad,emacs,vi 等等,创建以下servlet
WEB-INF/classes/test/HelloServlet.java
package test;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class HelloServlet extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();
out.println("Hello, world!");
out.close();
}
}
Now browse the servlet at /resin-3.0/hello. Resin will automatically compiles the servlet for you. Browsing servlets differs from page browsing because you're executing a servlet class, not looking at a page. The URL is configured for the hello, world servlet below.
现在可以通过/resin-3.0/hello来浏览servlet。Resin(服务器类似于apache)将自动编译你的servlet。浏览servlets不同于页面,因为你实际上是运行了一个servlet类,不是在看一个页面。/hello 这个地址是在下面为hello,world这个servlet配置的。
配置:
Configuration for the servlet is in the
file.需要在WEB-INF/web.xml中为servlet进行配置。
The servlet needs to be configured and it needs to be mapped to a URL. The <servlet> tag configures the servlet. In our simple example, we just need to specify the class name for the servlet.
servlet需要在配置文件中进行配置并且需要为它配置一个访问地址(URL)。<servlet>这个标签用来配置servlet,在我们这个简单的示例中,我们只需要为我们的servlet定义一个名字。
The <servlet-mapping> tag specifies the URLs which will invoke the servlet. In our case, the URL invokes the servlet. Because the tutorial webapp is a sub-URL like , the actual URL to invoke the servlet is the combination of the two.
<servlet-mapping>这个标签定义了可以执行servlet的访问地址。在我们这个示例中, /hello 这个地址可以执行我们的servlet。而实际执行servlet的地址应该是访问应用的地址加上servlet配置的地址,例如
+ / hello 即
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>test.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
进行以上配置后即可通过应用地址+servlet地址来执行servlet了
原文:http://www.caucho.com/resin-3.0/servlet/tutorial/helloworld/index.xtp。
对文章进行了截取,摘除不重要的部分