web basic Servlet and jsp

Getting Started with Web Development

Introduced
之前的程序: java桌面程序,控制台控制,socket gui界面。javase规范
现在和以后的程序:java web程序。浏览器控制。javaee规范

Structure of the software
C / S (Client - Server client - server)
Typical Applications: QQ software, autumn fly, spider mite.
Features:
1) must download a specific client program.
2) Upgrade the server, the client upgrade.

			**B/S (Broswer -Server 浏览器端- 服务器端)**
					典型应用: 腾讯官方(www.qq.com)  163新闻网站, 
					特点:
						1)不需要安装特定的客户端(只需要安装浏览器即可!!)
						2)服务器端升级,浏览器不需要升级!!!!

					javaweb的程序就是b/s软件结构!!!

server

			从物理上来说,服务器就是一台PC机器。8核,8G以上,T来计算,带宽100M

			web服务器:PC机器安装一个具有web服务的软件,称之为web服务器
			数据库服务器:PC机器安装一个具有数据管理件服务的软件,称之为数据库服务器。
			邮件服务器:PC机器安装一个具有发送邮件服务的软件,称之为邮件服务器。

web services software

			web服务软件的作用:把本地的资源共享给外部访问。

Common web server software market

			WebLogic: BEA公司的产品。 收费的。支持JavaEE规范。
			WebSphere: IBM公司的产品。收费的。支持JavaEE规范
			JBoss: Redhat公司的产品。收费的。支持JavaEE规范
			Tomcat: 开源组织Apache的产品。免费的。支持部分的JavaEE规范。(servlet、jsp。jdbc,但												ejb, rmi不支持)

DNS domain name parsing process

Using a domain name into an IP address, HOST first read local files, local files do not get the corresponding IP from the current telecommunications network.
Local host file C: \ Windows \ System32 \ drivers \ etc
drawing demonstration.

Intranet and extranet

The difference between the internal network and external networks?

Extranet, intranet are two of the Internet access.
  Netcom said local area network LAN network is vulgar, vulgar to say that external network and Internet communication WAN WAN or MAN MAN Road. Network and external networks is a relative term. Range larger than the general outside the network within the network, it can be said that the network subnet outside the network.
  ** external network (WAN) for each computer (or other network device) on ** has one or more WAN IP address (or the public network, the external network IP address), a wide area network IP address can not be repeated; LAN ( each computer (or other network device) has on a LAN) or more local IP address (or private network, an IP address), local IP address assigned inside the LAN, the IP address may be different LANs repeat, do not affect each other.

External network mapping tool

In doing some paid projects, the development of micro-channel, or docking third-party interfaces when some callback operations may require external network access.
So we are doing local development, when outside the network can not access to the local?
How to solve this problem?
It will be used outside the network mapping tool, commonly used outside the network mapping tool netapp (free), peanut shells and so on.
Reference: https://natapp.cn/article/natapp_newbie
Servlet core
Sevlet life cycle (focus)
Servlet four important life-cycle approach
constructor: Create a servlet object when called. By default, when you create an object first visit servlet servlet call only once. Tomcat servlet proof object in a single instance.
init method: finished creating servlet objects when called. Call only once.
service method: each time the call request. Call n times.
destroy method: when the destruction of servlet objects called. Stop the server or redeploy destroy servlet object web application. Call only once.
the servlet lifecycle
Tomtcat run internal code:
1) to content servlet-class found by mapping the string: com.itmayiedu.a_servlet.FirstServlet
2) reflected by the object structure FirstServlet
2.1 bytecode object obtained
Class clazz = class.forName ( "com.itmayiedu.a_servlet.FirstServlet");
2.2 no constructor call parameters to construct the object
Object obj = clazz.newInstance (); -1.servlet constructor is called
3) ServletConfig object created by calling the init method of the reflecting
3.1 Object methods give
Method m = clazz.getDeclareMethod ( "the init", ServletConfig.class);
3.2 invoke methods
m.invoke (obj, config); init method is called --2.servlet
4) create request, response object method calls the service by reflecting
4.1 Object methods give
Methodm m clazz.getDeclareMethod = ( "service", HttpServletRequest.class, HttpServletResponse.class);
4.2 invoke methods
m.invoke (obj, request, response) ; --3.servlet service method is called
5) is stopped or when the web server tomcat application of redeployment, reflected by the destroy method is called
5.1 methods to give the object
method, m = clazz.getDeclareMethod ( "destroy", null);
5.2 invoke methods
m.invoke (obj, null); --4.servlet's destroy method is called

