javawebServlet
javaweb
http响应
服务器 -- 响应 -- 客户端
Accept:告诉浏览器它所支持的数据类型
Accept-Encoding:支持那种 编码格式 GBK UTF-8 GB2312 ISO8859-1
Content-Type:text/html 类型
Content-Type: image/png
Connection:keep-Alive 连接
Cache-Control: private 缓存控制
Content-Encoding:gzip 编码
Host:主机……/.
Refresh :告诉客户端多久刷新一次
Location:让网页重新定位
servlet
web.xml
<?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>day1.ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
package day1;
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 ServletDemo extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ServletInputStream inputStream = req.getInputStream();
PrintWriter writer = resp.getWriter();
writer.println("hello world!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.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>
<servlet-name>hello</servlet-name>
<servlet-class>day1.ServletDemo</servlet-class>
</servlet>
<!-- 可以有多个servlet映射-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello3/*</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">
<!-- 注册servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>day1.ServletDemo</servlet-class>
</servlet>
<!-- 可以有多个servlet映射-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello3/*</url-pattern>
<!-- 映射可以使用统配符-->
</servlet-mapping>
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>day1.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
优先级问题,指定的固有的映射路径优先级最高,如果找不到就会走默认的处理请求
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>test</servlet-name>
<servlet-class>test.ContextTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>test1</servlet-name>
<servlet-class>test.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test1</servlet-name>
<url-pattern>/test1</url-pattern>
</servlet-mapping>
</web-app>
package test;
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 ContextTest extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// this.getServletConfig()//获取servlet配置
//this.getInitParameter()//获得servlet初始化参数
ServletContext servletContext = this.getServletContext();
servletContext.setAttribute("username","王涛");
}
}
package test;
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;
import java.io.PrintWriter;
public class Test extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf8");
PrintWriter writer = resp.getWriter();
ServletContext servletContext = this.getServletContext();
Object username = servletContext.getAttribute("username");
writer.println(username.toString());
writer.close();
}
}
文件过滤问题
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
HttpServletRequest
获取前端传递参数
package com.test;
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 doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
for (String hobby : hobbys) {
System.out.println(hobby);
}
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
<h2>Hello World!</h2>
<div style="text-align: center;">
<form method="post" action="${pageContext.request.contextPath}/login">
username: <input type="text" name="username">
password: <input type="password" name="password">
hobby:
<input type="checkbox" name="hobbys" value="girl"> girl
<input name="hobbys" type="checkbox" value="encoding"> encoding
<input name="hobbys" type="checkbox" value="song"> song
<input type="checkbox" name="hobbys" value="playboy"> playboy
<br>
<input type="submit">
</form>
</div>
307
HttpServletResponse
响应
web服务器接受到客户端的http请求,针对这个请求,分别创建一个代表响应的HttpServletResponse对象,代表请求的HttpServletRequest对象,
请求来的信息找HttpServletRequest,响应回去的信息找HttpServletResponse
简单分类
负责向浏览器发送数据的方法
public ServletOutputStream getOutputStream() throws IOException;
public PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
public void setCharacterEncoding(String charset);
public void setContentLength(int len);
public void setContentLengthLong(long len);
public void setContentType(String type);
public void setBufferSize(int size);
public int getBufferSize();
public void setDateHeader(String name, long date);
public void addDateHeader(String name, long date);
public void setHeader(String name, String value);
public void addHeader(String name, String value);
public void setIntHeader(String name, int value);
public void addIntHeader(String name, int value);
public void setStatus(int sc);
public static final int SC_CONTINUE = 100;
public static final int SC_SWITCHING_PROTOCOLS = 101;
public static final int SC_OK = 200;
public static final int SC_CREATED = 201;
public static final int SC_ACCEPTED = 202;
public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
public static final int SC_NO_CONTENT = 204;
public static final int SC_RESET_CONTENT = 205;
public static final int SC_PARTIAL_CONTENT = 206;
public static final int SC_MULTIPLE_CHOICES = 300;
public static final int SC_MOVED_PERMANENTLY = 301;
public static final int SC_MOVED_TEMPORARILY = 302;
public static final int SC_FOUND = 302;
public static final int SC_SEE_OTHER = 303;
public static final int SC_NOT_MODIFIED = 304;
public static final int SC_USE_PROXY = 305;
public static final int SC_TEMPORARY_REDIRECT = 307;
public static final int SC_BAD_REQUEST = 400;
public static final int SC_UNAUTHORIZED = 401;
public static final int SC_PAYMENT_REQUIRED = 402;
public static final int SC_FORBIDDEN = 403;
public static final int SC_NOT_FOUND = 404;
public static final int SC_METHOD_NOT_ALLOWED = 405;
public static final int SC_NOT_ACCEPTABLE = 406;
public static final int SC_REQUEST_TIMEOUT = 408;
public static final int SC_CONFLICT = 409;
public static final int SC_GONE = 410;
public static final int SC_LENGTH_REQUIRED = 411;
public static final int SC_PRECONDITION_FAILED = 412;
public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;
public static final int SC_REQUEST_URI_TOO_LONG = 414;
public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
public static final int SC_EXPECTATION_FAILED = 417;
public static final int SC_INTERNAL_SERVER_ERROR = 500;
public static final int SC_NOT_IMPLEMENTED = 501;
public static final int SC_BAD_GATEWAY = 502;
public static final int SC_SERVICE_UNAVAILABLE = 503;
public static final int SC_GATEWAY_TIMEOUT = 504;
public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
文件下载
package test;
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 DownServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取下载的文件路径
String realPath = "D:\\ideaProject\\MavenProject\\ServeltTest\\ContextTest\\src\\main\\resources\\1.png";
//D:\apache-tomcat-8.5.84\webapps\ContextTest_war\1.png,可以写死,直接写绝对路径
System.out.println(realPath);
//2.下载的文件名是什么?
String substring = realPath.substring(realPath.indexOf("\\") + 1);
//3.设置想办法让浏览器能够支持下载我们需要的资源
resp.setHeader("Content-Disposition","attachment;filename"+ URLEncoder.encode(substring,"utf-8"));
//4.获取下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
//5.创建缓冲区
byte[] bytes = new byte[1024];
int len;
//6.获取输出流对象
ServletOutputStream outputStream = resp.getOutputStream();
//7.文件输出流写入到缓冲区
while ((len = fileInputStream.read(bytes))!=-1){
outputStream.write(bytes);
}
//8.使用输出流讲缓冲区中的数据输入到客户端
outputStream.close();
fileInputStream.close();
}
}
验证码实现
package test;
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 doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//告诉浏览器每五秒刷新一次
resp.setHeader("refresh","5");
//在内存中创建图片
BufferedImage bufferedImage = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();//生成画笔工具
graphics.setColor(Color.white);//设置画笔颜色白色
graphics.fillRect(0,0,80,20);//画出一个矩形图片宽80高20再0,0位置
//生成随机数
graphics.setColor(Color.BLUE);//设置画笔颜色蓝色
graphics.setFont(new Font(null,Font.BOLD,20));//设置字体
graphics.drawString(makeInt(),0,20);//画出String
resp.setContentType("image/jpeg");//告诉浏览器响应类型
resp.setDateHeader("expires",-1);//告诉浏览器数据不缓存
resp.setHeader("Cache-Control","no-cache");//缓存控制,不缓存
resp.setHeader("Pragma","no-cache");
//使用ImageIO写出image对象
ImageIO.write(bufferedImage,"jpeg",resp.getOutputStream());
}
public String makeInt(){
Random random = new Random();
int i = random.nextInt(9999999);
String s = "" + i;
StringBuffer buffer = new StringBuffer();
for (int j = 0;j < 7-s.length();j++){
int nextInt = random.nextInt(10);
String s1 = nextInt + "";
buffer.append(s1);
}
s = buffer.toString() + s;
return s;
}
}
实现重定向
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/ContextTest_war/image");
}//重定向,实现请求转发

等价于
resp.setHeader("Location","/ContextTest_war/image");
resp.setStatus(302);
<html>
<body>
<h2>Hello World!</h2>
<form action="${pageContext.request.contextPath}/login" method="get">
<input type="text" name="username"> username
<input type="password" name="password"> password
<input type="submit">
</form>
</body>
</html>
package test;
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 doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("login");
resp.setHeader("Location","/ContextTest_war/image");
resp.setStatus(302);
System.out.println(req.getParameter("username"));
System.out.println(req.getParameter("password"));
}
}
javawebServlet的更多相关文章
- eclipse-maven安装配置java-web-servlet
eclipse-maven安装配置java-web-servlet 系统说明: win7 64位 一. Maven安装 环境 要求 看Maven下载说明也行 jdk7.0以上 安装配置Maven 下载 ...
- 2017.11.7 JavaWeb------Servlet过滤器
JavaWeb------Servlet过滤器 (1)过滤器是web服务器上的组件,它们对客户和资源之间的请求和响应进行过滤.Servlet 过滤器可以动态地拦截请求和响应,以变换或使用包含在请求或响 ...
- JavaWeb--Servlet部分笔记
1.集群:数万个服务器协同工作 2.web应用核心组件:jsp和servlet(属于门户),都在web容器中执行 3.web客户端发http请求(大的字符串)给web服务器:web服务器根据头信息来定 ...
- Javaweb---Servlet过滤器
Servlet过滤器从字面上的字意理解为景观一层次的过滤处理才达到使用的要求,而其实Servlet过滤器就是服务器与客户端请求与响应的中间层组件,在实际项目开发中Servlet过滤器主要用于对浏览器的 ...
- javaWeb---Servlet
1.整个Servlet页面跳转访问流程: 1.1:依据form表单的action的值找到web.xml中servlet-mapping的url的值找到对应的java类,在根据form中的method属 ...
- javaWeb-Servlet工作原理
1.客户发出请求—>Web 服务器转发到Web容器Tomcat: 2.Tomcat主线程对转发来用户的请求做出响应创建两个对象:HttpServletRequest和HttpServletRes ...
- JavaWeb-Servlet开发2
---恢复内容开始--- ServletConfig 配置Servlet初始化参数 在Servlet的配置文件web.xml中,可以使用一个或多个<init-param>标签为servle ...
- javaweb-servlet生成简单的验证码
package com.serv; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedIma ...
- javaweb-servlet获取给定文件在服务器上的绝对路径的方法
1.通过ServletContext获取 在tomcat5,6,7版本中我们可以通过ServletContext来获取给定文件在服务器上的绝对路径. ServletContext context = ...
- JavaWeb--Servlet 详解
一.基本概念 Servlet是运行在Web服务器上的小程序,通过http协议和客户端进行交互.这里的客户端一般为浏览器,发送http请求(request)给服务器(如Tomcat).服务器接收到请求后 ...
随机推荐
- .NET 6学习笔记(7)——ASP.NET Core通过配置文件启用HTTPS
本质上我还是一个Windows App Developer,所以虽然会做一些ASP.NET Core的工作,但通常这些ASP.NET Core的程序会托管在Windows Service上,并且大部分 ...
- Idea移除和删除模块
移除:右键模块-remove moduel 删除:在移除操作后 右键模块-delete 然后删除项目pom文件里面的<moduel>
- 使用SpringBoot简单实现WebRTC群聊会议室(Mesh方案)
近期需要做一个类似会议室功能,但网络上大多数是一对一通信,故记录分享希望帮助到有用的人 WebRTC一对一聊天原理 关于WebRTC建立一对一聊天的模板网上很多,可参考以下博客:springboot+ ...
- 【TS】枚举
ts中,枚举类型就是,枚举里面的每个数据值都可以叫做元素,每个元素都有自己的编号,编号是从0开始的,依次递增加1 , 语法: enum 枚举名 {} 此处定义一个枚举类型,例如: enum Color ...
- 安卓逆向 利用JEB进行动态调试断点 进行内购
1.第一步肯定是需要配置好,连接到模拟器 2.这个程序会弹出支付失败 所以我们搜索一下关键字 看到这里就很兴奋了 我们取JEB里面对这个方法进行断点 if eqz 等于0 这里 看到那个寄存器是v5 ...
- TCP/IP协议(4): 地址解析协议(ARP) —— 网络地址转换为物理地址的方式
TCP/IP协议(4): 地址解析协议(ARP)--网络地址转换为物理地址的方式 关于地址解析协议(Address Resolution Protocol, ARP) 关于 ARP 地址解析协议(Ad ...
- JZOJ 3242. Spacing
\(\text{Analysis}\) 最大值最小很容易想到二分答案 然后用 \(dp\) 检查 设 \(f_i\) 表示当前行最后一个为 \(i\) 时最优情况最大空格数是否小于 \(mid\) 若 ...
- cximage总括功能讲解
CxImage的功能 Constructors 构造函数 Initialization 初始化 File 文件操作,主要是编解码 Generic 图像基本变化 DSP 图像处理操作 Paintin ...
- LCD1602液晶屏(续)
从前面的分析中知道,在HD44780控制芯片忙的时候,是不能对其进行写入操作的,所以在写入指令或数据时都需要进行判忙的操作,其时序如下图所示(8位数据模式). 从上图中可看到,当HD44780在执行内 ...
- 学习操作系统P3 多处理器编程:从入门到放弃 (线程库;现代处理器和宽松内存模型)
啊 啊 啊 啊 操作系统会自动把线程放置在不同的处理器上 可以用top观察CPU使用率 啊 啊 啊 啊 a 甚至连一个简单的求和程序都做不对 a 汇编语言中的 lock: CPU的特性,通过总线加锁, ...