Java(9):MVC框架基础:Servlet+Jsp+javabean(1)

来源:互联网 发布:水稻基因组数据库 编辑:程序博客网 时间:2024/06/06 10:02

日期:2017/11/10

      自学Java一个月了,这段经历给我的感受是:确保每天进步一点点;前三个星期是领悟--通过持续不断的练习,熟练掌握面向对象的编程;后面的时间则是冲击流行框架(spring/springMVC/Mybatis/Hibernate/structs等等)的掌握,力求做出成品,现在熟悉了MVC(Servlet+JSP+JavaBean)开发的小Demo后,果然还是功力稍显嫩。

      保持脚踏实地、实事求是,现在对学会的作下总结:

一、Servlet

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

     一段运行在服务器(Tomcat)的程序,它是java代码,常用的继承类是HttpServlet,类的方法见下列表,但最常用的方法是doGet()和doPost():

Modifier and TypeMethod and Descriptionprotected voiddoDelete(HttpServletRequest req, HttpServletResponse resp)

Called by the server (via the service method) to allow a servlet to handle a DELETE request.
protected voiddoGet(HttpServletRequest req, HttpServletResponse resp)
Called by the server (via the service method) to allow a servlet to handle a GET request.
protected voiddoHead(HttpServletRequest req, HttpServletResponse resp)
Receives an HTTP HEAD request from the protected service method and handles the request.
protected voiddoOptions(HttpServletRequest req, HttpServletResponse resp)
Called by the server (via the service method) to allow a servlet to handle a OPTIONS request.
protected voiddoPost(HttpServletRequest req, HttpServletResponse resp)
Called by the server (via the service method) to allow a servlet to handle a POST request.
protected voiddoPut(HttpServletRequest req, HttpServletResponse resp)
Called by the server (via the service method) to allow a servlet to handle a PUT request.
protected voiddoTrace(HttpServletRequest req, HttpServletResponse resp)
Called by the server (via the service method) to allow a servlet to handle a TRACE request.
protected longgetLastModified(HttpServletRequest req)
Returns the time the HttpServletRequest object was last modified, in milliseconds since midnight January 1, 1970 GMT.
protected voidservice(HttpServletRequest req, HttpServletResponse resp)
Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class.
voidservice(ServletRequest req, ServletResponse res)
Dispatches client requests to the protected service method.

      仔细观察可以发现,这些方法共同的地方是引用了两个参数:HttpServletRequest req,HttpServletResponse resp。而service()是一个处理请求分发的方法,分配给doGet和DoPost。

Parameters:
req - an HttpServletRequest object that contains the request the client has made of the servlet
resp - an HttpServletResponse object that contains the response the servlet sends to the clientreq 是一个 HttpServletRequest 对象,代表了客户端的请求信息;

resp 是一个 HttpServletResponse 对象,代表了服务端的响应信息;


 HttpServletRequest 

Extends the ServletRequest interface to provide request information for HTTP servlets.

The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGetdoPost, etc).

     它是一个接口(interface),继承了另一个父接口--ServletRequest , HttpServletRequest 有一大批实现了的常用的方法:

Modifier and TypeMethod and Descriptionbooleanauthenticate(HttpServletResponse response)

