编写一个servlet程序分成两步:1.编写普通类;2.编写HttpServlet
简单的引例
1.编写HelloServlet.java
package MyExercise;
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 HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer=resp.getWriter();
writer.write("Hello,World!");
}
}
作用:在响应回来的页面输出“Hello,World!”
2.在web.xml编写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">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>MyExercise.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/h</url-pattern>
</servlet-mapping>
</web-app>
作用:要实现网页的访问必须有servlet映射,这样能帮助服务器找到对应的实现类
tips:两个servlet-name的内容要完全一致;servlet-class是写的servlet类所在路径;url-pattern是要在浏览器访问的路径
3.配置tomcat加载war包并运行
运行结果:
servlet原理图
说明:
HttpServletRequest继承自 ServletRequest。客户端浏览器发出的请求被封装成为一个HttpServlet Request对象。对象包含了客户端请求信息包括请求的地址,请求的参数,提交的数据,上传的文件客户端的ip甚至客户端操作系统都包含在其内。
HttpServletResponse是ServletResponse的子接口,HttpServletResponse对象的主要功能用于服务器对客户端的请求进行响应。
service方法中形参接收的是HttpServletResponse接口的实例化对象,这个对象中封装了向客户端发送数据,发送响应头,发送状态码的方法。
mapping问题
1.一个servlet类可以指定多个映射路径,即可通过不同的<url-class>都可以访问同一网页,
2.含有通配符*的路径优先级问题:
如果某个url-class是/h1/*,另一个url-class是/h1/hello,
当我们在浏览器输入localhost:8080/h1/hello时候,浏览器会优先访问url-class是/h1/hello对应的servlet类(更具体的路径)
ServletContext对象的介绍和应用
ServletContext对象介绍:
web容器启动时会给每一个web程序都创建一个对应的servletcontext对象,用来管理当前所有的servlet类,作用是可以实现不同servlet类间的数据共享。
ServletContext对象应用:
1.数据共享:
测试在servlet1设置的数据能否被servlet2拿到
编写servlet类(一个set一个get):
package MyExercise;
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 Servlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context=this.getServletContext();
String name="xiaoming";
context.setAttribute("username",name);//将数据放入context中,username相当于key,name相当于value
}
}
package MyExercise;
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 Servlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context=this.getServletContext();
String name=(String) context.getAttribute("username");//object向下强制转型
PrintWriter w=resp.getWriter();
w.write("成功拿到了username:"+name);
}
}
配置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">
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>MyExercise.Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>MyExercise.Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
运行结果:
2.获取web.xml中配置的参数
web.xml中设置参数和路径映射:
<web-app>
<context-param>
<param-name>url</param-name>
<param-value>复习一遍:jdbc:mysql://localhost:3306/mydb</param-value>
</context-param>
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>MyExercise.getParam</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
</web-app>
编写servlet类:
package MyExercise;
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 getParam extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
ServletContext context=this.getServletContext();
String url=context.getInitParameter("url");
PrintWriter w=resp.getWriter();
w.write("成功获取param:"+url);
}
}
启动tomcat获得运行结果:
3.读取生成的target文件下的Properties的内容
首先在db.properties中设置内容:
观察发现启动tomcat后其存在target->WEB-INF->classes下:
编写servlet类:
思路是需要一个文件流
public class getProperty extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context=this.getServletContext();
InputStream is=context.getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop=new Properties();
prop.load(is);//下载
String username=prop.getProperty("username");
String pwd=prop.getProperty("password");
PrintWriter w=resp.getWriter();
w.write("user:"+username);
w.write("pwd:"+pwd);
}
}
配置web.xml并启动tomcat得到运行结果:
4.请求转发
public class Test_RequestDispatcher extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context=this.getServletContext();
RequestDispatcher requestDispatcher=context.getRequestDispatcher("/gp");//重定向到映射路径为/gp的页面
requestDispatcher.forward(req,resp);
}
}
运行结果:
请求转发和重定向的区别
相同点:
都会跳转页面
不同点:
请求转发路径url不会变化
重定向url改变
重定向实例:
编写一个表单Login.jsp,我们要实现的是在请求servlet类的映射路径时跳转到此表单
<%--
Created by IntelliJ IDEA.
User: joyyiyi
Date: 2023/4/5
Time: 15:20
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%-- 注意这里的action要和web.xml注册的保持一致-%>
<%----%>
<h1>登录页面</h1>
<form action="/lin" method="get">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
编写servlet类
public class Test_sendRedirect extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/Login.jsp");
}
}
这里的斜杠‘/’是重点,表示当前路径,在tomcat设置了怎样的当前路径在重定向的时候也要加上
运行结果:
我输入的路径是:http://localhost:8088/sr
然后重定向跳转到页面:http://localhost:8088/Login.jsp
扩展:
通过response下载图片:
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.要获取下载图片的路径
//2.下载的文件名
//3.让浏览器能够支持我们下载的一些东西
//4.获取下载图片的输入流
//5.放入缓冲区
//6.获取outputstream对象
//7.将fileoutputstream流写入到buffer缓冲区
//8.关闭资源
String path="D:\\apache_maven_projects\\javaweb-filter\\src\\main\\resources\\img.png";//这是图片的绝对路径
String filename=path.substring(path.lastIndexOf("//")+1);
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
FileInputStream fis=new FileInputStream(path);
int len=0;
byte[] buffer=new byte[1024];
//这里和 PrintWriter w=resp.getWriter();异曲同工
ServletOutputStream out=resp.getOutputStream();
while ((len=fis.read(buffer))>0){
out.write(buffer,0,len);
}
fis.close();
out.close();
}
}
记得配置web.xml
运行结果:只有输入网页路径就自动下载请求的图片
今天记录到这,玩去了!!!!
版权归原作者 醒醒起来学习 所有, 如有侵权,请联系我们删除。