1 servlet Base 1.0 inheritance relationships for common servlet classes
Common objects in 1.1 servlet
- ServletContext: is a description of the current project context
- ServletRequest: Browser requests to the server
request.getParameter("username"); //获得单个数据request.getParameterValues("love"); //获得一组数据:用于复选框这种多项数据的情况request.setCharacterEncoding("UTF-8"); //处理中文乱码,此方法只对POST请求有效,GET需要单独处理request.setAttribute("login""true");
Other methods of request
SetAttribute (String name,object) //Set parameter value of request named Namegetattributenames () //Returns a collection of names for all properties of the request object, resulting in an instance of an enumerationgetcookies () //Returns all cookie objects for the client, resulting in an array of cookiesgetcharacterencoding () //Returns the character encoding in the requestgetcontentlength () //Returns the length of the requested bodyGetHeader (String name) //Get file header information defined by HTTP protocolgetheaders (String name) //Returns all values of the request header for the specified name, resulting in an instance of an enumerationgetheadernames () //Return so the name of the request header, the result is an instance of an enumerationgetInputStream () //Returns the requested input stream for obtaining the data in the requestGetMethod () //Get a way for clients to transfer data to the server sidegetparameter (String name)//Get client to server side with name specified parameter valuegetparameternames () //Get the name of all parameters that the client sends to the server side, and the result is an instance of the enumerationgetparametervalues (String name) //Get all values with the parameter specified by nameGetprotocol () //Gets the protocol name on which the client transmits data to the servergetquerystring () //Get query stringGetrequesturi () //Gets the client address that issued the request stringgetremoteaddr () //Get the IP address of the clientgetremotehost () //Get the name of the clientgetsession ([Boolean create]) //Return and request the relevant sessiongetServerName () //Get the name of the serverGetservletpath () //Gets the path of the script file requested by the clientGetserverport () //Get the port number of the serverremoveattribute (String name) //Delete one of the properties in the request
- Servletresponse: The server responds to the browser by storing all the data that needs to be sent to the browser on this object. Store the required data in the specified stream, and the data will be displayed in the browser
Response.getwriter ();//Generally send data content in the programResponse.getoutputstream ();//Byte stream is typically used in programs with copy functionResponse.setcontenttype ("Text/html;charset=utf-8");//Notify Tomcat and browser to send data encodingResponse.setheader ("Cache-control","No-cache");//Set client header informationResponse.sendredirect ("new.jsp");//redirect//Implement redirection on JSP page: <%response.sendredirect ("new.jsp");%>Objectobj = Request.getattribute ("Login"); Getrequestdispatcher (Stringpath);//server: The current program needs to get the request scheduler//forward: When the scheduler coordinates multiple Servlets, this method returns the page output of the last servlet
1.2 Servlet code Example
Public class formservlet extends httpservlet { Public void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter ();//★★ to get a character stream //Send dataOut.println ("<form action=\" #\ "method=\" post\ ">"); Out.println ("Name: <input type= ' text ' name= ' username ' value= ' chicken sister ' > <br/>"); Out.println ("Password: <input type= ' password ' name= ' userpwd ' > <br/>"); Out.println ("<input type= ' submit ' value= ' submitted '/> '); Out.println ("</form>"); }/// other code slightly}
1.3 Cookie and session
//1. Create a cookie and notify the browser "Cookieservlet.java" of cookie informationCookie cookie =NewCookies ("Test","Itcast");//Create CookiesResponse.addcookie (cookie);//Notify the browser of cookie information//2. Obtaining cookie information saved by the browser "Readcookieservlet.java"cookie[] cookies = request.getcookies ();if(Cookies! =NULL){//★ There's no such thing. The null pointer exception is reported when the browser is closed and then opened for(Cookie c:cookies) {System. out. println (C.getname () +":"+ C.getvalue ()); }}//3. Setting the effective time of a cookie to make a session-level cookie a persistent cookieCookie cookie =NewCookies ("GF","Fengjie");//* Create a cookieCookie.setmaxage ( -* -* -);//* Set valid timeResponse.addcookie (cookie);//* Notification browser//3. Modifying the path of a cookie,/cookie/addcookieservlet2//The cookie set by the current servlet can only be obtained in all Servlets under the cookie directory and in subsequent Servlets//Want to access in/getcookieservlet? Cookie cookie =NewCookies ("add222","22222222222");//* Create a cookieCookie.setmaxage ( -* -);//* Set valid timeCookie.setpath ("/day07/");//* Modify PathResponse.addcookie (cookie);//* Notification browser//4. Storing Chinese in a cookiecookie[] cookies = request.getcookies ();if(Cookies! =NULL){ for(Cookie c:cookies) {System. out. println (C.getname () +":"+ C.getvalue ());//Get the value of CN and decode if("cn". Equals (C.getname ())) {Stringvalue= Urldecoder.decode (C.getvalue (),"UTF-8"); System. out. println (value); }}}, String data ="Chinese"; String returndata = Urlencoder.encode (data,"UTF-8");//Encode the transmitted Chinese charactersCookie cookie =NewCookies ("cn", returndata);//Create CookiesResponse.addcookie (cookie);//Send data-}//5. Setting the maximum character value of a cookie Public void DoPost(HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {Request.setcha Racterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8");//Patchwork data, get 4KB string, cannot exceed 4KBStringBuffer buf =NewStringBuffer (); for(inti =0; I <1024x768*4; i + +) {Buf.append ("a"); } String data = Buf.tostring (); Cookie cookie =NewCookies ("Max", data);//Create CookiesCookie.setmaxage ( -* -);//Set valid timeResponse.addcookie (cookie);//Notify browser, send data}
The session object is created by the server and the session object is obtained through the Request.getsession () method
Session default is 30 minutes valid (in the Conf directory of the Web. xml file configuration: 30, note that the unit is minutes)
Sample code
Public void DoPost(HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {reques T.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8");//jsessionid=dfe75a1e9ccaa1591f900fa3b1aee9f3:tomcat automatically adds cookies, session-level //Get sessionHttpSession session = Request.getsession ();the//parameter defaults to TRUE. Not created, there is a return. System. out. println (Session.isnew ());The first time is true, then false//Persistent OperationCookie cookie =NewCookies ("Jsessionid", Session.getid ());//Create a cookie yourselfCookie.setmaxage ( -* -);//Set cookie attribute: valid timeResponse.addcookie (cookie);//Specify cookie behavior: Notify browser}
2. Different post and get requests in 2.1 HTTP requests [1]
- Security: Get Address bar commit, post in HTML header
- Get is the data that gets from the server, and the post sends the data to the server
- Submit data limit: Get within 1k, Post unlimited
Call Doget () for Get when you call Dopost () for post, based on the method attribute in the form tag.
What is the difference between forward () and redirect () in the 2.2 SERVLET API?
- The former is only the steering of the control in the container, in the client browser address bar will not show the post-turn address, the latter is a full jump, the browser will get the address of the jump, and resend the request link. This way, you can see the link address after the jump from the address bar of the browser. Therefore, the former is more efficient, when the former can satisfy the need, try to use the forward () method, and, as such, it also helps to hide the actual link. In some cases, for example, you need to jump to a resource on a different server, you must use the Sendredirect () method.
Forward
"REDIRECT"
The difference between 2.3 getattribute () and GetParameter
- The HttpServletRequest class has a setattribute () method and no Setparameter () method
- The values they fetch are different. GetAttribute takes an object, and GetParameter takes a string.
- Data delivery paths are different. The data passed by the Request.getparameter method is transmitted from the Web client to the Web server, which represents the HTTP request data used for form or URL redirection. The data passed by the Request.getattribute method exists only inside the Web container and is shared between Web Components that have a forwarding relationship (servlet and JSP), that is, the object exists within the request scope.
- In JSP, SetAttribute is to put this object in the corresponding piece of memory in the page, when the page server forwards to another page, the application server will copy the memory into another page memory.
In summary: The Request.getattribute () method returns the object that exists in the request scope, and the Request.getparameter () method is to get the data submitted by HTTP.
2.4 The difference between filters, listeners, interceptors
- Servlet
The servlet process is short, and after the URL is sent, it is processed and then returned or moved to a specific page of its own. It is primarily used to control the business before it is processed
- Filters (Filter)
Filter filters is a server-side program that implements the Javax.servlet.Filter interface, the main purpose of which is to filter character encoding, make some business logic judgments, and so on. The principle is that as long as you configure the Web. xml file to intercept the client request, it will help you intercept the request, at this time you can set the request or response (requests, Response) unified encoding, simplify the operation, but also to make logical judgments, such as whether the user has logged on, There is no permission to access the page and so on work. It starts with your web app, initializes only once, and then intercepts requests that are destroyed only when your web app is stopped or redeployed. The filter process is linear, and after the URL has passed, after checking, you can keep the original process going down, being received by the next Filter,servlet, and the servlet will not continue to pass down after processing.
- Listener (Listener)
A server-side program that implements the Javax.servlet.ServletContextListener interface, which is initiated with the launch of the Web application, is initialized only once and destroyed as the Web application stops. The main role is to do some initialization of the content to add work, set up some basic content, such as some parameters or some fixed objects and so on. Servlet/filter are for URLs and so on, and listener is for objects, such as the creation of a session, the occurrence of session.setattribute, something to do when such an event occurs.
- Interceptors (Interceptor)
Interceptors are applied in aspect-oriented programming, not URLs, but action, which is filtered when the page submits an action. is to call a method before the service or a method, or call a method after the method. Is a Java-based reflection mechanism. Interceptors are not configured in Web. XML, such as struts in Struts.xml
2.5 Servlet, Filter, listener execution order
In the entire project (without any frames), they are loaded in the context-param -> listener -> filter -> servlet order that the filter is executed in the order defined in Web. XML (when multiple filter matches are made) and the order of execution is represented
-
[Servlet] Summary