文章目录
- 1.ServletConfig
- 1.基本介绍
- 2.应用实例
- 1.DBServlet.java
- 2.web.xml
- 2.ServletContext
- 1.为什么需要ServletContext
- 2. 基本介绍
- 3.ServletContext 可以做什么
- 4.应用实例一_获取工程相关信息
- 1.ServletContext.java
- 2.web.xml
- 3.结果
- 5.应用实例二_完成简单网站访问计数器
- 1.PayServlet.java
- 2.OrderServlet.java
- 3.WebUtils.java
- 4.web.xml
- 5.结果
- 3.HttpServletRequest
- 1.基本介绍
- 2.常用方法
- 3.应用实例
- 1.request.java
- 2.register_request.html
- 3.结果
- 4.小练习
- 4.请求转发
- 1.为什么需要请求转发
- 2.基本介绍
- 3.示意图
- 4.请求转发实例
- 1.regsiter.html
- 2.check.java
- 3.return_.java
- 4.结果
- 5.细节说明
- 简单解释转发
- 6.关于路径的解析
- 1.浏览器发送的请求
- 2.服务器内部发送的请求
- 3.一个资源的全路径
- 7.两种乱码问题的解决
- 1.请求获取数据时的乱码问题
- 2.响应到浏览器时的乱码问题
- 8.课后作业
- 作业一
- 1.regsiter.html
- 2.GetParameters.java
- 3.答案
- 作业二
- GetNum.java
- 结果
- 5. HttpServletResponse
- 1.基本介绍
- 2.向客户端返回数据方法
- 3.请求重定向
- 1.基本介绍
- 2.示意图
- 3.请求重定向实例
- 1.down.html
- 2.DownServlet.java
- 3.DownServletNew.java
- 4.结果
- 4.细节说明
- 5.动态获取上下文路径
- 6.课后作业
- 1.pay.html
- 2.Pay.java
- 3.PayOk.java
- 4.结果
1.ServletConfig
1.基本介绍
2.应用实例
1.DBServlet.java
package ServletConfig;import javax.servlet.ServletConfig;
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;/*** @author 孙显圣* @version 1.0*/
public class DBServlet extends HttpServlet {@Overridepublic void init(ServletConfig config) throws ServletException {super.init(config);//如果重写了init方法,这行是不能注销的,因为//1.原本要调用的就是父类的init方法,并将创建的config对象给父类的config属性//2.如果在这里注销了,那么父类的config属性将不会被赋值,所以就导致了getServletConfig获取的config属性是空的}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//读取配置文件的内容ServletConfig servletConfig = super.getServletConfig(); //通过父类实现爷爷类的方法来获取servletConfigString user = servletConfig.getInitParameter("user");String pwd = servletConfig.getInitParameter("pwd");System.out.println(user + pwd);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//无论是get还是post都交给get来处理doGet(req, resp);}
}
2.web.xml
2.ServletContext
1.为什么需要ServletContext
2. 基本介绍
3.ServletContext 可以做什么
4.应用实例一_获取工程相关信息
1.ServletContext.java
package servletcontext;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** @author 孙显圣* @version 1.0*/
public class ServletContext extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//获取ServletContext对象javax.servlet.ServletContext servletContext = super.getServletContext();//获取上下文参数String name = servletContext.getInitParameter("name");String website = servletContext.getInitParameter("website");System.out.println("name:" + name + " website:" + website);//获取当前的上下文路径/servletString contextPath = servletContext.getContextPath();System.out.println("上下文路径:" + contextPath);//获取项目发布后的根路径(就是在out文件夹中的路径)String realPath = servletContext.getRealPath("/");System.out.println("发布后的根路径:" + realPath);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doGet(req, resp); //交给doget统一处理}
}
2.web.xml
3.结果
5.应用实例二_完成简单网站访问计数器
1.PayServlet.java
package servletcontext;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;/*** @author 孙显圣* @version 1.0*/
public class PayServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//获取ServletContext对象ServletContext servletContext = super.getServletContext();WebUtils.setCount(servletContext);//在显示器打印数值//首先指定编码resp.setContentType("text/html;charset=utf-8");//获取打印流PrintWriter writer = resp.getWriter();writer.print("访问网站的次数为:" + servletContext.getAttribute("count"));}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doGet(req, resp);}
}
2.OrderServlet.java
package servletcontext;import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** @author 孙显圣* @version 1.0*/
public class OrderServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//获取ServletContext对象ServletContext servletContext = super.getServletContext();WebUtils.setCount(servletContext);//在显示器打印数值//首先指定编码resp.setContentType("text/html;charset=utf-8");//获取打印流PrintWriter writer = resp.getWriter();writer.print("访问网站的次数为:" + servletContext.getAttribute("count"));}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doGet(req, resp);}
}
3.WebUtils.java
package servletcontext;import javax.servlet.ServletContext;/*** @author 孙显圣* @version 1.0*/
public class WebUtils {public static void setCount(ServletContext servletContext) {//获取数量Object count = servletContext.getAttribute("count");if (count == null) { //如果是第一次则创建一个key为count,并设置为1servletContext.setAttribute("count", 1);}else { //如果是第二次或以上,则获取里面的值并且加一Integer count_ = (Integer)count + 1;//将这个数值放到里面servletContext.setAttribute("count", count_);}}}
4.web.xml
5.结果
3.HttpServletRequest
1.基本介绍
2.常用方法
3.应用实例
1.request.java
package request;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** @author 孙显圣* @version 1.0*/
@WebServlet(urlPatterns = "/request")
public class request extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1.获取请求的信息System.out.println("请求的资源路径URI=" + req.getRequestURI());System.out.println("请求的URL=" + req.getRequestURL());System.out.println("请求的客户端ip地址=" + req.getRemoteAddr());System.out.println("请求头Host=" + req.getHeader("Host"));System.out.println("请求方式=" +req.getMethod());//getHeader可以获取请求头的任何信息//取出浏览器String header = req.getHeader("User-Agent");String[] split = header.split(" ");String s = split[split.length - 2].split("\\/")[0];System.out.println("浏览器=" + s);//2.获取表单数据//解决中文的乱码req.setCharacterEncoding("utf-8");//获取表单的单个数据String username = req.getParameter("username");String password = req.getParameter("password");//获取多个数据String[] hobbies = req.getParameterValues("hobby");System.out.println("username=" +username);System.out.println("password=" +password);System.out.print("hobby=");for (String hobby : hobbies) {System.out.print(hobby + " ");}//3.返回接受的信息到浏览器//解决中文乱码resp.setContentType("text/html;charset=utf-8"); //本质就是设置Content-Type来告诉浏览器使用什么方式和字符集解析内容PrintWriter writer = resp.getWriter();writer.print("<h1>" + "username=" + username + "</h1>");writer.flush();writer.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doGet(req, resp);}
}
2.register_request.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>注册 用户</h1>
<form method="get" action="/servlet/request">username:<input type="text" name="username">password:<input type="password" name="password"><br>选择你喜欢的老师<input type="checkbox" name="hobby" value="hsp">韩顺平<input type="checkbox" name="hobby" value="lh">老韩<input type="checkbox" name="hobby" value="spls">顺平老师<br><input type="submit" value="注册">
</form>
</body>
</html>
3.结果
4.小练习
//获取JSESSIONID的值String header1 = req.getHeader("Cookie");String s1 = header1.split(";")[0].split("=")[1];System.out.println("JSESSIONID=" + s1);
4.请求转发
1.为什么需要请求转发
2.基本介绍
3.示意图
4.请求转发实例
1.regsiter.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>使用请求转发,根据用户名判断身份</h1>
<form action="/servlet/check" method="post">username: <input type="text" name="username"><input type="submit" value="提交">
</form>
</body>
</html>
2.check.java
package request;import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** @author 孙显圣* @version 1.0*/
@WebServlet(urlPatterns = "/check")
public class check extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doGet(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//解决获取参数时的乱码,注意,一定要是在第一次获取参数之前设置编码,否则编码将以默认形式,即使在后面的转发的请求中设置编码也是没用的req.setCharacterEncoding("utf-8");String username = req.getParameter("username"); //这个请求一旦转发,则转发到的servlet是共享这个请求的所有信息System.out.println(username);//根据用户名向请求中添加信息if (username.equals("Tom")) {req.setAttribute("role", "管理员");}else {req.setAttribute("role", "普通用户");}//请求转发RequestDispatcher requestDispatcher = req.getRequestDispatcher("/return");requestDispatcher.forward(req,resp);}
}
3.return_.java
package request;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** @author 孙显圣* @version 1.0*/
@WebServlet(urlPatterns = "/return")
public class return_ extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//获取转发来的信息String role = (String) req.getAttribute("role");//这个请求和最开始浏览器向服务器发送的请求是同一个,所以依然可以获取用户名String username = req.getParameter("username");//解决服务器响应到浏览器的乱码resp.setContentType("text/html;charset=utf-8");//输出信息PrintWriter writer = resp.getWriter();writer.print("<h1>" + username + "是" + role + "</h1>");}
}
4.结果
5.细节说明
简单解释转发
- 浏览器向Tomcat服务发送请求
- Tomcat服务匹配到特定的servlet1并将请求给它
- servlet1为这个请求添加数据之后将这个请求再转发到另一个servlet2
- 此时servlet2的请求既可以获取浏览器的数据,也可以获取servlet1添加的数据
- 关于支付问题,浏览器向servlet1发送请求,servlet1完成支付,然后转发到servlet2,此时浏览器的地址是停留在servlet1的所以,一旦刷新,则浏览器还会向servlet1发送请求,导致重复支付
6.关于路径的解析
1.浏览器发送的请求
- 在发送请求之后,如果地址栏会发生变化,则是浏览器发送的请求
- 此时的“/”代表的是http://localhost:8080
- 比如,表单的提交,重定向,超链接
2.服务器内部发送的请求
- 在发送请求之后,地址栏不会发生变化,则是服务器内部发送的请求
- 此时的“/”代表的是http://localhost:8080/工程路径
- 比如,请求转发
3.一个资源的全路径
- servlet资源的全路径 = 上下文路径 + 路由
- 静态资源的路径 = 上下文路径 + /资源名(无文件夹状态)
7.两种乱码问题的解决
1.请求获取数据时的乱码问题
req.setCharacterEncoding("utf-8");
- 注意:必须是在第一次获取数据之前就设置编码,否则一旦获取了数据,就会以默认的编码为准,即使在后面再设置编码也不起作用
2.响应到浏览器时的乱码问题
resp.setContentType("text/html;charset=utf-8");
- 注意:这个也是同样道理,也是在第一次打印之前就要设置
8.课后作业
作业一
1.regsiter.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>使用请求转发,根据用户名判断身份</h1>
<form action="/servlet/check" method="post">username: <input type="text" name="username"><input type="submit" value="提交">
</form>
</body>
</html>
2.GetParameters.java
package HomeWork;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** @author 孙显圣* @version 1.0*/
@WebServlet(urlPatterns = "/getParameters")
public class GetParameters extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//设置编码req.setCharacterEncoding("utf-8");String username = req.getParameter("username");String password1 = req.getParameter("password1");String password2 = req.getParameter("password2");String[] sports = req.getParameterValues("sport");String sex = req.getParameter("sex");String city = req.getParameter("city");String text = req.getParameter("text");for (String sport : sports) {System.out.println(sport);}System.out.println(username + " \n" + password1 + "\n " + password2 + "\n " + sex + " \n" + city + " \n" + text);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doGet(req,resp);}
}
3.答案
作业二
GetNum.java
package HomeWork;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;/*** @author 孙显圣* @version 1.0*/
@WebServlet(urlPatterns = "/getnum")
public class GetNum extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String header = req.getHeader("User-Agent");String regStr = "\\((.*;.*;.*)\\).*\\(";Pattern compile = Pattern.compile(regStr);Matcher matcher = compile.matcher(header);if (matcher.find()) {System.out.println(matcher.group(1));}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}
}
结果
5. HttpServletResponse
1.基本介绍
2.向客户端返回数据方法
3.请求重定向
1.基本介绍
2.示意图
3.请求重定向实例
1.down.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>下载资源</h1>
<h3><a href="/servlet/down">下载天龙八部</a></h3>
</body>
</html>
2.DownServlet.java
package redirect;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** @author 孙显圣* @version 1.0*/
@WebServlet(urlPatterns = "/down")
public class DownServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//使用重定向resp.sendRedirect("/servlet/downnew");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}
}
3.DownServletNew.java
package redirect;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.HTML;
import java.io.IOException;/*** @author 孙显圣* @version 1.0*/
@WebServlet(urlPatterns = "/downnew")
public class DownServletNew extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//设置内容类型为x-tarresp.setContentType("application/x-tar;");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}
}
4.结果
4.细节说明
5.动态获取上下文路径
String contextPath = super.getServletContext().getContextPath();
6.课后作业
1.pay.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>支付页面</h1>
<form action="/servlet/pay" method="post">用户编号:<input type="text" name="id">支付金额:<input type="text" name="money"><input type="submit" value="提交">
</form>
</body>
</html>
2.Pay.java
package redirect;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** @author 孙显圣* @version 1.0*/
@WebServlet(urlPatterns = "/pay")
public class Pay extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//获取信息String id = req.getParameter("id");String money = req.getParameter("money");if (Integer.parseInt(money) > 100) {resp.sendRedirect("/servlet/payok");}else {resp.sendRedirect("/servlet/pay.html");}}
}
3.PayOk.java
package redirect;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** @author 孙显圣* @version 1.0*/
@WebServlet(urlPatterns = "/payok")
public class PayOk extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html;charset=utf-8");PrintWriter writer = resp.getWriter();writer.print("<h1>" + "恭喜你,支付成功!" + "<h1>");}
}