Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,具有独立于平台和协议的特性,主要功能在于交互式地浏览和生成数据,生成动态Web内容。
狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。Servlet运行于支持Java的应用服务器中。从原理上讲,Servlet可以响应任何类型的请求,但绝大多数情况下Servlet只用来扩展基于HTTP协议的Web服务器。
图解Servlet接口、HttpServlet、GenericServlet三者关系
//将项目中自带web.xml中的内容,替换为以下内容
<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>
public class HelloWeb extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("你好呀,世界");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
为什么需要映射:我们写的是JAVA程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要再web服务中注册我们写的Servlet,还需给他一个浏览器能够访问的路径
<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>helloservlet-name>
<servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
//配置Servlet请求路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
web-app>
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
即在:在 ->http://localhost:8080/<-后输入hello,便可以进入“你好呀,世界”页面
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/turl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/surl-pattern>
servlet-mapping>
即在:在 ->http://localhost:8080/<-后输入hello、t、s,便可以进入“你好呀,世界”页面
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hello/*url-pattern>
servlet-mapping>
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/*url-pattern>
servlet-mapping>
注意,这种情况下Web服务器会直接响应“你好呀,世界”,这个页面
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.practice.javaweb01.HelloWebservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
即在:在 ->http://localhost:8080/<-后输入以“.do”为后缀的数据,便可以进入“你好呀,世界”页面
已经指定的(确定的)Mapping映射路径优先级最高,若找不到映射页面,则走默认的Mapping映射路径
ServletContext:web容器在启动的时候,会为每个web程序都创建一个对应的ServletContext对象,代表当前的web应用;
即在一个Servlet中保存的数据,在另外一个servlet中拿到数据
ServletContext context = this.getServletContext(); //获取context对象
context.setAttribute("username","张三丰"); //向context中存放数据
String username = (String) context.getAttribute("username"); //获取context中的数据
具体实现类
//保存数据请求路径配置
<servlet>
<servlet-name>saveservlet-name>
<servlet-class>com.practice.javaweb02.Contextservlet-class>
servlet>
<servlet-mapping>
<servlet-name>saveservlet-name>
<url-pattern>/saveurl-pattern>
servlet-mapping>
////获取数据请求路径配置
<servlet>
<servlet-name>getsaveservlet-name>
<servlet-class>com.practice.javaweb02.getContextservlet-class>
servlet>
<servlet-mapping>
<servlet-name>getsaveservlet-name>
<url-pattern>/getsaveurl-pattern>
servlet-mapping>
public class Context extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.setAttribute("username","张三丰");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
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);
}
}
注意:应先保存数据后,在获取数据,否则数据为空
<context-param>
<param-name>urlparam-name>
<param-value>jdbc:mysql//mysql:3306param-value>
context-param>
public class init extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print("url:"+url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>disservlet-name>
<servlet-class>com.practice.javaweb02.Dispservlet-class>
servlet>
<servlet-mapping>
<servlet-name>disservlet-name>
<url-pattern>/dispathurl-pattern>
servlet-mapping>
public class Disp extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.getRequestDispatcher("/c").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注:请求,转换URL路径不会发生改变
注:A请求的东西在C处,所以A告诉B自己所需的东西后,B向C请求资源,得到资源后响应给A,所以url路径不会发生变化
具体实现类
public class Pro extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
InputStream in = context.getResourceAsStream("/WEB-INF/classes/pro.propertise");
Properties properties = new Properties();
properties.load(in);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("姓名:"+username+"\t"+"密码:"+password+"\t"+"路径:"+url);
}
}
//设置下载文件响应头,为避免中文乱码,使用URLEncoder.encode(filename,"utf-8"),参数一下载文件名,参数二编码
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
注:为避免中文乱码,使用URLEncoder.encode(filename,“utf-8”)来加工下,参数一:下载文件名,参数二:编码类型
public class Resp extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取资源绝对路径
String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/路飞.jpg");
//2.获取下载文件名
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
//3.设置下载文件响应头,为避免中文乱码,使用URLEncoder.encode(filename,"utf-8"),参数一下载文件名,参数二编码
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
//4.获取输入流
FileInputStream input = new FileInputStream(realPath);
//5.创建缓冲区
int len=0;
byte[] buffer = new byte[1024];
//6.获取输出流,将资源写入客户端
ServletOutputStream output = resp.getOutputStream();
while((len=input.read(buffer))!=-1){
output.write(buffer,0,len);
}
//7. 关闭流
input.close();
output.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
相关头的配置
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
具体实现类
public class down_Im extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.定期5秒刷新网页
resp.setHeader("refresh","3");
//2.生成照片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//3.获取2D画笔,设置背景颜色
Graphics2D g = (Graphics2D) image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,80,20);
//4.设置字体相关配置
g.setColor(Color.BLUE);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//5.设置响应类型
resp.setContentType("image/jpeg");
//6.设置缓存响应头,缓存控制,以及Pragma,作用:避免占用web资源
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//7.将图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
//生成7位数验证码
private String makeNum(){
Random random = new Random();
String num = random.nextInt(9999999) + "";
//确保生成7位数的随机数
StringBuffer s = new StringBuffer();
for (int i = 0; i < 7-num.length(); i++) {
s.append("0");
}
num=s.toString()+num;
return num;
}
}
public class sD extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/d");
}
}
HttpServletRequest :HttpServletRequest代表客户端请求,用户通过http协议访问服务器,http请求中的所有信息会被封装在HttpServletRequest对象中,通过使用该对象的方法,可以获得请求的所有信息
req.getRequestDispatcher("/success.jsp").forward(req,resp);
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录title>
head>
<body>
<h1>注册h1>
<form action="${pageContext.request.getContextPath()}/login" method="post">
用户名: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
爱好: <input type="checkbox" name="hobby" value="电影">电影
<input type="checkbox" name="hobby" value="阅读">阅读
<input type="checkbox" name="hobby" value="跑步">跑步 <br>
<input type="submit" name="注册">
form>
body>
html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<h1 style="color: aqua">成功h1>
body>
html>
public class requ extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
String username = req.getParameter("username");
String password = req.getParameter("password");
String hobby = Arrays.toString(req.getParameterValues("hobby"));
System.out.println("姓名:"+username+"\t"+"密码:"+password+"\t"+"爱好:"+hobby);
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}