servlet life cycle
multithreading issues Servlet's
Note: servlet objects tomcat server is a single-instance multi-threaded.
Because the servlet is multi-threaded, so when multiple threads simultaneously access the servlet's servlet to share data, such as member variables, may cause thread-safety issues.
Solution:
1) the use of a code block to shared data synchronization (sync using the synchronized keyword)
2) advise against the use of member variables in the servlet class. If you really want to use the members must be synchronized. And minimize the scope of the synchronization code block. (Where the member variables to use, where to sync !!), in order to avoid the concurrent synchronous and result in reduced efficiency.
Servlet:
the HttpServletRequest request object: a request for information
HttpServletResponse response object: Object setting response
ServletConfig object servlet configuration object
ServletContext object; servlet context object
thread-safe code is:


package com.servlet;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServetlDemo4 extends HttpServlet {
private int i = 1;
@Override
public void init() throws ServletException {
System.out.println(“ServetlDemo4…init()”);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置编码格式
// resp.setContentType(“text/html;charset=utf-8”);
resp.setCharacterEncoding ( "utf-8") ; // content encoding, to prevent Chinese garbled
resp.setContentType ( "text / HTML; charset = UTF-. 8");
the synchronized (ServetlDemo4.class) {
// the output to the browser SUMMARY
resp.getWriter () write ( "this is the first" + i + "visit ...");.
the try {
the Thread.sleep (5000);
} the catch (Exception E) {
// the TODO: Exception handle
}
I ++;
}
}
@Override
public void the destroy () {
System.out.println ( "... ServetlDemo4 the destroy ()");
}
}

Session Management

Technical Session
Cookie Technology: session data stored in the browser client.
Technical Session: Session data is stored on the server side.
Domain objects: data sharing between resources.

		request域对象
		context域对象

Cooke technology

Features
Cookie Technology: session data stored in the browser client.

Cookie technology core
		Cookie类:用于存储会话数据

			1)构造Cookie对象
				Cookie(java.lang.String name, java.lang.String value)
			2)设置cookie
				void setPath(java.lang.String uri)   :设置cookie的有效访问路径
				void setMaxAge(int expiry) : 设置cookie的有效时间
				void setValue(java.lang.String newValue) :设置cookie的值
			3)发送cookie到浏览器端保存
				void response.addCookie(Cookie cookie)  : 发送cookie
			4)服务器接收cookie
				Cookie[] request.getCookies()  : 接收cookie

Cookie Principle

			1)服务器创建cookie对象,把会话数据存储到cookie对象中。
					new Cookie("name","value");
			2)	服务器发送cookie信息到浏览器
					response.addCookie(cookie);

					举例: set-cookie: name=eric  (隐藏发送了一个set-cookie名称的响应头)
			3)浏览器得到服务器发送的cookie,然后保存在浏览器端。
			4)浏览器在下次访问服务器时,会带着cookie信息
				    举例: cookie: name=eric  (隐藏带着一个叫cookie名称的请求头)
			5)服务器接收到浏览器带来的cookie信息
					request.getCookies();

Cookie details

		1)void setPath(java.lang.String uri)   :设置cookie的有效访问路径。有效路径指的是cookie的有效路径保存在哪里,那么浏览器在有效路径下访问服务器时就会带着cookie信息,否则不带cookie信息。
		
		2)void setMaxAge(int expiry) : 设置cookie的有效时间。
				正整数:表示cookie数据保存浏览器的缓存目录(硬盘中),数值表示保存的时间。
				负整数:表示cookie数据保存浏览器的内存中。浏览器关闭cookie就丢失了!!
				零:表示删除同名的cookie数据
		3)Cookie数据类型只能保存非中文字符串类型的。可以保存多个cookie,但是浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。

Technical Session

Introducing
Cookie limitations:
. 1) Cookie can store string type. You can not save the object
2) can store non-Chinese.
3) a capacity not exceeding Cookie is 4KB.
If you want to save the non-string, more than 4kb content, technology can only use the session! ! !
Session Features:
session data stored on the server side. (Memory)

