Servlet

package com.qing.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter; public class HelloServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
} @Override
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
//响应的类型:html
response.setContentType("text/html");
//响应的编码
response.setCharacterEncoding("utf-8");
//获取响应的输出流
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true"> <!--web.xml中配置web的核心应用-->
<!--注册Servlet-->
<servlet>
<!--名称,可以随意写-->
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.qing.servlet.HelloServlet</servlet-class>
</servlet>
<!--映射:一个Servlet对应一个mapping-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!--请求路径,可以随意写-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

Servlet简介

  1. Servlet是sun公司开发动态web的一门技术
  2. sun公司在这些API中提供一个接口:Servlet,如果想开发一个Servlet程序,只需要完成两个步骤
    1. 编写一个类,实现Servlet接口
    2. 把开发好的java类部署到web服务器中
  3. 我们把实现了Servlet接口的java程序叫做Servlet
  4. Servlet接口sun公司有两个默认的实现类:HttpServlet和GenericServlet

HelloServlet

  1. 构建一个普通maven项目,删掉src目录,这个空的工程就是Maven主工程,可以在里面建立Module;


  1. 配置pom.xml,添加依赖;
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.qing</groupId>
<artifactId>javaweb-03-servlet</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies> </project>
  1. 在父工程中新建子模块Module;



  1. 关于父子工程的理解:父项目中的jar包子项目可以直接使用;

    1. 父项目中会有
    2. 子项目中会有
    <modules>
<module>servlet-01</module>
</modules>
    <parent>
<artifactId>javaweb-03-servlet</artifactId>
<groupId>com.qing</groupId>
<version>1.0-SNAPSHOT</version>
</parent>

  1. Maven环境优化:

    1. 修改web.xml为最新版本:修改子工程web.xml中的版本;
    2. 将maven的结构搭建完整:子工程添加java和resources目录;
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
</web-app>

  1. 编写一个Servlet程序;

    1. 编写一个普通类
    2. 实现Servlet接口,这里继承HttpServlet

