标签:des style blog http color io os ar 使用
一,Servlet入门
1,所有的Servlet都要实现Servlet接口,它的services()(对外提供服务)方法会被容器直接调用,但是一般我们继承HttpServlet类,它是GenericServlet的子类(实现了Servlet接口)。services()方法会调用doGet(),doPost()等方法,挡在浏览器中输入url时会调用doGet()方法,在表单以post方式提交时会调用doPost()方法。
public class HelloWordServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doGet");
PrintWriter out =resp.getWriter();
out.write("<a href=‘http://www.baidu.com‘>go</a>");//客户端呈现
}
}
HttpServletRequest :封装了客服端到服务器端的一系列的请求。
HttpServletResponse :从服务器返回给客户端的内容。
2,在web.xml中的配置
<servlet> <servlet-name>HelloWorldServlet</servlet-name> <servlet-class>HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorldServlet</servlet-name> <url-pattern>/HelloWorldServlet</url-pattern> </servlet-mapping>
二,Servlet的生命周期
在webapplication整个生命过程中,servlet只new一次,所以代码在后台只输出一次constructor,只初始化一次,输出一次init。只有webapplication退出的时候才执行destroy()方法。
public class TestLifeCycleServlet extends HttpServlet { public TestLifeCycleServlet() { System.out.println("constructor"); } public void init() throws ServletException { System.out.println("init"); } public void destroy() { System.out.println("destroy"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
执行结果:
三,Servlet编程接口
四,request获取请求的参数
public class ShowParameters extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading All Request Parameters"; out.println("<html><head><title>读取所有参数</title></head>" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Parameter Name<TH>Parameter Value(s)"); Enumeration paramNames = request.getParameterNames();//Enumeration 一个过时的接口,存放参数名 while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.print("<TR><TD>" + paramName + "\n<TD>"); String[] paramValues = request.getParameterValues(paramName); if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.println("<I>No Value</I>"); else out.println(paramValue); } else { out.println("<UL>"); for(int i=0; i<paramValues.length; i++) { out.println("<LI>" + paramValues[i]); } out.println("</UL>"); } } out.println("</TABLE>\n</BODY></HTML>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
五,Cookies(记录在客户端)
1,由于http是无状态的协议,它不知道client以前在我这做过什么事情,所以要用到cookie
2,处理Cookie
//response设置cookie
for(int i=0; i<3; i++) { // Default maxAge is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i); response.addCookie(cookie); cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); // Cookie is valid for an hour, regardless of whether // user quits browser, reboots computer, or whatever. cookie.setMaxAge(3600); response.addCookie(cookie);
//request获取cookie
Cookie[] cookies = request.getCookies(); if (cookies != null) { Cookie cookie; for(int i=0; i<cookies.length; i++) { cookie = cookies[i]; out.println("<TR>\n" + " <TD>" + cookie.getName() + "</TD>\n" + " <TD>" + cookie.getValue()+"</TD></TR>\n"); }
3,当new一个cookie时,若没有设置存活周期,则它存在于这个浏览器窗口打开期间,它的窗口及其子窗口可以访问cookie,相当于cookie写在了内存中.如果设置了存活周期,则会写在本地文件中。
六,Session(记录在服务器端)
1, 当打开一个浏览器窗口生成session时,就会自动生成一个sessionid,这个sessionid会在浏览器窗口打开期间一直存在,直到该窗口连同浏览器一起关掉(在不关该浏览器的情况下,另打开一个该浏览器,可以访问原来的session),若在其他类型浏览器中打开则访问不到。(疑问:前面括号的东西和所看视频不一致(一个窗口对应一个sessionid),自己试验的可以。。。)
<session-config> <session-timeout>30</session-timeout> </session-config>
2,HttpServletRequest中的Session管理方法
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get current session or, if necessary, create a new one HttpSession mySession = request.getSession(true); //MIME type to return is HTML response.setContentType("text/html"); //get a handle to the output stream PrintWriter out = response.getWriter(); //generate HTML document out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>Session Info Servlet</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H3>Session Information</H3>"); out.println("New Session: " + mySession.isNew()); out.println("<BR>Session ID: " + mySession.getId()); out.println("<BR>Session Creation Time: " + new java.util.Date(mySession.getCreationTime())); out.println("<BR>Session Last Accessed Time: " + new java.util.Date(mySession.getLastAccessedTime())); out.println("<H3>Request Information</H3>"); out.println("Session ID from Request: " + request.getRequestedSessionId()); out.println("<BR>Session ID via Cookie: " + request.isRequestedSessionIdFromCookie()); out.println("<BR>Session ID via rewritten URL: " + request.isRequestedSessionIdFromURL()); out.println("<BR>Valid Session ID: " + request.isRequestedSessionIdValid()); out.println("<br/><a href="+response.encodeURL("SetSession")+">refresh</>"); out.println("</BODY></HTML>"); out.close(); //close output stream }
public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Tracking Example"; HttpSession session = request.getSession(true); String heading; // Use getAttribute instead of getValue in version 2.2. Integer accessCount = (Integer)session.getValue("accessCount"); if (accessCount == null) { accessCount = new Integer(0); heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; accessCount = new Integer(accessCount.intValue() + 1); } // Use setAttribute instead of putValue in version 2.2. session.putValue("accessCount", accessCount); out.println("<html><head><title>Session追踪</title></head>" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" + "<H2>Information on Your Session:</H2>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Info Type<TH>Value\n" + "<TR>\n" + " <TD>ID\n" + " <TD>" + session.getId() + "\n" + "<TR>\n" + " <TD>Creation Time\n" + " <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR>\n" + " <TD>Time of Last Access\n" + " <TD>" + new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" + " <TD>Number of Previous Accesses\n" + " <TD>" + accessCount + "\n" + "</TABLE>\n" + "</BODY></HTML>");
七,Application
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=gb2312"); PrintWriter out = response.getWriter(); ServletContext application = this.getServletContext(); Integer accessCount = (Integer) application.getAttribute("accessCount"); if (accessCount == null) { accessCount = new Integer(0); } else { accessCount = new Integer(accessCount.intValue() + 1); } // Use setAttribute instead of putValue in version 2.2. application.setAttribute("accessCount", accessCount); out.println("<html><head><title>Session追踪</title></head>" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + accessCount + "\n" + "</TABLE>\n" + "</BODY></HTML>" + "</H1>\n"); }
八,Servlet中使用Bean
标签:des style blog http color io os ar 使用
原文地址:http://www.cnblogs.com/enjoy-life-clh/p/4027179.html