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).服务器接收到请求后 ...
随机推荐
- 我为什么要放弃RESTful,选择拥抱GraphQL
背景 REST作为一种现代网络应用非常流行的软件架构风格,自从Roy Fielding博士在2000年他的博士论文中提出来到现在已经有了20年的历史.它的简单易用性,可扩展性,伸缩性受到广大Web开发 ...
- 《Terraform 101 从入门到实践》 Terraform在公有云GCP上的应用
<Terraform 101 从入门到实践>这本小册在南瓜慢说官方网站和GitHub两个地方同步更新,书中的示例代码也是放在GitHub上,方便大家参考查看. Terraform支持的公有 ...
- Nginx11 openresty连接redis(lua-resty-redis)
1 官网 http://openresty.org/cn/lua-resty-redis-library.html https://github.com/openresty/lua-resty-red ...
- 线程基础知识 04 synchronized锁的四种状态和升级
转https://www.cnblogs.com/mingyueyy/p/13054296.html 1 轻量级锁和重量级锁简要说明 线程调度本来是由操作系统来管理的.现在,操作系统上跑了一个虚拟机J ...
- 乌卡时代的云成本管理:从0到1了解FinOps
在上一篇文章中,我们介绍了企业云业务的成本构成以及目前面临的成本困境,以及当前企业逐步转向 FinOps 的行业趋势,这篇文章我们将详细聊聊 FinOps,包括概念.重要性以及成熟度评价指标. 随着对 ...
- JZOJ 1967.【2011集训队出题】聪聪可可
题目 [2011集训队出题]聪聪可可 思路 看看做做 阴阳 这道题 极力推荐 自从做了这道题后,这些题就变成秒切的题了 很容易想到求节点到分治中心的距离,然后 \(\bmod 3\) 那么在求根节点一 ...
- knock:端口敲门服务
knock:端口敲门服务 端口敲门服务,即:knockd服务.该服务通过动态的添加iptables规则来隐藏系统开启的服务,使用自定义的一系列序列号来"敲门",使系统开启需要访问的 ...
- Vulhub 漏洞学习之:Couchdb
Vulhub 漏洞学习之:Couchdb 目录 Vulhub 漏洞学习之:Couchdb 1 Couchdb 垂直权限绕过漏洞(CVE-2017-12635) 1.1 漏洞利用过程 2 Couchdb ...
- python爬取网页的多种方式以及保存方法
爬取网页信息并保存 bs4和lxml都是用来将接收的数据解析html 1.bs4+excel(openpyxl): import requests from bs4 import BeautifulS ...
- Oracle中的sql脚本语言中的循环语句介绍
--sql脚本语言的循环介绍:--1.goto循环点.declare x number;begin x:=0;--变量初始化: <<repeat_loop>>--设置循环 ...