Introduction to Java Web Development servlet (ii)

Source: Internet
Author: User

Brief introduction

I also fret that my blog writing format sucks, title + code format. Because the daily curriculum is relatively large, there is no time to spend on the writing format, such as not accustomed to please forgive me. I insist on writing a daily blog is mainly to develop a habit, and continue to continue, although the content is very vague, the purpose is also achieved, in order to consolidate knowledge points, perseverance

Servlet Quick Start 0. About Servlet
What is a servlet it is actually Java class, running on the server side, the main purpose is to process the user to send HTTP requests, and to respond to learning two packages: Javax.servlet/javax.servlet.httpservlet container is tomcat, That is, the Web server
1. Manually Deploy Web Apps
Myapp|--web-inf:|--classes (after the servlet compiles the code into this package) |--lib|--web.xml|--css|--html|--img|--js1. Creating servlet Class packages manually Com.itheima.servlet;import javax.servlet.*;import java.io.*;p ublic class Helloworldservlet extends GenericServlet { public void Service (ServletRequest req,servletresponse res) throws Servletexception,ioexception {Res.getwriter (). Write ("Hello World");}} 2. Compile set classpath=%classapth%; C:\apache-tomcat-6.0.37\lib\servlet-api.jarjavac-d. Helloworldservlet.java3. configuration file Add a servlet configuration to Web. XML <servlet><!--a name of your own--><servlet-name>hello </servlet-name><!--must be the full path of the servlet class--><servlet-class>com.itheima.servlet.helloworldservlet </servlet-class> </servlet> <servlet-mapping><!--a name you deserve--><servlet-name>hello </servlet-name><!--a URL for the map, must be/start (specific path)--><url-pattern>/cgx/aj</url-pattern>// Configure the mapping URL path name must precede the slash/, the slash represents the current application directory </servlet-mapping>
2. MyEclipse Project Considerations
Note: If the project name is modified, the corresponding project facet path will also be modified (right-click Properties-->myeclipse-->[project facets]-->web-->context Root) Replace the Servlet template *wizard*.jar-->template/servlet.java (templates file)
3. Doget/dopost Analysis
When the user initiates the request, the always called is the Service () method, and the method internally determines whether to call Doget (), or doPost () and the servlet we define itself rewrites the doget (), DoPost () Conclusion: Do not rewrite the service () method yourself, because the parent class has this method, generally overriding the Doget/dopost method extension: Using the Template method design mode public class A {service () {doget ();d opost ();} public abstract void Doget ();p ublic abstract void DoPost ();} public class B extends A {public void doget () {...} public void DoPost () {...}} @Testpublic void Test () {A A = new B (); A.service ();}
4. servlet life cycle
When the user first accesses the instantiation/initialization/provision of services the second visit only provides external services 1. By default, the servlet lifecycle is executed as follows: When the user first requests: 1. Instantiation: Construction Method 1 times 2. Initialization: (init): 1 times 3. Services: (service), each subsequent request, will be directly executed service ()  : N times 4. Destroy: When the server is stopped or the application is removed, the Destroy Destory () method executes at this time: 1 times 2. The rewrite lifecycle is a value that is implemented through <load-on-startup>:  integers (1 starts with a  smaller priority) after the server starts, the corresponding servlet executes the lifecycle (instantiation, initialization) each time the user executes , Walk the Service () method advantages: When the user requests each time, the speed will become faster disadvantage: If Load-on-startup is configured too much, tomcat boot speed will be slow
5. Details of servlet configuration in Web. xml
1. Can be equipped with multiple mapping addresses <servlet-mapping><servlet-name>myfirst</servlet-name><url-pattern>/servlet/ Myfirstservletdemo1</url-pattern> </servlet-mapping> <servlet-mapping><servlet-name> Myfirst</servlet-name><url-pattern>/aj</url-pattern> </servlet-mapping>2. Mappings can also use wildcard characters * How to use: A, *. extension: Must begin with a * and end with an extension. For example *.dob,/action/*: Must begin with/start, * at the end. For example/action/* principle: B Priority is higher than a. If all is a or both B, match the previous one.    fully matched mapping priority highest do not write this/*.action3. Summary rule: 1. The exact match with the exact matching 2./* priority is higher than *. The extension can also be configured with a default Servlet1. Notation:  /< Servlet-mapping><servlet-name>myfirst</servlet-name><url-pattern>/</url-pattern> </servlet-mapping>2. When a static resource is requested, the default servletif ("1.jpg" is found) is executed if it is not found {display picture}else{not found 404}3. This default servlet is not typically configured, Why? Because in Tomcat's web. XML, there are
6. Thread Safety
Illustrates that the servlet is not thread-safe, and that it is designed to use multithreading to handle user requests for thread safety solutions: 1.synchronized: Thread synchronization 2. Single-threaded: that is the implementation of the Singlethreadmodel interface summary: Both methods are not, Violate the design intent!!! The Final Solution: the programmer's own attention, do not define member variables, try to use local variables to reasonably determine the scope of variables defined in the servlet
The servletconfig of the servlet the configuration information for a servlet, the parameters that need to be initialized at first
<servlet><!--Configure this servlet for ServletDemo3--><servlet-name>servletdemo3</servlet-name> <servlet-class>com.itheima.servlet.ServletDemo3</servlet-class><init-param> <!-- The value that represents AAA is BBB--><param-name>aaa</param-name><param-value>bbb</param-value></ init-param></servlet>//Get configuration information for the servlet and print public void doget (HttpServletRequest request, HTTPSERVLETRESPO NSE response) throws Servletexception, IOException {servletconfig sc = getservletconfig (); String value = Sc.getinitparameter ("encoding"), if (value== null) value = "GBK"; Response.getwriter (). write (value);//In control All parameters and values of the Servlet enumeration e = Sc.getinitparameternames () are printed on the console. All parameter names while (E.hasmoreelements ()) {String paramname = (string) e.nextelement (); System.     Out. println (paramname+ "=" +sc.getinitparameter (paramname));} }

Introduction to Servlet ServletContext 1. What is ServletContext and its role
It is an object generated by the server that is used to share information between the Servlets to obtain global initialization parameter 1). It is run in a Web container, and each Web application will have its own unique ServletContext object 2). When the app is loaded by the Web container, 3 is created). It is the same life cycle as the Web application, and as the Web application launches, it disappears as the application unloads: 1). As a global domain object to use (the four domains are the most widely used), can realize the application scope of data sharing, to obtain the global initialization parameter implementation principle: is to maintain the global scope of a map collection setattribute (key,value) Object obj = getattribute (key); RemoveAttribute (key); 2). Gets the global initialization parameter Getinitparameter ("") getinitparameternames ();
2. Implement the servlet forwarding
1. What is forwarding? A-->b--c redirect a----B (no resources) a----C implementation steps: 1. Get the forwarder  path must be absolute path RequestDispatcher rd = Getservletcontext (). Getrequestdispatcher ("/servlet/servletcontextdemo1"); 2. Forwarding Rd.forward (request, response); 2. Realization Mode// Put Iphone6sc.setattribute ("Gift", "iphone6");//forwarding, using ServletContext to implement forwarding, can not use relative path, can only use/start to represent an absolute path requestdispatcher RD = Sc.getrequestdispatcher ("/servlet/servletcontextdemo5");//forwarder//rd.forward (request, response);//forwarding//When implementation is included, It will include the response body of the target object, and if it has a response header, it does not work  rd.include (request, response);//contains
3. Forwarding and redirection differences
Characteristics of Forwarding: 1). The address bar does not change 2). Indicates that the client sent only one request to the server 3). Values placed in the Reques domain can be shared with redirection 1). Address bar Change 2). The client sent 2 requests 3). Data that is placed in the request domain cannot be shared
4. Read the resource file 3 ways
1. Based on the learning of the absolute path obtained by the relative path Getrealpath, only suitable for WEB project//string Absolutepath = Getservletcontext (). Getrealpath ("/web-inf/classes/ Cfg2.properties ");//string Absolutepath = Getservletcontext (). Getrealpath ("/web-inf/classes/com/itheima/ Day07servlet/cfg2.properties "); String Absolutepath = Getservletcontext (). Getrealpath ("/web-inf/cfg3.properties"); Properties prop = new properties ();//Get a Properties object Prop.load (New FileInputStream (Absolutepath)); Load this file into memory Response.getoutputstream (). Write (Prop.getproperty ("P"). GetBytes ());//2. ResourceBundle resource file loader//Applicable scope: Web project, Java Project can, can only load src under resources//resourcebundle RB = Resourcebundle.getbundle ("Cfg2"); Base name: Just without extension resourcebundle RB = Resourcebundle.getbundle ("com.itheima.day07Servlet.cfg"); Base name: is the string value without the extension = rb.getstring ("P"); Response.getoutputstream (). Write (Value.getbytes ()); 3. The class loader Classloaderclassloader cl = This.getclass (). getClassLoader ();//inputstream is = Cl.getresourceasstream (" Cfg2.properties "); InputStream is = Cl.getresourceasstream (" com/itheima/day07Servlet/cfg.properties ");//inputstream is = Cl.getresourceasstream (".. /cfg3.properties "); Web-inf Properties prop = new properties ();p rop.load (IS); Response.getoutputstream (). Write (Prop.getproperty ("P"). GetBytes ());

Servlet for getting Started with Java Web development (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.