Write in front:
This article is transferred from: http://www.oschina.net/question/12_52027 article, if asked to delete, the first time contact me immediately delete!
Web frameworks are best practices for architecture when developers write web App services in a language. Many web frameworks are extracted from actual Web projects, only related to Web request and response processing, and form the basis for developing other application projects from this stripped-down foundation, allowing developers to focus more on more specific business issues rather than the control of Web requests and responses.
Many frameworks, but the routines are basically similar, help you hide a lot about the HTTP protocol details, focus on functional development.
But for a beginner, premature contact frames are often inefficient! The same problem, for a different framework you may need to start from scratch.
The following is a beginner Java development Web process Some personal insights and ideas, master can skip.
1. Basic requirements: Java Programming Basics
There is a good foundation for Java programming, which is necessary, and the problem of having a Java programming Foundation when discussing WEB development techniques will be despised.
2. Environment Readiness (Eclipse + Tomcat)
Choose one of your favorite servlet containers, or even bigger is the application server, which recommends Tomcat, Resin, or Jetty these lightweight products. These three products download the zip package after decompression can be used. If you are unfamiliar with Tomcat, please do not use the EXE version of Tomcat, which will add a lot of trouble. It is also not recommended to integrate TOMCAT in some development environments, such as Eclipse, and also to add annoyance.
Start the application server and have access to its default page.
About Development tools
Using the JEE version of MyEclipse and Eclipse is not recommended, increasing annoyance, slow running, and the inability to understand the structure of WEB projects. Common Eclipse or your favorite development tool is enough to support common Java project development.
For convenience, I made a basic Java project--servletdemo.zip, and you can import it into Eclipse as a complete, simplest WEB project.
Then replace the following XML content with the Conf/server.xml file under Tomcat:
<?xml version= ' 1.0 ' encoding= ' utf-8 '? ><server port= "8005" shutdown= "shutdown" > <service name= " Catalina "> <connector port=" 8080 "protocol=" http/1.1 "connectiontimeout=" 20000 "redirectport=" 8443 " uriencoding= "UTF-8"/> <engine name= "Catalina" defaulthost= "localhost" >
Where D:\WORKDIR\ServletDemo is replaced with the project path you imported, and after you start Tomcat again, you can see the output of Hello world when the browser opens Http://localhost:8080/hello.
3. Understanding Servlets and Filter
Well, I've set the environment up, what's the next thing to do?
The previous step is to build a test environment and then let you understand the structure of a most basic Java Web project.
One of the most basic Java WEB projects required for a JAR package requires only one Servlet-api.jar, the classes in this jar are mostly interfaces, and there are tools that have a total of 2 packages, namely Javax.servlet and Javax.servlet.htt P. I put the jar in a separate packages folder outside of the WebApp directory because all of the Servlet containers have this package, and you don't have to put it in the Web project, and we just put it in the need of compiling and running is not needed. If you simply put Servlet-api.jar in the Webapp/web-inf/lib directory, then Tomcat will also report a warning message when it starts.
The Java Web project also requires a very important configuration file, Web. XML, which has been minimized by me in this project, preserving only useful information:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web application 2.3//en" "http://java.sun.com/dtd/web-app_2 _3.dtd "><web-app> <servlet> <servlet-name>hello_world</servlet-name> <servlet-class>demo. helloservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>hello_world</servlet-name> <url-pattern>/ hello</url-pattern> </servlet-mapping> </web-app>
Each servlet must be defined in Web. XML and configured for URL mapping, the early Java development web when there is no framework flying around, this file defines a large number of servlets, or someone for the sake of the convenience of a/servlet/* to directly call through the class name Servlet.
There is another very important and very useful interface in the Servlet specification that is filter filters.
The following is the simplest Filter class and the corresponding definition method:
Package demo; Import java.io.IOException; Import Javax.servlet.filter;import Javax.servlet.filterchain;import Javax.servlet.filterconfig;import Javax.servlet.servletexception;import Javax.servlet.servletrequest;import Javax.servlet.servletresponse;import Javax.servlet.http.HttpServletRequest; public class Hellofilter implements Filter { @Override public void init (Filterconfig arg0) throws servletexception { System.out.println ("Filter initialization"); } @Override public void DoFilter (ServletRequest req, servletresponse Res, Filterchain chain) throws IOException, servletexception { HttpServletRequest request = (httpservletrequest) req; System.out.println ("Intercept uri=" +request.getrequesturi ()); Chain.dofilter (req, res); } @Override public Void Destroy () { System.out.println ("Filter End");} }
The configuration in Web. XML must precede the Servlet:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "Http://java.sun. Com/dtd/web-app_2_3.dtd "><web-app> <filter> <filter-name>helloFilter</filter-name> <filter-class>demo. hellofilter</filter-class> </filter> <filter-mapping> <filter-name>hellofilter</f ilter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>hello_world</servlet-name> <servlet-class>demo. helloservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <ser Vlet-mapping> <servlet-name>hello_world</servlet-name> <url-pattern>/hello</url-patt Ern> </servlet-mapping> </web-app>
Visit Http://localhost:8080/hello to see what output information the Tomcat console has.
4. Correspondence between Servlet and HTTP
Servlet is the most important part of the Java EE, with the servlet you are the Java EE, the other aspects of the Java EE content to be used. And the servlet specification you need to Master is the servlet and filter these two technologies. Most of the framework is not based on a servlet or filter, and if it is to run on a servlet container, it can never be separated from this model.
Why the servlet specification will have two packages, Javax.servlet and javax.servlet.http, the person who designed the specification earlier that the servlet is a service model, not necessarily dependent on some kind of network protocol, thus abstracting a Javax.servlet, while providing an interface extension based on the HTTP protocol. But from the actual running for so many years, it seems that there is no Servlet technology implemented on other protocols.
Javax.servlet and Javax.servlet.http Both packages add up to just 34 interfaces and classes. You need to be familiar with the specific meaning of each class and interface through the JAVADOC documentation of the Java EE. In particular, the following interfaces must be familiar with the meaning and purpose of each method:
- HttpServlet
- Servetconfig
- ServletContext
- Filter
- Filterconfig
- Filterchain
- RequestDispatcher
- HttpServletRequest
- HttpServletResponse
- HttpSession
- Some listenser classes
Again, the two interfaces of HttpServletRequest and HttpServletResponse should be well-established.
If you are literally unable to understand the meaning of a method, you can do experiments on the basis of the previous project to see its output, and then you can go to the discussion area to ask questions, such questions are very clear, many people can help you.
Why do I emphasize httpservletrequest and httpservletresponse these two interfaces, because WEB development is inseparable from the HTTP protocol, and the Servlet specification is actually the HTTP protocol object-oriented encapsulation, the HTTP protocol, please The sum response is the two interfaces that correspond to HttpServletRequest and HttpServletResponse.
You can get all the information about the request through HttpServletRequest, including the URI, Cookie, Header, request parameters, and so on, with no other way. So when you use a frame, you want to get information about the HTTP request, just get the HttpServletRequest instance.
The HttpServletResponse interface is used to produce HTTP responses, including cookies, headers, and the content of responses.
5. Talk about the Session again
There is no definition for session sessions in the HTTP protocol, which is produced by various programming languages based on the stateless nature of the HTTP protocol. Its implementation is nothing more than a hash table on the server side, and the hash table key is the Cookie value passed to the browser named Jsessionid.
When you need to save a value to the session, the container performs the following steps:
A. Get the Jsessionid value, and if not, create a method that is request.getsession ().
B. The HttpSession object instance you get is the equivalent of a hash table where you can store data in the hash table (SetAttribute)
C. You can also get a value by getattribute
This Cookie, called Jsessionid, is automatically deleted when the browser is closed. Set the MaxAge value of the Cookie to 1 to achieve the effect that the browser turns off auto-delete.
6. About JSP
First of all, I've been using the Velocity template engine for many years now without JSP.
Any JSP page will be compiled into a Servlet class file when executed, and if it is Tomcat, the generated Java files will be placed in a subdirectory of the corresponding project in the {Tomcat}/work directory, such as the following for tomcat-generated class files:
Package org.apache.jsp; Import Javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;import java.util.*; Public final class Test_jsp extends Org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent {private static final jspfactory _jspxfactory = Jspfactory.getdefaultfactory (); private static java.util.list<string> _jspx_dependants; Private Javax.el.ExpressionFactory _el_expressionfactory; Private Org.apache.tomcat.InstanceManager _jsp_instancemanager; Public java.util.list<string> getdependants () {return _jspx_dependants; } public void _jspinit () {_el_expressionfactory = _jspxfactory.getjspapplicationcontext (Getservletconfig (). GetServle Tcontext ()). Getexpressionfactory (); _jsp_instancemanager = Org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager (Getservletconfig ()); public void _jspdestroy () {} public void _jspservice (final httpservletrequest request, final httpservletreSponse response) throws Java.io.IOException, servletexception {final PageContext pagecontext; HttpSession session = NULL; Final ServletContext Application; Final ServletConfig config; JspWriter out = null; Final Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try {response.setcontenttype ("text/html;charset=utf-8"); PageContext = _jspxfactory.getpagecontext (this, request, response, NULL, True, 8192, true); _jspx_page_context = PageContext; application = Pagecontext.getservletcontext (); Config = Pagecontext.getservletconfig (); Session = Pagecontext.getsession (); out = Pagecontext.getout (); _jspx_out = out; Out.write ("\ r \ n"); Out.write ("
In the servlet there is a package javax.servlet.jsp is a JSP-related interface specification definition. The advantage of JSP over servlet is that direct modification takes effect immediately, unlike a servlet that must restart the container to take effect.
Therefore, the JSP is suitable for the view, while the Servlet is suitable for the control layer.
7. Summary
Preaching a large pile, summed up is the following points:
- Do not learn any framework before you know the Servlet specification
- Use the simplest tool, without any wizards and visualizations
- Familiarity with the HTTP protocol
When you really mastered the Servlet spec and then went to see the frame, it would feel like some side dishes. In short: Do not be framed by the nose walk, frame is your tool, it should listen to you!
Beginner Java Web Development, move away from the various frameworks and develop from the Servlet