Servlet-开发流程
- 创建一个JavaWeb项目,并将tomcat添加到当前项目的依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body>
<form action="userServlet" method="post"> 用户名:<input type="text" name="username"> <br> <input type="submit" value="校验"> </form> </body> </html>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.PrintWriter;
public class UserServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username");
String info = "Yes"; if (username.equals("xiaobai")){ info = "NO"; } PrintWriter writer = resp.getWriter(); writer.write(info); } }
|
- 在Web.xml中,配置servlet 对应的请求映射路经
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" version="6.0">
<servlet> <servlet-name>userServlet</servlet-name> <servlet-class>com.xiaobai.servlet.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>userServlet</servlet-name> <url-pattern>/userServlet</url-pattern> </servlet-mapping> </web-app>
|
Content-Type响应头
MIME基类型响应头,又称为媒体类型、文件类型、响应的数据类型
MIME类型用于告诉客户端响应的数据是什么类型的数据,客户端以此类型决定用什么方式解析响应体
在Tomcat 的配置文件 -> web.xml中,几乎记录了所有的文件类型对应的MIME类型,例如:
1 2 3 4
| <mime-mapping> <extension>html</extension> <mime-type>text/html</mime-type> </mime-mapping>
|
扩展名为html的文件在响应时,Tomcat会根据web.xml的配置查找到对应Content-Type的属性值并将其赋值
动态页面的访问
当请求的是一个servlet页面时,响应头中没有Content-Type的键值对,默认的时html格式
我们需要调用resp对象的setContentType方法手动为其属性赋值
1 2
| resp.setContentType("text/html"); resp.setHeader("Content-Type", "text/html");
|