狂神说Java
把实现了Servlet接口的java程序叫做,Servlet
Servlet接口sun公司有两个默认实现类:HttpServlet,
1.构建一个普通的Maven项目,删掉里面的src目录,就在这个项目里面建立Module。
这个空的工程就是Maven主工程;pom.xml中可以添加servlet、jsp依赖
2.关于Maven父子工程的理解:
父项目中会有:
<modules>
<module>servlet-01module>
modules>
子项目中会有:
<parent>
<artifactId>javaweb-02-servletartifactId>
<groupId>com.xpcccccgroupId>
<version>1.0-SNAPSHOTversion>
parent>
3.编写一个Servlet程序
1.编写一个普通类
2.实现Servlet类,我们直接继承HttpServlet类
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入doGet方法");
PrintWriter writer = resp.getWriter();//响应流
writer.print("Hello,Servlet!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
5.编写Servlet映射
为什么需要编写映射:我们写的是Java程序但是需要通过浏览器进行访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的Servlet,还需给他一个浏览器能访问的路径
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.xpccccc.servlet.HelloServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
6.配置Tomcat
注意配置项目发布的路径就可以了(Tomcat 10可能访问不到500,可以使用Tomcat 9)
7.启动测试
出现以下则成功
一个Servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
一个Servlet可以指定多个映射路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hello1url-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hello2url-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hello3url-pattern>
servlet-mapping>
一个Servlet可以指定通用映射路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hello/*url-pattern>
servlet-mapping>
默认请求路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/*url-pattern>
servlet-mapping>
指定一些后缀或前缀等等
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>*.xupengurl-pattern>
servlet-mapping>
可以自定义后缀实现请求路径
注意:*前面不能加项目映射的路径(/hello/hsdbgcjhsd.xupeng 错误)
优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求
<servlet>
<servlet-name>errorservlet-name>
<servlet-class>com.xpccccc.servlet.ErrorServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>errorservlet-name>
<url-pattern>/*url-pattern>
servlet-mapping>
Web容器在启动的时候,他会为每个web程序创建一个对应的ServletContext对象,他代表了当前的web应用;
我们在这个Servlet中保存的数据,可以在另一个Servlet中拿到
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Hello");
//this.getServletContext() Servlet上下文
ServletContext context = this.getServletContext();
String username="徐鹏";
context.setAttribute("username",username);//(类似键值对)
}
}
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String username = (String)servletContext.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);
}
}
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.xpccccc.servlet.HelloServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
<servlet>
<servlet-name>getcservlet-name>
<servlet-class>com.xpccccc.servlet.GetServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>getcservlet-name>
<url-pattern>/getcurl-pattern>
servlet-mapping>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
<context-param>
<param-name>urlparam-name>
<param-value>jdbc:mysql://localhost:3306/mybatisparam-value>
context-param>
servlet>
<servlet-mapping>
<servlet-name>gpservlet-name>
<url-pattern>/gpurl-pattern>
servlet-mapping>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
System.out.println("进入了ServletDemo04");
context.getRequestDispatcher("/gp").forward(req,resp);//请求转发
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
<servlet>
<servlet-name>sd4servlet-name>
<servlet-class>com.xpccccc.servlet.ServletDemo04servlet-class>
servlet>
<servlet-mapping>
<servlet-name>sd4servlet-name>
<url-pattern>/sd4url-pattern>
servlet-mapping>
Properties
发现:都被打包到同一个路径下:classes,我们俗称这个路径为classpath
思路:需要一个文件流
username=root
password=123445
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/xpccccc/servlet/aa.properties");
Properties prop = new Properties();
prop.load(is);
String usr = prop.getProperty("username");
String psd = prop.getProperty("password");
resp.getWriter().print(usr+":"+psd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>downservlet-name>
<servlet-class>com.xpccccc.servlet.FileServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>downservlet-name>
<url-pattern>/downurl-pattern>
servlet-mapping>
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、获取下载文件的路径
System.out.println("进入FileServlet");
String realPath = "/Users/xupeng/Documents/JavaWeb/javaweb-02-servlet/response/src/main/resources/截屏2022-03-01 上午10.25.07.png" ;
System.out.println("下载的路径为:"+realPath);
//2、下载的文件名是是啥
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
//3、设置想办法让浏览器支持下载我们需要的东西
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
//4、获取下载文件的缓输入流
FileInputStream in = new FileInputStream(fileName);
System.out.println("haha");
//5、创建缓冲期
int len=0;
byte[] buffer = new byte[1024];
//6、获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//7、将FileInputStream写入到buffer
while((len=in.read(buffer))>0){
//8、使用OutputStream将缓冲区数据写到客户端
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>imageservlet-name>
<servlet-class>com.xpccccc.servlet.ImageServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>imageservlet-name>
<url-pattern>/imageurl-pattern>
servlet-mapping>
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器每2秒刷新一次
resp.setHeader("refresh","2");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics g = image.getGraphics();
//设置图片背景颜色
g.setColor(Color.white);
g.fillRect(0,0,80,20);
//给图片写数据
g.setColor(Color.blue);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//告诉浏览器,这个请求用图片的方式打开
resp.setContentType("image/jpeg");
//网站存在缓存,不让浏览器缓存
resp.setHeader("Cache-Control","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生产随机数
public String makeNum(){
Random r = new Random();
String num=r.nextInt(9999999)+"";//生成7位数验证码
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 7-num.length(); i++) {
sb.append("0");
}
num=sb.toString()+num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
一个web资源收到客户端的请求后,他会通知客户端去访问另外一个web资源,这个过程叫重定向
常见场景:
用户登录
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
resp.setHeader("Location","/r1/image");
resp.setStatus(302);
* */
resp.sendRedirect("/r1/image");//重定向
}
重定向和转发的区别
相同点:页面都会跳转
不同点:
<servlet>
<servlet-name>requestservlet-name>
<servlet-class>com.xpccccc.servlet.RequestServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>requestservlet-name>
<url-pattern>/loginurl-pattern>
servlet-mapping>
Hello World!
<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}这个代表当前项目--%>
这里注意,web2.3不支持${pageContext.request.contextPath},所以在web.xml更新为更高的4.0版本
<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>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入这个请求了");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username+":"+password);
//重定向时候一定要注意路径问题,否则404
resp.sendRedirect("/r1/success.jsp");
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
Success
HttpServletRequest代表了客户端的请求,用户通过Http协议服务器,Http请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息
<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>LoginServletservlet-name>
<servlet-class>com.xpccccc.servlet.LoginServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>LoginServletservlet-name>
<url-pattern>/loginurl-pattern>
servlet-mapping>
web-app>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
登录
登录
<%--这里表单的意思是,以post方式提交表单,提交到我们的login请求--%>
@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");
String[] hobbies = req.getParameterValues("hobbies");
System.out.println("======================");
System.out.println(username);
System.out.println(password);
System.out.println(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);
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
登录成功