Learning Notes (ii) Eclipse settings servlet configuration and initialization parameter reading and servlet application

Source: Internet
Author: User
Tags java web tomcat server

1. Developing a dynamic WEB project (Javaweb project) using Java EE version of Eclipse
1). Switch the development options to Java EE
2). You can find the package Explorer in Windows-a Show View and drag it to the left of the development zone
3). Create a new Tomcat server in the Servers panel. Be sure to associate to the root directory of the Tomcat installation
4). Create a new Dynamic Web Project. Where Target Runtime needs to select Tomcat6.0
5). Developing Java WEB applications
6). You can run the WEB project through run on server.

2. Servlet's HelloWorld
1). Create an implementation class for the Servlet interface.
public class HelloServlet implements Servlet

2). Configure and map this Servlet in the Web. xml file

<!--Configuring and mapping Servlets--
<servlet>
<!--Servlet Registration name--
<servlet-name>helloServlet</servlet-name>
<!--Servlet Full class name--
<servlet-class>com.atguigu.javaweb.HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<!--need to be consistent with the text node of a serlvet-name child node of a servlet node--
<servlet-name>helloServlet</servlet-name>
<!--map the specific access path:/represents the root directory of the current WEB app. -
<url-pattern>/hello</url-pattern>
</servlet-mapping>

3. servlet container: A software environment that runs Servlet, JSP, Filter, and so on.
1). You can create a servlet and invoke the associated life-cycle method of the servlet.
2). JSP, Filter, Listener, Tag ...

4. Servlet Life cycle Methods: The following methods are called by the Serlvet container.
1). Constructor: called only once. An instance of the servlet is created only the first time the servlet is requested. Invokes the constructor.
This shows a single instance of Serlvet!
2). Init method: called only once. Called immediately after a good instance has been created. Used to initialize the current Servlet.
3). Service: called multiple times. Each request invokes the service method. Actually used in response to a request.
4). Destroy: Called only once. Called before the WEB app where the current Servlet resides is unloaded. Used to release resources occupied by the current Servlet.

5. Load-on-startup Parameters:
1). Configure in the servlet node:

<servlet>
<!--Servlet Registration name--
<servlet-name>secondServlet</servlet-name>
<!--Servlet Full class name--
<servlet-class>com.atguigu.javaweb.SecondServlet</servlet-class>
<!--can specify the time that the Servlet was created--
<load-on-startup>2</load-on-startup>
</servlet>

2). Load-on-startup: You can specify the time when Serlvet is created. If it is negative, it is created on the first request. If it is 0 or a positive number, the current WEB application is
Serlvet creates an instance when the container is loaded, and the smaller the array is created earlier.

6. About Serlvet-mapping:

1). The same servlet can be mapped to multiple URLs, that is, the setting value of the <servlet-name> child elements of multiple <servlet-mapping> elements can be the same
The name of the servlet's registry.

2). You can also use the * wildcard character in the URL that the servlet maps to, but there are only two fixed formats:
One format is "*. Extension", and the other is preceded by a forward slash (/) and ends with "/*".

<servlet-mapping>
<servlet-name>secondServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

OR

<servlet-mapping>
<servlet-name>secondServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

Note: The following are illegal with/and with an extension.

