Java Web development for beginners, please stay away from various frameworks, from Servlet Development

Source: Internet
Author: User

[Reprinted from sweet potato, original post address] http://www.oschina.net/question/12_52027

The OSCHINA software library has a category-Web framework that contains nearly 500 projects in multiple programming languages.

Web framework is the best practice for developers to write Web application servers in a certain language. Many Web frameworks are extracted from actual Web projects and are only related to Web requests and Response Processing, forming a foundation, when developing other application projects, you can start from the basis of this separation, so that developers can pay more attention to more specific business problems, rather than control Web requests and responses.

There are many frameworks, but the routines are similar, helping you hide a lot of HTTP details and focus on function development.

But for a beginner, too early exposure to the framework is often half the battle! For the same question, you may need to study the framework from the beginning.

The following are some personal opinions and ideas on developing Web in Java for beginners.

1. Basic Requirements: Java programming Basics

It is necessary to have a good Java programming Foundation. When discussing Web development technology, a question about Java programming basics will be despised.

2. Environment preparation (Eclipse + Tomcat)

Select a Servlet container that you like, or an application server. We recommend lightweight products such as Tomcat, Resin, and Jetty. The three products can be used after downloading the zip package. If you are not familiar with Tomcat, please do not use Tomcat of the exe version, which will increase a lot of troubles. We do not recommend that you integrate Tomcat in Eclipse or other development environments, which will increase your worries.

Start the application server and access its default page.

About Development Tools

It is not recommended to use the JEE versions of MyEclipse and Eclipse. It increases your worries and runs slowly, and makes you unable to understand the structure of Web projects. Common Eclipse or your favorite development tools are enough to support normal Java project development.

For convenience, I made a basic Java project-ServletDemo.zip. You can import it to Eclipse as a complete and simple Web project.

Replace the following XML content with the conf/server. xml file in 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">      <Host name="localhost"><Context path="" docBase="D:\WORKDIR\ServletDemo\webapp" reloadable="true"/>      </Host>    </Engine>  </Service></Server>

3. understand Servlet and Filter. Replace D: \ WORKDIR \ ServletDemo with the imported project path. start Tomcat again and open http: // localhost in the browser: 8080/hello, you can see the output of Hello World.

Now, I have set up the environment. What should I do next?

The previous steps are to build a test environment and then let you know the structure of a basic Java Web project.

The jar package required by the most basic Java Web project only needs a servlet-api.jar, most of the classes in this jar package are interfaces, there are some tool classes, a total of 2 packages, are javax. servlet and javax. servlet. http. I put this jar package in an independent packages folder outside the webapp directory. This is because all Servlet containers carry this package and you do not need to put it in a Web project, we put it here only for compilation, and it is not required for running. If you just put the servlet-api.jar in webapp/WEB-INF/lib
Directory, a warning message is reported when Tomcat is started.

The Java Web project also requires a very important configuration file web. xml, which has been minimized by me and only keeps 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>

Another very important and useful interface in the Servlet specification is the Filter. Each servlet must be in the web. xml defines and configures URL ing. In the early stage, when Java developed Web without a framework, this file will define a large number of servlets, or someone simply calls a/servlet/* class name to save trouble.

The following is a simple 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 {@ Overridepublic void init (FilterConfig arg0) throws ServletException {System. out. println ("Filter initialization") ;}@ Overridepublic void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req; System. out. println ("intercepted URI =" + request. getRequestURI (); chain. doFilter (req, res) ;}@ Overridepublic void destroy () {System. out. println ("Filter ended ");}}

The configuration in web. xml must be placed before 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</filter-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><servlet-mapping><servlet-name>hello_world</servlet-name><url-pattern>/hello</url-pattern></servlet-mapping></web-app>

When accessing http: // localhost: 8080/hello, check the output information on the Tomcat console.

4. Relationship between Servlet and HTTP

Servlet is the most important part of J2EE. With Servlet, you are J2EE, and other aspects of J2EE need to be used. Servlet specifications you need to master servlet and filter technologies. The vast majority of frameworks are either servlet-based or filter-based. If they are to run on Servlet containers, they will never be able to leave this model alone.

Why does the Servlet specification have two packages, javax. servlet and javax. servlet. http. People who designed this specification earlier thought that Servlet is a service model and does not necessarily depend on a certain network protocol. Therefore, a javax is abstracted. servlet. It also provides an HTTP-based interface extension. However, from the years of actual operation, it seems that no Servlet technology is implemented on other protocols.

The javax. servlet and javax. servlet. http packages add up to a total of 34 interfaces and classes. You need to familiarize yourself with the specific meaning of each class and interface through the JavaDoc documentation of J2EE. 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

I emphasize that the two interfaces HttpServletRequest and HttpServletResponse should be more familiar.

If you cannot understand the meaning of a method literally, you can perform an experiment on the basis of the previous project to see its output. If not, you can go to the discussion board to ask a question. Such a question is very clear, many people can help you.

Why do I emphasize the two interfaces HttpServletRequest and HttpServletResponse so that Web development is inseparable from the HTTP protocol, while the Servlet specification is actually an object-oriented encapsulation of the HTTP protocol, HTTP requests and responses correspond to the HttpServletRequest and HttpServletResponse interfaces.

You can use HttpServletRequest to obtain all request-related information, including URI, Cookie, Header, and request parameters. Therefore, when you use a framework, you only need to obtain the HttpServletRequest instance to obtain the relevant information of the HTTP request.

The HttpServletResponse interface is used to produce HTTP responses, including cookies, headers, and response content.

5. Talk about the Session.

There is no definition of Session in the HTTP protocol. Session is generated by various programming languages based on the stateless nature of the HTTP protocol. The implementation is nothing more than a hash table on the server side. The Key of the hash table is the Cookie value passed to the browser named jsessionid.

When you need to save a value to the session, the container will perform the following steps:

A. Get the jsessionid value. If no value exists, generate one, that is, the request. getSession () method.

B. The obtained HttpSession object instance is equivalent to a hash table. You can store data (setAttribute) in the hash table)

C. You can also get a value through getAttribute.

The Cookie named jsessionid is automatically deleted when the browser is closed. Set the MaxAge value of the Cookie to-1 to disable automatic deletion by the browser.

6. About JSP

I have not used JSP for many years. Now I have been using the Velocity template engine.

Any JSP page is compiled into a Servlet-class file during execution. If it is Tomcat, these generated java files will be placed in the subdirectory of the corresponding project under the {TOMCAT}/work directory. For example, the class files generated by Tomcat are as follows:

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().getServletContext()).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, The javax. servlet. jsp package is defined in some interface specifications related to JSP. JSP is more convenient than servlet in that the modification can take effect immediately. Unlike servlet modification, you must restart the container to take effect.

Therefore, JSP is suitable for view, while servlet is suitable for control layer.

7. Summary

There are a lot of Luo Liluo, which are summarized as follows:

  • Do not learn any frameworks before learning servlet specifications.
  • Use the simplest tool without any wizard or visualization
  • Familiar with HTTP

When you have mastered the servlet specifications and then look at the framework, you will feel that some of the dishes are delicious. In a word, do not be led by the framework. The framework is your tool. It should listen to you!

Sweet potatoes can be sprayed at any time.

*****************************

Thank you for your excellent article! It is strongly recommended for beginners.

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.