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).服务器接收到请求后 ...
随机推荐
- 六、python基础知识之变量常量、索引取值和PEP8规范
目录 一.变量与常量 1.什么是变量? 2.什么是常量? 变量的基本使用 变量使用的语法结构与底层原理 变量名的命名规范和命名风格 变量的命名风格 常量的基本使用 二.索引取值 三.PEP8规范 1. ...
- DBSCAN学习笔记
基本概念 核心点:若某个点的密度达到算法设定的阈值,即ε-邻域内点的数量(包括自己)不小于minPts,则该点为核心点. 边界点:在ε-邻域内点的数量小于minPts,但是落在核心点邻域内的点. 噪声 ...
- 聊聊火热的 ChatGPT(我帮大伙问了几个比较关心的问题)
如需要转载,请声明原文链接微信公众号「ENG八戒」https://mp.weixin.qq.com/s/L9tZy_KWnE1kf0E3HNhJhQ 本文大概 2562 个字,阅读需花 15 分钟 内 ...
- springboot如何在拦截器中拦截post请求参数以及解决文件类型上传问题
我们经常有这样一个场景,比如:在springboot拦截器中想截取post请求的body参数做一些中间处理,或者用到自定义注解,想拦截一些特定post请求的方法的参数,记录一些请求日志. 想到了使 ...
- 使用xamarin开发Android、iOS报错failed to open directory: 系统找不到指定的文件
使用vs2019学习xamarin时,创建新程序.使用模拟器真机等测试都报错如下图错误: 调整AndroidManifest.xml和设备调试属性,打开[Android SDK和工具]安装可能需要的S ...
- 图说论文《An Empirical Evaluation of In-Memory Multi-Version Concurrency Control》
本文从< An Empirical Evaluation of In-Memory Multi-Version Concurrency Control>摘取部分图片,来介绍 MVCC. 该 ...
- 智能指针 shared_ptr weak_ptr shared_from_this 笔记
shared_ptr 当指向对象的std::shared_ptr一创建,被管理对象的控制块SharedPtrControlBlock(参考下面的图)就建立了. 被管理的对象的控制块中有引用计数(ref ...
- Kronecker convolution 克罗内克卷积理解
在了解空洞卷积时候发现了Kronecker convolution是对空洞卷积的改进,于是学习了一下 ,原文连接:1812.04945v1.pdf (arxiv.org) 个人理解如下: 首先,对于一 ...
- Supported OPs and DPU Limitations
Currently Supported Operators source:https://www.xilinx.com/html_docs/xilinx2019_2/vitis_doc/zmw1606 ...
- 简单使用wireshark
wireshark抓包工具 拓扑图: 拓扑图解释:终端用户使用wireshark抓包工具监听无线网卡,监听时,终端访问互联网,可实时监听网络抓包 操作步骤: 一,打开wireshark抓包工具,监听网 ...