public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//this.getInitParameter(); 初始化参数
//this.getServletConfig(); Servlet配置
//this.getServletContext(); Servlet上下文
ServletContext servletContext = this.getServletContext();
String username="尚硅谷";//数据
servletContext.setAttribute("username",username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
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);
}
}
servlet1
HelloServlet
servlet1
/one
url
jdbc.mysql:://localhost:3306/mybatis
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String url = servletContext.getInitParameter("url");
resp.getWriter().print(url);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.print("进入了ServletDemo04");
ServletContext servletContext = this.getServletContext();
servletContext.getRequestDispatcher("/three").forward(req,resp);//转发的请求路径,调用forward实现请求转发
}
properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为类路径classpath;
需要一个文件流;
username=qinjiang
password=123456
public class ServletDemo05 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
InputStream is = servletContext.getResourceAsStream("/WEB-INF/classes/db.properties");//路径区分大小写
Properties pros = new Properties();
pros.load(is);
String username = pros.getProperty("username");
String password = pros.getProperty("password");
resp.getWriter().print(username+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
访问测试即可ok;
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
负责向浏览器发送数据的方法
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);
void setDateHeader(String var1, long var2);
void addDateHeader(String var1, long var2);
void setHeader(String var1, String var2);
void addHeader(String var1, String var2);
void setIntHeader(String var1, int var2);
void addIntHeader(String var1, int var2);
void setStatus(int var1);
响应的状态码
int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409;
int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500;
int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2.下载文件
1.向浏览器输出消息(一直在讲,见上面的例子)
2.下载文件
1.要获取下载文件的路径
2.下载的文件名是啥?
3.设置想办法让浏览器能够支持下载我们需要的东西
4.获取下载文件的输入流
5.创建缓冲区
6.获取OutputStream对象
7.将FileOutputStream流写入buffer缓冲区
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.要获取下载文件的路径
String realPath = "D:\\ideaWorkSpace\\javaweb-servlet-01\\response\\src\\main\\resources\\狂神.png";
System.out.print("下载文件的路径:"+realPath);
// 2.下载的文件名是啥?
String fileName = realPath.substring(realPath.lastIndexOf("//") + 1);
// 3.设置想办法让浏览器能够支持(Content-disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码
resp.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
// 4.获取下载文件的输入流
FileInputStream fis = new FileInputStream(realPath);
// 5.创建缓冲区
int len=0;
byte[] buffer = new byte[1024];
// 6.获取OutputStream对象
ServletOutputStream os = resp.getOutputStream();
// 7.将FileOutputStream流写入buffer缓冲区
while ((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
os.close();
fis.close();
}
3.验证码功能
验证怎么来的?
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器5秒自动刷新一次
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D g = (Graphics2D) 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/ PNG");
//网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("cache- Control","no-cache");//缓存策略
resp.setHeader("pragma","no-cache");
//把图片写给浏览器
boolean png = ImageIO.write(image, "png", resp.getOutputStream());
}
4.实现重定向
一个web资源收到客户端请求后,他会通知客户端去访问另外一个web资源,这个过程叫重定向
常见场景:
void sendRedirect(String var1) throws IOException;
测试:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
resp.setHeader("Location","/image");
resp.setStatus(302);
*/
resp.sendRedirect("/image");//重定向
}
面试题:请你聊聊重定向和转发的区别?
相同点:
不同点:
1、找到${CATALINA_HOME}/conf/logging.properties
2、找到java.util.logging.ConsoleHandler.encoding = UTF-8
修改为java.util.logging.ConsoleHandler.encoding = GBK
注意在转发的时候如果在点击提交按钮的时候报404错误,并且是因为输入pageContext.request.contextPath的这一段,是因为web.xml的版本问题
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理请求
String username=req.getParameter("username");
String password=req.getParameter("password");
System.out.print(username+password);
//重定向的时候一定要注意,路径问题,否则404
resp.sendRedirect("/r/success.jsp");
}
Test
com.atguigu.servlet.RequestTest
Test
/login
登录页面
Hello World!
<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前的项目 --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
Success
1.获取前段传递的参数
2.请求转发
@Override
protected void doPost(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[] hobbys = req.getParameterValues("hobbys");
//后台接收中文乱码问题
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
System.out.println("===================");
//重定向
// resp.sendRedirect();
//转发
// this.getServletContext()
//通过请求转发
//这里的斜杠代表当前的web应用
req.getRequestDispatcher("/Success.jsp").forward(req,resp);
}
面试题:请你聊聊重定向和转发的区别
相同点
不同点
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话
有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话;
你能怎么证明你是谁?
1.身份证
一个网站,怎么证明你来过?
客户端 服务端
1.服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了;cookie
2.服务器登记你来过了,下次你来的时候我来匹配你;seesion
cookie
seesion
常见场景:网站登录之后,你下次不用登录了,第二次访问直接就上了!
1.从请求中拿到Cookie信息
2.服务器响应给客户端Cookie
Cookie[] cookies = req.getCookies();//获得Cookie
cookie.getName()//获得Cookie中的key
cookie.getValue()//获得Cookie中的value
out.write(date.toLocaleString());//date类型转String
cookie.setMaxAge(24*60*60);//设置有效期
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");//新建Cookie
resp.addCookie(cookie);//响应给客户端一个Cookie
cookie:一般会保存在本地的用户目录下appdata;
一个网站的Coolie是否存在上限!聊聊细节问题
删除Cookie
编码解码:
URLEncoder.encode("秦疆","utf-8")//编码
URLDecoder.decode(cookie.getValue(),"utf-8")//解码
什么是Session:
Session
Session和Cookie的区别:
使用场景:
使用Session:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;Character=utf-8");
//得到Session
HttpSession session = req.getSession();
//给Session中存东西
session.setAttribute("name",new Person("秦疆",1));
//获取Session的ID
String id=session.getId();
//判断Session是不是新创建
if(session.isNew()){
resp.getWriter().write("Session创建成功,id="+id);
}else{
resp.getWriter().write("Session已经在服务器中存在"+id);
}
//Session做了什么
// Cookie jsessionid = new Cookie("JSESSIONID", "6815754D02889928D1B75B3EADDFCB07");
// resp.addCookie(jsessionid);
}
//得到Session
HttpSession session = req.getSession();
HttpSession session1 = req.getSession();
Person name = (Person) session1.getAttribute("name");
resp.getWriter().write(name.toString());
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销session
session.invalidate();
会话自动过期:web.xml配置
15
Java Server Pages:Java服务器端页面,也和Servlet一样,用于动态Web技术!
最大的特点:
思路:JSP到底怎么执行的!
我电脑的地址:
C:\Users\q\.IntelliJIdea2017.3\system\tomcat\Unnamed_javaweb-session-cookie\work\Catalina\localhost\s\org\apache\jsp
发现页面转变成了Java程序!
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet!
JSP最终也会转换成一个Java类!
JSP本质也是一个Servlet
//初始化
public void _jspInit() {
}
//销毁
public void _jspDestroy() {
}
//JSPService
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
1.判断请求
2.内置了一些对象
final javax.servlet.jsp.PageContext pageContext; //页面上下文
javax.servlet.http.HttpSession session = null; //session
final javax.servlet.ServletContext application; //applicationContext
final javax.servlet.ServletConfig config; //config
javax.servlet.jsp.JspWriter out = null; //out
final java.lang.Object page = this; //page:当前页面
HttpServletRequest request //请求
HttpServletResponse response //响应
3.输出页面前增加的代码
response.setContentType("text/html"); //设置响应的页面类型
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
4.以上的这些个对象我们可以在JSP页面中直接使用
在JSP页面中:
只要是JAVA代码就会原封不动的输出,只要是HTML代码就会被转为:
out.write("