作者:笑如夏风_503 | 来源:互联网 | 2023-09-03 12:59
实现COOKIE关于当前时间显示的Demo
使用Servlet实现。
java代码:
import javax. servlet. ServletException; import javax. servlet. http. COOKIE; import javax. servlet. http. HttpServlet; import javax. servlet. http. HttpServletRequest; import javax. servlet. http. HttpServletResponse; import java. io. IOException; import java. io. PrintWriter; import java. util. Date; public class COOKIEDemo01 extends HttpServlet { @Override protected void doGet ( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req. setCharacterEncoding ( "utf-16" ) ; resp. setCharacterEncoding ( "utf-16" ) ; PrintWriter out = resp. getWriter ( ) ; COOKIE[ ] COOKIEs = req. getCOOKIEs ( ) ; if ( COOKIEs!= null) { out. write ( "你上一次访问的时间是:" ) ; for ( int i = 0 ; i < COOKIEs. length; i++ ) { COOKIE COOKIE = COOKIEs[ i] ; if ( COOKIE. getName ( ) . equals ( "lastLoginTime" ) ) { long lastLoginTime = Long. parseLong ( COOKIE. getValue ( ) ) ; Date date = new Date ( lastLoginTime) ; out. write ( date. toLocaleString ( ) ) ; } } } else { out. write ( "这是您第一次访问本站" ) ; } COOKIE COOKIE = new COOKIE ( "lastLoginTime" , System. currentTimeMillis ( ) + "" ) ; resp. addCOOKIE ( COOKIE) ; } @Override protected void doPost ( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet ( req, resp) ; } }
对相关的Servlet进行注册
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" > < servlet> < servlet-name> COOKIEDemo01 servlet-name> < servlet-class> com.donric.servlet.COOKIEDemo01 servlet-class> servlet> < servlet-mapping> < servlet-name> COOKIEDemo01 servlet-name> < url-pattern> /COOKIE url-pattern> servlet-mapping> web-app>
最后配置一下tomcat就好了。