package conclusion;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/ServletDemo")
public class ServletDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//小结:
//ServletContext: 生命周期 -> 开始: 服务器启动 结束: 服务器关闭
//获得对象: request.getServletContext() this.getServletContext() getServletConfig().getServletContext()
//获得的是同一个 application
ServletContext application = request.getServletContext();
//ServletContext application1 = getServletContext();
//ServletContext application2 = getServletConfig().getServletContext();
//获得参数 -> 需要在web.xml文件中添加
// <context-param>
// <param-name>name</param-name>
// <param-value>zjh</param-value>
// </context-param>
String name = application.getInitParameter("name");
System.out.println(name);//zjh
//获得应用名
String contextPath = application.getContextPath();
System.out.println(contextPath);///20220816
//获取资源的绝对路径
String realPath = application.getRealPath("a.txt");
System.out.println(realPath);//D:\Nochinese\Java\JavaEE\out\artifacts\20220816_war_exploded\a.txt
//存储数据
application.setAttribute("count",1);
Object count = application.getAttribute("count");
System.out.println(count);//1
application.removeAttribute("count");
System.out.println(count);//1
//request:
//获得请求参数
String password = request.getParameter("password");
System.out.println(password);//1234
//域对象的使用 -> 转发
request.getRequestDispatcher(getServletContext().getContextPath()).forward(request,response);
//乱码问题
request.setCharacterEncoding("UTF-8");
//获得Cookie
Cookie cookie = new Cookie("id", "123");
response.addCookie(cookie);
String value = cookie.getValue();
System.out.println(value);//123
//获得session
HttpSession session = request.getSession();
session.setAttribute("age",18);
String JSESSIOID = session.getId();
Object age = session.getAttribute("age");
System.out.println(age);//18
System.out.println(JSESSIOID);//1016AB523BCB02185096A6010E9BC21F
//response:
//设置响应类型
response.setStatus(302);
//重定向, 响应体
response.sendRedirect(getServletContext().getContextPath());
//cookie有关
//session: 原理, 使用, 持久化
//持久化 设置cookie路径名称必须一致
Cookie cookie1 = new Cookie("JSESSIONID",session.getId());
cookie.setPath(request.getContextPath());
cookie.setMaxAge(10 * 60);
response.addCookie(cookie1);
//cookie: 原理, 使用, 常用api
Cookie cookie2 = new Cookie("job", "manager");
//设置存在时间,单位秒
cookie2.setMaxAge(1000);
//获得key
cookie2.getName();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
Servlet小结
最新推荐文章于 2024-09-24 08:39:48 发布