package com.qing.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter; public class HelloServlet extends HttpServlet {
//由于get或者post只是请求实现的不同方式,可以相互调用,业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入doGet方法");
PrintWriter writer = resp.getWriter();//响应流
writer.print("hello,servlet");
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
  1. 在web.xml中编写Servlet的映射

为什么需要映射?

我们写的是Java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的Servlet,还需要给他一个浏览器可以访问的路径

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true"> <!--注册Servlet-->
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.qing.servlet.HelloServlet</servlet-class>
</servlet>
<!--Servlet的请求路径-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
  1. 配置Tomcat

  1. 启动测试

Servlet原理

Servlet是由web服务器调用,web服务器收到浏览器请求后,会:

servlet-mapping Servlet请求路径

  1. 一个Servlet指定一个映射路径
    <servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
  1. 一个Servlet指定多个映射路径
    <servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello1</url-pattern>
</servlet-mapping>
  1. 一个Servlet指定通用映射路径
    <servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
  1. 默认请求路径,会跳过index.jsp,直接进Servlet
    <servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
  1. 指定后缀
<!--可以自定义后缀实现请求映射,注意:*前面不能加任何字符,否则会报错-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>*.qing</url-pattern>
</servlet-mapping>
  1. 优先级问题:指定固定映射路径优先级最高,如果找不到就会走默认请求路径
<!--404-->
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.qing.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

ServletContext Servlet上下文

web容器在启动的时候,会为每个web程序都创建一个对应的ServletContext对象,它代表了当前web应用

ServletContext的应用

共享数据:在一个Servlet设置的数据,可以在另一个Servlet获取到

package com.qing.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("hello");
//Servlet上下文
ServletContext context = this.getServletContext();
//设置数据
String username = "清风";
context.setAttribute("username", username);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.qing.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get");
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
System.out.println(username);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true"> <servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.qing.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>get</servlet-name>
<servlet-class>com.qing.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/get</url-pattern>
</servlet-mapping>
</web-app>

获取初始化参数

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true"> <context-param>
<param-name>url</param-name>
<param-value>127.0.0.1</param-value>
</context-param> <servlet>
<servlet-name>get</servlet-name>
<servlet-class>com.qing.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/get</url-pattern>
</servlet-mapping>
</web-app>
package com.qing.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get");
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().println(url);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

请求转发

package com.qing.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get");
ServletContext context = this.getServletContext();
//转发到/hello
context.getRequestDispatcher("/hello").forward(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

读取Properties文件

username=root
password=123456
package com.qing.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; public class PropertiesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取流,根路径为打包后target下的项目名称
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(in);
String user = properties.getProperty("username");
String pwd = properties.getProperty("password");
resp.getWriter().print(user + ":" + pwd);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true"> <servlet>
<servlet-name>prop</servlet-name>
<servlet-class>com.qing.servlet.PropertiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>prop</servlet-name>
<url-pattern>/prop</url-pattern>
</servlet-mapping>
</web-app>

HttpServletResponse

  • web服务器接收到浏览器的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象和一个代表响应的HttpServletResponse对象

    • 如果要获取浏览器请求过来的参数:找HttpServletRequest
    • 如果要给浏览器响应一下信息:找HttpServletResponse
  • 简单分类
    • 负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
  • 负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
  • 响应的状态码
int SC_OK = 200;
int SC_CREATED = 201;
  • 常见应用

    • 向浏览器输出消息

下载文件

  - 获取下载文件的路径
- 获取文件名
- 设置浏览器支持下载
- 文件下载的消息头和编码问题 [https://www.cnblogs.com/hackxiyu/p/9046247.html](https://www.cnblogs.com/hackxiyu/p/9046247.html)
response.setHeader("Content-Disposition", "attachment;filename="+new String(AREA_FILE.getBytes("gb2312"), "ISO-8859-1"));
  - 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将输入流写入buffer缓冲区,使用输出流将缓冲区中的数据输出到客户端
package com.qing.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder; public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取下载文件的路径
String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/静.jpg");
System.out.println("下载文件的路径为:" + realPath);
//获取文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
System.out.println("文件名为:" + fileName);
//设置浏览器支持下载
resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//获取下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
//创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//获取OutputStream对象
ServletOutputStream outputStream = resp.getOutputStream();
//将输入流写入buffer缓冲区,使用输出流将缓冲区中的数据输出到客户端
while ((len=fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
fileInputStream.close();
outputStream.close();
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true"> <servlet>
<servlet-name>fileDown</servlet-name>
<servlet-class>com.qing.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileDown</servlet-name>
<url-pattern>/fileDown</url-pattern>
</servlet-mapping>
</web-app>

验证码功能

package com.qing.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random; public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置浏览器3秒自动刷新一次
resp.setHeader("refresh", "3"); //在内存中创建一个图片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//得到画笔
Graphics2D g = (Graphics2D) image.getGraphics();
//设置画笔颜色,画矩形背景
g.setColor(Color.WHITE);
g.fillRect(0,0,80,20);
//设置画笔颜色和字体,画随机数
g.setColor(Color.BLUE);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeRandom(),0,20); //告诉浏览器,这个请求用图片的方式打开
resp.setContentType("image/jpeg");
//网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache"); //把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
} //生产随机数
private String makeRandom() {
Random random = new Random();
String num = random.nextInt(9999999) + "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 7 - num.length(); i++) {
sb.append(0);
}
num = sb.toString() + num;
return num;
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true"> <servlet>
<servlet-name>imageServlet</servlet-name>
<servlet-class>com.qing.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageServlet</servlet-name>
<url-pattern>/image</url-pattern>
</servlet-mapping>
</web-app>

重定向

一个web资源收到客户端请求后,他会通知客户端去访问另外一个web资源,这个过程叫重定向。


常见场景:用户登录

package com.qing.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
重定向相当于
resp.setHeader("Location","/resp/image");
resp.setStatus(302);
*/
//重定向
resp.sendRedirect("/resp/image");
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true"> <servlet>
<servlet-name>imageServlet</servlet-name>
<servlet-class>com.qing.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageServlet</servlet-name>
<url-pattern>/image</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>redirectServlet</servlet-name>
<servlet-class>com.qing.servlet.RedirectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>redirectServlet</servlet-name>
<url-pattern>/redirect</url-pattern>
</servlet-mapping>
</web-app>

重定向和转发的区别

  • 相同点

    • 页面都会实现跳转
  • 不同点
    • 请求转发的时候,URL不会发生变化 状态码:307
    • 重定向的时候,URL会发生变化 状态码:302

登录demo

  1. pom.xml添加jsp依赖:javax.servlet.jsp
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.qing</groupId>
<artifactId>javaweb-03-servlet</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>servlet-01</module>
<module>servlet-02</module>
<module>response</module>
</modules> <dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
</dependencies> </project>
  1. 编辑登录页,${pageContext.request.contextPath}代表当前项目
<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
  1. 编辑登录成功页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>
  1. 处理登录请求,重定向到成功页面
package com.qing.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入登录请求");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username + ":" + password);
//重定向
resp.sendRedirect("/resp/success.jsp");
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
  1. 在web.xml中添加Servlet映射
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true"> <servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.qing.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

HttpServletRequest

HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,http请求中的所有信息都会被封装到HttpServletRequest,通过HttpServletRequest的方法,可以获得客户端的所有信息。

获取浏览器传递的参数

String contextPath = req.getContextPath();//项目路径
String servletPath = req.getServletPath();//Servlet路径
String requestURI = req.getRequestURI();//请求路径
String name = req.getParameter("name");
String[] names = req.getParameterValues("name");

请求转发

//请求转发
//这里的/代表当前的web应用,即contextPath
req.getRequestDispatcher("/success.jsp").forward(req,resp);

050_Servlet详解的更多相关文章

  1. Linq之旅:Linq入门详解(Linq to Objects)

    示例代码下载:Linq之旅:Linq入门详解(Linq to Objects) 本博文详细介绍 .NET 3.5 中引入的重要功能:Language Integrated Query(LINQ,语言集 ...

  2. 架构设计:远程调用服务架构设计及zookeeper技术详解(下篇)

    一.下篇开头的废话 终于开写下篇了,这也是我写远程调用框架的第三篇文章,前两篇都被博客园作为[编辑推荐]的文章,很兴奋哦,嘿嘿~~~~,本人是个很臭美的人,一定得要截图为证: 今天是2014年的第一天 ...

  3. EntityFramework Core 1.1 Add、Attach、Update、Remove方法如何高效使用详解

    前言 我比较喜欢安静,大概和我喜欢研究和琢磨技术原因相关吧,刚好到了元旦节,这几天可以好好学习下EF Core,同时在项目当中用到EF Core,借此机会给予比较深入的理解,这里我们只讲解和EF 6. ...

  4. Java 字符串格式化详解

    Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...

  5. Android Notification 详解(一)——基本操作

    Android Notification 详解(一)--基本操作 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Notification 文中如有纰 ...

  6. Android Notification 详解——基本操作

    Android Notification 详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 前几天项目中有用到 Android 通知相关的内容,索性把 Android Notificatio ...

  7. Git初探--笔记整理和Git命令详解

    几个重要的概念 首先先明确几个概念: WorkPlace : 工作区 Index: 暂存区 Repository: 本地仓库/版本库 Remote: 远程仓库 当在Remote(如Github)上面c ...

  8. Drawable实战解析:Android XML shape 标签使用详解(apk瘦身,减少内存好帮手)

    Android XML shape 标签使用详解   一个android开发者肯定懂得使用 xml 定义一个 Drawable,比如定义一个 rect 或者 circle 作为一个 View 的背景. ...

  9. Node.js npm 详解

    一.npm简介 安装npm请阅读我之前的文章Hello Node中npm安装那一部分,不过只介绍了linux平台,如果是其它平台,有前辈写了更加详细的介绍. npm的全称:Node Package M ...

随机推荐

  1. 关于free和delete的使用

    上一篇篇幅太长,这里再区分free和delete的用法. 两个同时存在是有它的原因的,我们前面说过,free是函数,它只释放内存,但不会调用析构函数,如果用free去释放new申请的空间,会因为无法调 ...

  2. zsh & for loop bug

    zsh & for loop bug ​for: command not found syntax error near unexpected token do' do' Unicode 编码 ...

  3. Apple CSS Animation All In One

    Apple CSS Animation All In One Apple Watch CSS Animation https://codepen.io/xgqfrms/pen/LYZaNMb See ...

  4. 图解 HTTP, 图解 HTTPS, 图解 HTTP/2, 图解 HTTP/3, 图解 QUIC

    图解 HTTP, 图解 HTTPS, 图解 HTTP/2, 图解 HTTP/3, 图解 QUIC HTTP https://en.wikipedia.org/wiki/Hypertext_Transf ...

  5. Android Webview & iframe auto full screen

    Android Webview & iframe auto full screen android webview iframe 全屏适配 https://stackoverflow.com/ ...

  6. flutter & i18n & L10n & json

    flutter & i18n & L10n & json https://marketplace.visualstudio.com/items?itemName=esskar. ...

  7. React LifeCycle Methods & re-learning 2019

    React LifeCycle Methods & re-learning 2019 v16.9.0 https://reactjs.org/docs/react-component.html ...

  8. 关于TCP的Total Length

    TCP/IP传输层 文档 随便找了个发送的TCP: 70 89 cc ee 84 2c 3c 2c 30 a6 a2 d0 08 00 45 00 00 4c c7 a8 40 00 80 06 00 ...

  9. NGK DeFi Baccarat怎么玩能赚钱?

    市面上大多数DeFi项目都是基于以太坊来开发的,除了吞吐量低.存储量小以及交易速度慢等问题以外,高额的Gas手续费将不少终端用户拒之门外. 基于此NGK.IO推出了低门槛的DeFi项目-- Bacca ...

  10. C# NOPI 项目实战(经典)(可下载项目源码)

    1 -.首先说明下项目目的: 之前我有写过一篇  "NPOI操作EXCEL" 这篇文章主要介绍了如何安装NPOI,以及NPOI具体如何使用,并且用具体实例介绍了excel导入到da ...