Servlet的概述
Servlet其实就是一个运行在web服务器上的Java程序,用于处理从web客户端发送的请求,并且对请求作出响应。
1、servlet的使用
- 编写一个Java类实现Servlet接口
点击查看代码
package com.itheima.servlet.demo1;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class HelloServlet implements Servlet{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
// T在页面上输出
resp.getWriter().println("HelloServlet...");
}
}
- 在web.xml配置这个类
点击查看代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>web_test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置servlet -->
<servlet>
<!-- 配置servlet的名称 -->
<servlet-name>helloServlet</servlet-name>
<!-- 配置servlet的全路径 -->
<servlet-class>com.itheima.servlet.demo1.HelloServlet</servlet-class>
</servlet>
<!-- 配置servlet的映射 -->
<servlet-mapping>
<!-- 配置servlet的名称 -->
<servlet-name>helloServlet</servlet-name>
<!-- 配置访问路径 -->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>