Use the container login mechanism configured for the ServletContext to authenticate the user making this request.
StringchangeSessionId()
Change the session id of the current session associated with this request and return the new session id.
StringgetAuthType()
Returns the name of the authentication scheme used to protect the servlet.
StringgetContextPath()
Returns the portion of the request URI that indicates the context of the request.
Cookie[]getCookies()
Returns an array containing all of the Cookie objects the client sent with this request.
longgetDateHeader(String name)
Returns the value of the specified request header as a long value that represents a Date object.
StringgetHeader(String name)
Returns the value of the specified request header as a String.
Enumeration<String>getHeaderNames()
Returns an enumeration of all the header names this request contains.
Enumeration<String>getHeaders(String name)
Returns all the values of the specified request header as an Enumeration of String objects.
default HttpServletMappinggetHttpServletMapping()
Return the HttpServletMapping by which the HttpServlet for this HttpServletRequest was invoked.
intgetIntHeader(String name)
Returns the value of the specified request header as an int.
StringgetMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.
PartgetPart(String name)
Gets the Part with the given name.
Collection<Part>getParts()
Gets all the Part components of this request, provided that it is of type multipart/form-data.
StringgetPathInfo()
Returns any extra path information associated with the URL the client sent when it made this request.
StringgetPathTranslated()
Returns any extra path information after the servlet name but before the query string, and translates it to a real path.
StringgetQueryString()
Returns the query string that is contained in the request URL after the path.
StringgetRemoteUser()
Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.
StringgetRequestedSessionId()
Returns the session ID specified by the client.
StringgetRequestURI()
Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.
StringBuffergetRequestURL()
Reconstructs the URL the client used to make the request.
StringgetServletPath()
Returns the part of this request's URL that calls the servlet.
HttpSessiongetSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.
HttpSessiongetSession(boolean create)
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
default Map<String,String>getTrailerFields()
Get the request trailer fields.
PrincipalgetUserPrincipal()
Returns a java.security.Principal object containing the name of the current authenticated user.
booleanisRequestedSessionIdFromCookie()
Checks whether the requested session ID was conveyed to the server as an HTTP cookie.
booleanisRequestedSessionIdFromUrl()
Deprecated. 
As of Version 2.1 of the Java Servlet API, use isRequestedSessionIdFromURL() instead.
booleanisRequestedSessionIdFromURL()
Checks whether the requested session ID was conveyed to the server as part of the request URL.
booleanisRequestedSessionIdValid()
Checks whether the requested session ID is still valid.
default booleanisTrailerFieldsReady()
Return a boolean indicating whether trailer fields are ready to read using getTrailerFields().
booleanisUserInRole(String role)
Returns a boolean indicating whether the authenticated user is included in the specified logical "role".
voidlogin(String username, String password)
Validate the provided username and password in the password validation realm used by the web container login mechanism configured for theServletContext.
voidlogout()
Establish null as the value returned when getUserPrincipalgetRemoteUser, and getAuthType is called on the request.
default PushBuildernewPushBuilder()
Instantiates a new instance of PushBuilder for issuing server push responses from the current request.
<T extends HttpUpgradeHandler>
T
upgrade(Class<T> handlerClass)
Creates an instance of HttpUpgradeHandler for a given class and uses it for the http protocol upgrade processing.

同理,HttpServletRequest也是一样:

Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.

The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's service methods (doGetdoPost, etc).

常用的方法有:

Modifier and TypeMethod and DescriptionvoidaddCookie(Cookie cookie)

Adds the specified cookie to the response.
voidaddDateHeader(String name, long date)
Adds a response header with the given name and date-value.
voidaddHeader(String name, String value)
Adds a response header with the given name and value.
voidaddIntHeader(String name, int value)
Adds a response header with the given name and integer value.
booleancontainsHeader(String name)
Returns a boolean indicating whether the named response header has already been set.
StringencodeRedirectUrl(String url)
Deprecated. 
As of version 2.1, use encodeRedirectURL(String url) instead
StringencodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.
StringencodeUrl(String url)
Deprecated. 
As of version 2.1, use encodeURL(String url) instead
StringencodeURL(String url)
Encodes the specified URL by including the session ID, or, if encoding is not needed, returns the URL unchanged.
StringgetHeader(String name)
Gets the value of the response header with the given name.
Collection<String>getHeaderNames()
Gets the names of the headers of this response.
Collection<String>getHeaders(String name)
Gets the values of the response header with the given name.
intgetStatus()
Gets the current status code of this response.
default Supplier<Map<String,String>>getTrailerFields()
Gets the supplier of trailer headers.
voidsendError(int sc)
Sends an error response to the client using the specified status code and clears the buffer.
voidsendError(int sc, String msg)
Sends an error response to the client using the specified status and clears the buffer.
voidsendRedirect(String location)
Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.
voidsetDateHeader(String name, long date)
Sets a response header with the given name and date-value.
voidsetHeader(String name, String value)
Sets a response header with the given name and value.
voidsetIntHeader(String name, int value)
Sets a response header with the given name and integer value.
voidsetStatus(int sc)
Sets the status code for this response.
voidsetStatus(int sc, String sm)
Deprecated. 
As of version 2.1, due to ambiguous meaning of the message parameter. To set a status code use setStatus(int), to send an error with a description use sendError(int, String). Sets the status code and message for this response.
default voidsetTrailerFields(Supplier<Map<String,String>> supplier)
Sets the supplier of trailer headers.


二、JSP

     java server page,动态技术标准,嵌入了java的html文件,引入目的:负责用户的html显示,实现"业务逻辑"和“视图实现”的分离。本质还是一个servlet,因为它不是被客户端直接的调用,而是 先翻译成 .java 文件,编译成 .class 文件而执行



三、JavaBean

     java bean是可复用组件(说明白了,就是将复用性强的java代码封装在一个类文件中)。对比 EJB,主要用在客户端的开发,只能在开发阶段定制,也不是什么分布式对象,只能在web-app内部被访问。




待续...


阅读全文
0 0