<servlet-mapping>
<servlet-name>secondServlet</servlet-name>
<url-pattern>/*.action</url-pattern>
</servlet-mapping>

7. ServletConfig: Serlvet configuration information is encapsulated and ServletContext objects can be obtained

1). Configure initialization parameters for Serlvet

<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.atguigu.javaweb.HelloServlet</servlet-class>

<!--Configure initialization parameters for Serlvet. And the node must be in front of the Load-on-startup node--
<init-param>
<!--parameter Names--
<param-name>user</param-name>
<!--parameter Values--
<param-value>root</param-value>
</init-param>

<init-param>
<param-name>password</param-name>
<param-value>1230</param-value>
</init-param>

<load-on-startup>-1</load-on-startup>

</servlet>

2). Get initialization parameters:

> Getinitparameter (String name): Gets the initialization parameters for the specified parameter name
> Getinitparameternames (): Gets the enumeration object that consists of the name of the parameter.

String user = Servletconfig.getinitparameter ("user");
System.out.println ("User:" + user);

enumeration<string> names = Servletconfig.getinitparameternames ();
while (Names.hasmoreelements ()) {
String name = Names.nextelement ();
String value = servletconfig.getinitparameter (name);
System.out.println ("^^" + name + ":" + value);
}

3). Gets the configuration name of the Serlvet (learn)

8. ServletContext

1). Can be obtained by serlvetconfig:

ServletContext ServletContext = Servletconfig.getservletcontext ();


2). This object represents the current web app: You can think of Serlvetcontext as a big housekeeper for your current Web application. You can get information about the various aspects of your current WEB app.

①. Getting initialization parameters for the current WEB app

Set initialization parameters: can be obtained for all servlets, while the servlet initialization parameters are only available with that Serlvet.

<!--Configure initialization parameters for the current WEB app--
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>

Method:

Getinitparameter
Getinitparameternames

Code:

ServletContext ServletContext = Servletconfig.getservletcontext ();

String Driver = servletcontext.getinitparameter ("Driver");
System.out.println ("Driver:" + driver);

enumeration<string> names2 = Servletcontext.getinitparameternames ();
while (Names2.hasmoreelements ()) {
String name = Names2.nextelement ();
System.out.println ("--" + name);
}

②. Get the absolute path to a file on the server for the current WEB app, not the pre-deployment path

Getrealpath (String path);

Code:

String Realpath = Servletcontext.getrealpath ("/note.txt");
System.out.println (Realpath);

③. Get the name of the current WEB app:

Getcontextpath ()

Code:

String ContextPath = Servletcontext.getcontextpath ();
System.out.println (ContextPath);

④. Gets the input stream for a file for the current WEB app.

getResourceAsStream (String path): The root directory of the current WEB app for path.

Code:

InputStream Is2 = Servletcontext.getresourceasstream ("/web-inf/classes/jdbc.properties");

⑤. Several methods related to attribute:

9. GET requests and POST requests:

1). pass parameters using Get mode:

①. When you enter a URL address in the browser address bar or click a hyperlink on a webpage, the HTTP request message sent by the browser is requested as get.
②. If the method property of the <form> form element in the Web page is set to "get", the HTTP request message generated when the browser submits the form form is also get.
③. Use the GET request format to pass parameters to the Web server:

Http://www.atguigu.com/counter.jsp?name=lc&password=123

④. The amount of data transferred using get is typically limited to less than 1KB.

2). Pass parameters using POST:

①. POST request mode is primarily used to submit data from a form form to a WEB server-side program: The method of Form form is set to POST
②. POST means that each form field element and its data are sent to the WEB server as the entity content of the HTTP message, and the amount of data transferred is much larger than the amount of data that is sent using the Get method.

post/counter.jsp http/1.1
Referer:http://localhost:8080/register.html
content-type:application/x-www-form-urlencoded
host:localhost:8080
content-length:43

name=zhangsan&password=123--Pass parameters in the request body.

10. How to obtain the request information in Serlvet:

1). The service () method of the Servlet is used to answer the request: Because each request invokes the service () method

public void Service (ServletRequest request, servletresponse response)
Throws Servletexception, IOException

ServletRequest: Encapsulates the request information. Any request information that can be obtained from it.
Servletresponse: Encapsulates the response information, if you want to give the user what the response, you can use the method of the interface implementation.

The implementation classes for both interfaces are implemented by the server and are passed in when the service method is invoked by the server.

2). ServletRequest: Encapsulates the request information. Any request information that can be obtained from it.

①. Get Request Parameters:

> String GetParameter (String name): Returns the parameter value based on the name of the request parameter.
If the request parameter has more than one value (for example, a checkbox), the method can only get the value to the first commit.

> string[] getparametervalues (string name): Returns an array of strings corresponding to the request parameters, based on the name of the request parameter.

> Enumeration Getparameternames (): Returns the enumeration object that corresponds to the parameter name,
A Getinitparameternames () method similar to ServletConfig (or ServletContext).

> Map getparametermap (): Returns the key-value pair for the request parameter: key: Parameter name, Value: Parameter value, String array type.

②. Get the requested URI:

HttpServletRequest httpservletrequest = (httpservletrequest) request;

String RequestUri = Httpservletrequest.getrequesturi ();
System.out.println (RequestUri); /day_29/loginservlet

③. Get the Request method:

String method = Httpservletrequest.getmethod ();
System.out.println (method); GET

④. For a GET request, get the string that corresponds to the request parameter, that is? The string after that.

String queryString = httpservletrequest.getquerystring ();
System.out.println (queryString); User=atguigu&password=123456&interesting=game&interesting=party&interesting=shopping

⑤. Get the mapped path of the requested Serlvet

String Servletpath = Httpservletrequest.getservletpath ();
System.out.println (Servletpath); /loginservlet

⑥. Several methods related to attribute:

3). HttpServletRequest: Is the sub-interface of the serlvetrequest. defined for the HTTP request. It contains a number of methods related to getting HTTP requests.

4). Servletresponse: Encapsulates the response information, if you want to give the user what response, you can use the method of the interface implementation.

①. *getwriter (): Returns the PrintWriter object. Call the object's print () method, and the parameters in print () are printed directly
To the client's browser.

②. Setting the content type of the response: Response.setcontenttype ("Application/msword");

③. void Sendredirect (String location): The requested redirect. (This method is defined in HttpServletResponse.)

-----------------------------------------------------------------------------

In the Web. xml file, set the initialization parameters for the two password, user, and A.
Define a login.html that defines two request fields: User, password. Send request to Loginservlet
Create a loginservlet in which to get the requested user, password. is more consistent than the request parameters defined in the Web. xml file
If consistent, response hello:xxx, if not consistent, the response sorry:xxx xxx is user.

-----------------------------------------------------------------------------


Learning Notes (ii) Eclipse settings servlet configuration and initialization parameter reading and servlet application

Related Article

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.