Session core technology

		HttpSession类:用于保存会话数据

		1)创建或得到session对象
			HttpSession getSession()  
			HttpSession getSession(boolean create)  
		2)设置session对象
			void setMaxInactiveInterval(int interval)  : 设置session的有效时间
			void invalidate()     : 销毁session对象
			java.lang.String getId()  : 得到session编号
		3)保存会话数据到session对象
			void setAttribute(java.lang.String name, java.lang.Object value)  : 保存数据
			java.lang.Object getAttribute(java.lang.String name)  : 获取数据
			void removeAttribute(java.lang.String name) : 清除数据

session object destruction time:
3.1 minutes 30 default server automatically recovered
3.2 modified session recovery time
3.3 globally modify the session valid time

<session-config>
	<session-timeout>1</session-timeout>
</session-config>
   手动销毁session对象

4) How to avoid the browser's cookie JSESSIONID as the browser is closed and the problem of missing

    手动发送一个硬盘保存的cookie给浏览器
	Cookie c = new Cookie("JSESSIONID",session.getId());
	c.setMaxAge(60*60);
	response.addCookie(c);

What is the built-in objects?

Frequently used in the JSP development to some objects, SUN companies to simplify the development, provision after the JSP page is loaded automatically help developers created these objects in the design of JSP, developers only need to use the appropriate corresponding object calling the method that is can. The system creates an object called a good built-in objects.

JSP nine built-in objects

Built-in object type name
request the HttpServletRequest
Response the HttpServletResponse
config the ServletConfig
file application the ServletContext
the session the HttpSession
Exception the Throwable
Page Object (the this)
OUT the JspWriter
the pageContext the PageContext
. 1, the request object
request javax.servlet.httpServletRequest object is an object type. The object represents a client request information, mainly for receiving data transmitted to the server via the HTTP protocol. (Including header information, system information, and a request requesting mode parameters, etc.). Scope request once the request object.
2, the object response
response represents a response to the client, the main object of the treated JSP container back to the client. The response object also has a scope, it is only valid within the JSP page.
3, session objects
session object is created automatically by the server associated with the user object requests. Server generates a session object for each user, for storing information of the user, the tracking operation state of the user. Map session using internal object classes to store data, the data stored in the format "Key / value". value session object may make the complex object types, not just a string type.
4, application objects
application information objects can be stored in the server until the server is shut down, otherwise the application objects stored information will be valid throughout the application. Compared with the session objects, application objects longer life cycle, similar to the system of "global variables."
5, out objects
out object is used to output information in the Web browser, and manage the output buffer on the application server. When the object using the output data out, the operation may be made to the data buffer, timely removal of residual data in the buffer, so that the space for other output buffer. After the completion of data output, to close the output stream.
6, pageContext objects
role pageContext object is to obtain any range of parameters, you can get out JSP page through it, request, reponse, session, application and other objects. pageContext objects are created and initialized by the container to complete, can be used directly pageContext object in JSP pages.
7, config object is
the main object is to get action config server configuration information. By pageConext object getServletConfig () method gets a config object. When a Servlet initialization, certain information transmitted to the container the Servlet using the config object. Application developers can program in the environment Servlet and JSP pages provide initialization parameters in the web.xml file.
8, page objects
page object represents the JSP itself, only in the JSP page is legitimate. page hidden object contains the current Servlet interface reference variable in nature, similar to the this pointer in Java programming.
9, exception objects
The role of the exception object is to display exception information, containing only can be used isErrorPage = "true" page, use the object in general will not compile JSP page JSP file. excepation object and all the objects, like Java, has inherited the structure provided by the system. Almost all the exception object is defined exceptions. In Java programs, you can use try / catch keyword to handle exceptional conditions; if not caught exception occurs in a JSP page, it will generate exception object, and the object is transferred to the exception error page set in the page directive and then processing the corresponding exception object error page.

Four Scope

page domain: You can only use the current jsp page (current page)
Request Domain: Use only (forward) in the same request
session domains: use only (private) in the same session (session objects) in the
context domain: use only (global) within the same web application

Published 26 original articles · won praise 0 · Views 683

Guess you like

Origin blog.csdn.net/YHM_MM/article/details/104044741