public class HelloServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request:请求的输入;response:响应的输出
request.setCharacterEncoding("UTF-8");//设置请求的字符集编码
// request.getInputStream();//请求正文的输入流
String method = request.getMethod();//获取请求方式:get/post
String name = request.getParameter("name");//获取请求参数
response.setCharacterEncoding("UTF-8");//设置响应的字符集编码
response.setContentType("text/html;charset=UTF-8");//设置文档类型和字符集编码
// response.getOutputStream();//响应正文的输出流
PrintWriter out = response.getWriter();//获取字符输出流
//将响应正文输出
out.println("methon:"
+method+"");
out.println("name:"
+name+"");
out.println("date:"
+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"");
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
方式一: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>Tomcat_yh</display-name>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.yh.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello.let</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello/*
HelloServlet
*.hello
RetetionServlet
com.yh.servlet.RetetionServlet
yh
zf
1
RetetionServlet
/retetion.let
方式二:Annotation注解
//@WebServlet(value={"/hello1.let","/hello2.let"})
//@WebServlet("/hello.let")
//@WebServlet("hello.let")
@WebServlet({"/hello1.let","/hello1/*","*.hello1"})
//注解,相当于web.xml配置文件中的servlet配置
public class HelloServlet extends HttpServlet{}
访问原理
index.jsp
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>第一个JSP程序</h1>
<%=new java.util.Date() %>
<h2>修改了</h2>
<%=this.getClass().getResource("/") %>
<a href="hello.let">hello.let</a>
<a href="hello/yh">/hello/*
/*.hello
hello.let?name=yh
@WebServlet
hello1.let
/hello1/*
/*.hello1
retetion.let