一.服务器:装有服务器软件的计算机
数据库服务器:装有MySql软件的计算机。
Web服务器:装有Web服务器软件的计算机,用于接收请求,处理请求,响应请求。
二.http协议---超文本传输协议:1)浏览器往服务器发送 ---- 请求;2)服务器往浏览器回写 ---- 响应
1)请求(request)----请求行,请求头,请求体
1.请求行:请求信息的第一行(格式:请求方式<get和pos> 访问的资源 协议/版本 举例:GET /day0801/1.html HTTP/1.1)
2.请求头:请求信息的第二行到空行结束(格式:key/value (value可以是多个值))
3.请求体:空行以下的内容(只有post才有请求体 get请求参数拼接在URL后面)
2)响应(response)---响应行 响应头 响应体
1.响应行:响应信息的第一行(格式:协议/版本 状态码 状态码说明 例如:HTTP/1.1 200 OK)
状态码:200----正常响应成功;302----重定向;304----读缓存;404----用户操作资源不存在;500----服务器内部异常。
2.响应头:从响应信息的第二行到空行结束(格式:key/value(value可以是多个值))
3.响应体:空行以下的内容
三.Servlet
1)步骤:
(1)创建web项目
(2)定义一个Java类,实现Servlet接口
(3)重写所有未实现方法
(4)配置Servlet,在web.xml
<!-- 配置Servlet,为了配置Servlet的访问路径 -->
<servlet>
<servlet-name>demo1</servlet-name>
<servlet-class>org.westos.servlet.ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo1</servlet-name>
<!-- 设置访问路径,以/开头 -->
<url-pattern>/demo</url-pattern>
</servlet-mapping>
(5)发布项目
(6)访问/demo路径访问该Servlet
2)Servlet中的五个需要被实现的方法
public class ServletDemo implements Servlet {
// 当Servlet被创建时调用,而且只调用一次
public void init(ServletConfig config) throws ServletException {
System.out.println("Servlet被创建了");
}
// 对外提供服务的方法,每一次请求时都会调用该方法
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
System.out.println("请求来了");
}
// 获取配置对象
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
// 获取Servleet版本,作者等信息
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
// 当Servlet被销毁时调用
public void destroy() {
System.out.println("Servlet被销毁了");
}
3)ServletConfig--配置对象
/*
* 让服务器一开始就进行初始化的方法: 再web.xml中配置---<load-on-startup>0</load-on-startup>
* 它的默认值是-1,即在第一次请求时才调用init()方法,如果是非负整数 服务器开启时就会调用 init()方法
*/
public void init(ServletConfig config) throws ServletException {
// ServletConfig--配置对象:是一个接口,子类对象由服务器创建,当服务器调用init()方法时作为参数传递
// 配置对象的作用:
// 1.获取web.xml中配置的初始化参数
// 方式一:config.getInitParameter(name)
String name = config.getInitParameter("username");
System.out.println(name);
String age = config.getInitParameter("age");
System.out.println(age);
System.out.println("--------------------------");
// 方式二: config.getInitParameterNames()
Enumeration<String> values = config.getInitParameterNames();
while (values.hasMoreElements()) {
String key = values.nextElement();
String value = config.getInitParameter(key);
System.out.println(value);
}
}
public void init(ServletConfig config) throws ServletException {
// ServletConfig--配置对象
// 作用2:获取全局域对象:config.getServletContext()
// ServletContext--全局上下文对象(一个域<域:范围>对象):是一个接口,他的子类对象由服务器创建
ServletContext context = config.getServletContext();
// 在域中存储数据
context.setAttribute("num", "100");
// 获取域中的数据
String value = (String) context.getAttribute("num");// 100
// 清除域中的数据
context.removeAttribute("num");
// 获取域中的数据
String value2 = (String) context.getAttribute("num");// null
System.out.println(value);// 100
System.out.println(value2);// null
// 作用3:获取Web.xml 配置的Servlet的名字 :config.getServletName()
String name = config.getServletName();
System.out.println(name);// myDemo2
}
4)ServletContext---
全局上下文对象(一个域<域:范围>对象)
ServletConfig config;// 单例的
// 在Servlet 最好不要定义成员变量 因为会有线程安全问题的存在
// final int num=100;
public void init(ServletConfig config) throws ServletException {
this.config = config;
}
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return config;
}
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// ServletContext作用:
// 1.在域中的资源间共享数据
// 2.用来获取服务器的真实路径
// //读取a.txt(在WEB-INF目录下)
// File file = new File(
// "D:\\tomcat\\apache-tomcat-7.0.26\\webapps\\ServletDemo2\\WEB-INF\\a.txt");
// FileInputStream in = new FileInputStream(file);
// // 读取b.txt(WEB-Root目录下)
// File file2 = new File(
// "D:\\tomcat\\apache-tomcat-7.0.26\\webapps\\ServletDemo2\\b.txt");
// FileInputStream in2 = new FileInputStream(file2);
//
// // 读取c.txt(src目录下) \\WEB-INF\\classes\\c.txt
// File file3 = new File(
// "D:\\tomcat\\apache-tomcat-7.0.26\\webapps\\ServletDemo2\\WEB-INF\\classes\\c.txt");
// FileInputStream in3 = new FileInputStream(file3);
//
// System.out.println(in);
// System.out.println(in2);
// System.out.println(in3);
// 动态获取服务器的真实路径
ServletConfig config2 = this.getServletConfig();
ServletContext context = config.getServletContext();
String realPath = context.getRealPath("/");
System.out.println(realPath);//D:\tomcat\apache-tomcat-7.0.26\webapps\ServletDemo2\
// 读取a.txt
File file1 = new File(context.getRealPath("/WEB-INF/a.txt"));
// 读取b.txt
File file2 = new File(context.getRealPath("/b.txt"));
// 读取c.txt
File file3 = new File(context.getRealPath("/WEB-INF/classes/c.txt"));
System.out.println(file1);//D:\tomcat\apache-tomcat-7.0.26\webapps\ServletDemo2\WEB-INF\a.txt
System.out.println(file2);//D:\tomcat\apache-tomcat-7.0.26\webapps\ServletDemo2\b.txt
System.out.println(file3);//D:\tomcat\apache-tomcat-7.0.26\webapps\ServletDemo2\WEB-INF\classes\c.txt
// 调用工具类 读取文件
MyUtil.readFile();
}
四.GenericServlet--适配器(实现了Servletjie接口)
public class ServletDemo extends GenericServlet {
// 适配器
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
ServletConfig config2 = this.getServletConfig();
ServletContext context2 = config2.getServletContext();
}
}
五.HttpServlet(继承了GenericServlet,重写了service()方法)
public class ServletDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("get请求来了");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
System.out.println("post请求来了");
}
}
1)响应对象
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* request 请求对象 ; response 响应对象 请求对象和响应对象直接由服务器创建管理和销毁
*/
// PrintWriter writer = response.getWriter();
// writer.write("hello");
// writer.write("你好");//??
// 为了防止乱码,设置服务器对字符流的编码,默认服务器用的是ISO-8859-1
// response.setCharacterEncoding("utf-8");
// 告诉浏览器用相应的编码去解码
// response.setHeader("content-type", "text/html; charset=utf-8");
// 以上两行代码合并
// 设置字符打印输出流的编码,并告诉浏览器用相应的编码去解码
response.setContentType("text/html; charset=utf-8");
// 获取发送字符数据的对象
PrintWriter writer = response.getWriter();
writer.write("你好");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取图片路径
String path = this.getServletContext().getRealPath("/girl.jpg");
FileInputStream fis = new FileInputStream(new File(path));
// 获取响应对象中的字节输出流
ServletOutputStream fos = response.getOutputStream();
// 读写操作
// byte[] bys = new byte[1024];
// int len = 0;
// while ((len = fis.read(bys)) != -1) {
// fos.write(bys, 0, len);
// }
IOUtils.copy(fis, fos);
// 释放资源
fos.close();
fis.close();
}
//重定向
/*
*重定向的特点:页面跳转
* 1.两次请求,两次响应
* 2.地址栏会发生变化
* 3.可以跳转到外部站点的资源,也可以跳转到内部站点的资源
* */
public class ServletDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* //设置状态码
* response.setStatus(302);
* //通过Http协议中的响应头告诉浏览器重定向的位置
* response.setHeader("location", "http://www.baidu.com");//跳到外部站点
* response.setHeader("location", "/ServletDemo4/demo2");//跳到内部站点
*/
//以上两步合并
response.sendRedirect("http://www.baidu.com");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
2)请求对象//请求对象request 由服务器创建,管理,和销毁 用来封装请求消息
public class ServletDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取请求方法
String method = request.getMethod();// GET
// 获取URI--统一资源标识符
String uri = request.getRequestURI();// /ServletDemo4/demo2
// 获取URL--统一资源定位符
StringBuffer url = request.getRequestURL();// http://localhost:8080/ServletDemo4/demo2
// 获取协议版本
String protocol = request.getProtocol();// HTTP/1.1
System.out.println(method);
System.out.println(uri);
System.out.println(url);
System.out.println(protocol);
// 获取ip
String ip = request.getRemoteAddr();
// 获取主机名
String host = request.getRemoteHost();
// 获取端口
int port = request.getRemotePort();
System.out.println(ip);
System.out.println(host);
System.out.println(port);
String header = request.getHeader("user-agent");// 获取请求头
System.out.println(header);
// Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,
// like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
//处理get和post请求
public class ServletDemo3 extends HttpServlet {
// 处理get请求--get请求参数拼接在URL后面
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String line = request.getQueryString();
// 通过request.getQueryString()获取出来的请求参数经过了浏览器的URLEncode()编码
System.out.println(line);// usename=%E5%BC%A0%E4%B8%89&password=12345
// 通过URLDecode解码
line = URLDecoder.decode(line, "utf-8");
System.out.println(line);// usename=张三&password=124567
}
//处理post请求--post请求把请求参数封装在请求体里面
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String line = request.getReader().readLine();
System.out.println(line);//usename=%E5%BC%A0%E4%B8%89&password=12345
line = URLDecoder.decode(line, "utf-8");
System.out.println(line);//usename=张三&password=12345
}
}
//this.doGet(request, response)的由来
public class ServletDemo4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
getParment(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
// getParment(request, response);
}
private void getParment(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String method = request.getMethod();
String line = null;
if ("get".equals(method)) {
line = request.getQueryString();
} else if ("post".equals(method)) {
line = request.getReader().readLine();
}
String[] split = line.split("&");
String[] split2 = split[0].split("=");
String ukey = split2[0];
String uvalue = split2[1];
String[] split3 = split[1].split("=");
String pkey = split3[0];
String pvalue = split3[1];
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 处理中文乱码的方式(只针对post请求)
// request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
// System.out.println(username + "---" + password);//??????---12345
// 处理中文乱码的方式(get/post请求均可用)
// byte[] bytes = username.getBytes("Iso-8859-1");
// username = new String(bytes, "utf-8");
System.out.println(username + "---" + password);
}
public class ServletDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取请求参数
//方式一:
String username = request.getParameter("username");
String password = request.getParameter("password");
//复选框
String[] values = request.getParameterValues("hobby");
for(String v:values){
System.out.println(v);
}
//方式二:将请求参数的值和键全部封装进Map集合中
Map<String,String[]> map = request.getParameterMap();
Set<String> keySet = map.keySet();
for(String key:keySet){
String[] values2 = map.get(key);
for(String v:values2){
System.out.println(key+"---"+v);
}
}
//方式三
Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
String key = names.nextElement();
String v = request.getParameter(key);
System.out.println(v);
}
}
//请求转发
/*特点:
* 1.地址栏不发生变化
* 2.一次请求一次响应
* 3.只能请求内部站点的资源
* */
public class ServletDemo7 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/demo2").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
六.验证码小案例
//制作一个验证码
public class ServletDemo5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String str = "";
// 创建一个图片对象(参三--图片类型)
int width = 150;
int height = 60;
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// -------美化图片部分-------
// 获取画笔
Graphics g = img.getGraphics();
// 设置画笔的颜色
g.setColor(Color.CYAN);
// 填充背景
g.fillRect(0, 0, width, height);
// 设置边框
g.setColor(Color.BLUE);
g.drawRect(0, 0, width - 1, height - 1);
// ------图片添加文字-------
g.setColor(Color.black);
String msg = "abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
// 随机获取四个字符
Random random = new Random();
for (int i = 1; i <= 4; i++) {
// 获取随机角标
int index = random.nextInt(msg.length());
// 获取随机角标对应的字符
char ch = msg.charAt(index);
str = str + ch;
// 给图片添加文字
g.drawString(ch + "", width / 5 * i, height / 2);
}
System.out.println(str);
// ------添加干扰线-----
g.setColor(Color.RED);
for (int i = 0; i < 5; i++) {
// 获取四个随机坐标
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
ImageIO.write(img, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
My.html
<body>
<img src="/ServletDemo/demo5" id="yzm" />
<a href="javascript:void(0)" οnclick="change()">看不清换一张</a>
</body>
<script type="text/javascript">
function change() {
document.getElementById("yzm").src = "/ServletDemo3/demo5?imgpath="
+ new Date().getTime();
}
</script>