JavaWeb入门
项目结构
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">
</web-app>
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.william</groupId>
<artifactId>javaweb-maven-01</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 项目的打包方式:
jar: java项目
war: javaweb项目
-->
<packaging>war</packaging>
<name>javaweb-maven-01 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<!-- 配置-->
<properties>
<!-- 项目的默认构建编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 编码版本-->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!-- 项目依赖 从仓库中下载jar包的信息-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 项目构建的信息-->
<build>
<finalName>javaweb-maven-01</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Servlet
mapping
<!-- 注册servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.william.servlet.HelloServlet</servlet-class>
</servlet>
<!-- servlet请求的映射名和请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
ServletContext
// GetContext.class
public class GetContext extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("名字:" +username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
// HelloServlet.class
public class HelloServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = "william";
context.setAttribute("username", username);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
HttpServletReponse
负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setBufferSize(int var1);
常用响应的状态码
int SC_OK = 200;
int SC_MULTIPLE_CHOICES = 300; // 重定向
int SC_NOT_FOUND = 404;
int SC_BAD_GATEWAY = 502; // 网关错误
常见应用
向浏览器发送消息
下载文件
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取文件的下载路径
// String realPath = this.getServletContext().getRealPath("/1.png"); 这个路径是web服务器(Tomcat)下的路径,找不到目标文件
String realPath = "D:\\MyProject\\javeweb-servlet-01\\response\\target\\classes\\1.png";
System.out.println("文件的下载路径是" + realPath);
//2.下载的文件名
String fileName = realPath.substring(realPath.lastIndexOf("//") + 1);
/* 小技巧: 用lastIndexOf找出文件路径最后一个/的下标+1后
得到文件名第一个字的下标后使用substring得出文件名*/
//3.设置浏览器响应头
resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
//4.获取文件的输入流
FileInputStream in = new FileInputStream(realPath);
//5.创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//7.将FileInputStream流写入缓冲区,使用ServletOutputStream将缓冲区数据输出到客户端
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
//9.关闭流
out.close();
in.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
应用:生成验证码图片
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置浏览器自动刷新
resp.setHeader("refresh","5");
//在内存中创建一个图片对象
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
//得到笔
Graphics2D graphics = (Graphics2D) image.getGraphics();
//设置笔的颜色,填充图片背景
graphics.setColor(Color.WHITE);
graphics.fillRect(0,0,80,20);
//写字
graphics.setColor(Color.BLACK);
graphics.setFont(new Font(null, Font.BOLD,20));
graphics.drawString(makeNum(), 0, 20);
//设置浏览器
resp.setContentType("image/jpeg");
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("pragma", "no-cache");
//把图片写给浏览器
ImageIO.write(image, "jpeg", resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
/*生成随机数*/
private String makeNum() {
Random random = new Random();
String num = random.nextInt(9999999) + "";
StringBuffer stringBuffer = new StringBuffer();
//保证返回的字符串是7位
for (int i = 0; i < 7 - num.length(); i++) {
stringBuffer.append("0");
}
num = stringBuffer.toString() + num;
return num;
}
}
重定向
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/response_war/image");
/*
相当于
resp.setHeader("Location","/response_war/image");
resp.setStatus(HttpServletResponse.SC_FOUND);
*/
}
重定向和转发的区别
相同
- 页面都会实现跳转
不同点
- 请求转发时,URL不会变 307
- 重定向,URL会改变 302
HttpServletRequest
package com.william.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.util.Arrays;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//防止中文乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
//多个属性用getParameterValues()获取
String[] hobbies = req.getParameterValues("hobbies");
System.out.println("================================");
System.out.println("username = " + username);
System.out.println("password = " + password);
System.out.println("hobbies = " + Arrays.toString(hobbies));
System.out.println("================================");
//通过请求转发实现跳转
// /代表当前web应用
req.getRequestDispatcher("/success.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Cookie Session
保存会话的两种技术
Cookie
- 客户端技术
Session
- 服务器技术
package com.william;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
//保存用户上一次登录的时间
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
//服务端从客户端获取cookie
Cookie[] cookies = req.getCookies();
//判断cookie是否为空
if (cookies != null) {
out.print("last login time: ");
for (Cookie cookie : cookies) {
if (cookie.getName().equals("last_time")) {
String value = cookie.getValue();
// cookie值转换为时间输出
long l = Long.parseLong(value);
Date date = new Date(l);
out.print(date.toString());
}
}
} else {
out.print("this is your first time for login");
}
// 第一次访问则服务器给客户端一个cookie
// 不是第一次也更新cookie
Cookie cookie = new Cookie("last_time", System.currentTimeMillis() + "");
//设置cookie有效期
cookie.setMaxAge(24 * 60 * 60);
//设置有效期为0则删除
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
JSP
基本语法
<%--JSP表达式用于将程序的输出输出至客户端--%>
<%= new java.util.Date()%>
<%--JSP脚本片段--%>
<%
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += i;
}
out.print("<h1>sum=" + sum + "</h1>");
%>
JSP声明
会将代码转换为生成的类中.
其他的会生成到_jspService方法中
<%!
static {
System.out.println("entry servlet");
}
%>
Filter过滤器
导包
编写过滤器
- 实现接口
- 重写方法
- 在web.xml中注册
Listener监听器
与过滤器类似