Home  >  Article  >  Java  >  Detailed graphic explanation of Java Web project basics

Detailed graphic explanation of Java Web project basics

尚
forward
2019-11-27 14:19:383566browse

Detailed graphic explanation of Java Web project basics

1. Java Web module structure

JSP files are similar to AXPX files, and the paths and URLs correspond one to one. will be dynamically compiled into a separate class. The core of Java Web and ASP.NET are the Servlet and IHttpHandler interfaces respectively. Therefore, both the basic Page file (JSP, ASPX) method and the later developed MVC method (Spring MVC, ASP.NET MVC) are based on the core interface. Basically encapsulate and extend again (DispatcherServlet, MvcHandler). (Recommended: java video tutorial)

Except for JSP files, all other files are deployed in the WEB-INF subdirectory of the application directory. The WEB-INF directory can be considered as ASP.NET Store the web.config file, bin directory and runtime directory starting with App_ in a unified root directory.

Java Web's configuration file web.xml is also stored in the WEB-INF directory, while ASP.NET's configuration file web.config is generally stored directly in the application directory (other ASP.NET directories can also have web .config file). ASP.NET deploys all references and code-generated dlls in the bin, while Java Web's reference jars and generated classes are stored in the subdirectories lib and classes of WEB-INF respectively (Reference 1).

To sum up, similar to web.config, bin, App_Data, etc. in ASP.NET, WEB-INF, web.xml, lib and classes in Java Web are what we must understand and master.

|--Assembly Root
  |---WEB-INF/
    |--web.xml
    |--lib/
    |--classes/

1. WEB-INF directory: the root directory of Java Web files.

2. web.xml file: configuration file (asp.net web.config).

3. lib directory: stores class library files (asp.net bin).

4. Classes directory: stores class files (asp.net bin).

2. Basic structure of Java Web project [Eclipse Dynamic Web Project]

Eclipse Dynamic Web Project

( 1) You can configure the source code directory and output directory that need to be compiled. By default, the source files in the src directory are compiled to the build\classes directory.

(2) You can configure the root directory of WEB-INF, which defaults to WebContent.

(3) You can choose whether to generate a default web.xml file.

We create a Dynamic Web Proejct project named DynamicWP that generates web.xml by default. The file structure is as follows:

|--DynamicWP
  |--.settings/
  |--build/
    |--classes/
  |--src/
  |--WebContent/
    |--META-INF/
      |--MANIFEST.MF
    |--WEB-INF/
      |--web.xml
      |--lib/

The view of the DyanmicWP project in the Eclipse project explorer is as follows:

|--DynamicWP
  |--Deployment Desciptor
  |--JAX-WS Web Services
  |--Java Resources
  |--JavaScript Resources
  |--build
  |--WebContent
    |--META-INF/
      |--MANIFEST.MF
    |--WEB-INF/
      |--web.xml
      |--lib/

1. .settings is the Eclipse project folder, which stores various configurations of the Eslipse project. . Not visible in Eclipse project view.

2. The src directory stores the source code. Corresponds to Java Resources/src in the project view of Eclipse.

3. Build stores compiled files.

4. You can view the runtime file structure in a similar \workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\DynamicWP directory.

3. The basic structure of the Maven Web project

In view of the fact that there are many Java IDEs and all have certain supporters, Eclipse’s Java Web project Not portable. Maven not only solves the specification problem of project structure but also provides powerful functions such as powerful reference processing. It has become the current de facto standard in terms of project layout and other aspects. The main structure of the Maven project is as follows (reference 2):

|--root
  |--pom.xml
  |--src/
    |--main/
      |--java/
      |--resources/
      |--webapp/
    |--test/
      |--java/
      |--resources
  |--target/

Create a new Maven web app project in Eclipse. The file structure is as follows:

|--MavenWP
  |--pom.xml
  |--.project
  |--.classpath
  |--.settings/
  |--src/
  |--target/
    |--classes/
    |--m2e-wtp/

1. pom.xml: maven project configuration file.

2. The .project file and .classpath file as well as the files in the .settings directory and target/m2e-wtp directory are Eclipse project configuration files.

3, src and target: maven standard project directory.

Corresponding project resource management view in Eclipse4.5.1

|--MavenWP
  |--Deployment Desciptor/
  |--Java Resources/
  |--JavaScript Resources/
  |--Deployed Resources/
  |--src
  |--target
  |--pom.xml

1. The created project will add an index.jsp and report an error: use maven to search and add servlet dependencies, and then it will be normal after updating run.

2. Java build path problem warning: Use maven to search and add the compiler plug-in and configure the configuration node update to eliminate it.

3. To configure the maven image for the wall problem, I use http://maven.oschina.net/content/groups/public/.

4. Directories such as src/main/java, src/test/java and src/test/resources that are missing from the maven webapp created by default need to be added manually.

5. Modify .settings/org.eclipse.wst.common.project.facet.core.xml and update .

6. Modify the beginning of the web.xml root node as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">

Maven’s configuration file pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>me.test</groupId>
    <artifactId>MavenWP</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>MavenWP Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>MavenWP</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

4. Servlet basics

Just as the core of ASP.NET is IHttpHandler, the core of Java Web is the Servlet interface, located in the javax.servlet namespace. The concept of Filter can refer to ASP.NET's HttpModule, and the various Listeners in Servlet can refer to similar events in ASP.NET HttpApplicaiton.

Whether it is Java or .NET Web technology, they are all based on the specific implementation of the HTTP protocol. Some core items in Java Web and ASP.NET correspond as follows:

Detailed graphic explanation of Java Web project basicsSimplified diagram of Servlet and ASP.NET:

Detailed graphic explanation of Java Web project basics

用于简化web.xml配置的Servlet的注解(3.0开始支持,在ASP.NET中没有对应项):

(1)WebServlet:作用在javax.servlet.http.HttpServlet的实现类上。

(2)WebFilter:作用在javax.servlet.Filter的实现类上。

(3)WebListener:作用在Listener的实现类上(javax.servlet.ServletContextListener、javax.servlet.ServletContextAttributeListener、javax.servlet.ServletRequestListener、javax.servlet.ServletRequestAttributeListener、javax.servlet.http.HttpSessionListener、javax.servlet.http.HttpSessionAttributeListener)。

(4)WebInitParam:结合WebServlet和WebFilter注解用来配置属性。

(5)MultipartConfig:作用在javax.servlet.http.HttpServlet的实现类上。标注请求是mime/multipart类型。

用于Servlet容器初始化的ServletContainerInitializer(可实现无web.xml,3.0开始支持,可类比ASP.NET的Application_Start方法):

(1)Servlet容器启动时查找ServletContainerInitializer的实例。

(2)ServletContainerInitializer实例使用HandlesTypes标注一个或多个类型,Servlet容器将在启动时扫描classpath,获取这些类型的实例。

(3)Servlet容器在启动时调用ServletContainerInitializer实现类的onStartup方法,该方法可以获取HandlesTypes标注的所有类型对象。

五、自定义Session

Session在存储安全性要求较高的会话信息方面是必不可少的,Session当然绝对不是用来存储用户登录状态的,但类似验证码等敏感信息却必须存储在Session中。对于分布式Web应用自定义Session支持独立的状态服务器或集群是必须的。

ASP.NET通过SessionStateModule通过配置文件配置实际的Session提供程序,Session提供程序实现了SessionStateStoreProviderBase,因此在ASP.NET中实现自定义Session是通过继承SessionStateStoreProviderBase实现,配置Session是通过Web.config。

Detailed graphic explanation of Java Web project basics

同理,Java Servlet中使用自定义Session通过Filter可以实现。由于不同的servlet容器对Session的实现不同,所以通用性最好的方式是继承HttpServletRequestWrapper重写getSession方法返回自定义的Session对象。

(1)首先自定义继承HttpSession的MySession(为了便于演示,仅包装了容器的session并转发调用)。

import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

public class MySession implements HttpSession {

    private HttpSession _containerSession;

    public MySession(HttpSession session) {
        this._containerSession = session;
    }

    @Override
    public long getCreationTime() {
        return this._containerSession.getCreationTime();
    }

    @Override
    public String getId() {
        return this._containerSession.getId();
    }

    @Override
    public long getLastAccessedTime() {
        return this._containerSession.getLastAccessedTime();
    }

    @Override
    public ServletContext getServletContext() {
        return this._containerSession.getServletContext();
    }

    @Override
    public void setMaxInactiveInterval(int interval) {
        this._containerSession.setMaxInactiveInterval(interval);
    }

    @Override
    public int getMaxInactiveInterval() {
        return this._containerSession.getMaxInactiveInterval();
    }

    @SuppressWarnings("deprecation")
    @Override
    public HttpSessionContext getSessionContext() {
        return this._containerSession.getSessionContext();
    }

    @Override
    public Object getAttribute(String name) {
        return this._containerSession.getAttribute(name);
    }

    @SuppressWarnings("deprecation")
    @Override
    public Object getValue(String name) {
        return this._containerSession.getValue(name);
    }

    @Override
    public Enumeration<String> getAttributeNames() {
        return this._containerSession.getAttributeNames();
    }

    @SuppressWarnings("deprecation")
    @Override
    public String[] getValueNames() {
        return this._containerSession.getValueNames();
    }

    @Override
    public void setAttribute(String name, Object value) {
        this._containerSession.setAttribute(name, value);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void putValue(String name, Object value) {
        this._containerSession.putValue(name, value);
    }

    @Override
    public void removeAttribute(String name) {
        this._containerSession.removeAttribute(name);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void removeValue(String name) {
        this._containerSession.removeValue(name);
    }

    @Override
    public void invalidate() {
        this._containerSession.invalidate();
    }

    @Override
    public boolean isNew() {
        return this._containerSession.isNew();
    }

}

(2)自定义继承HttpServletRequestWrapper的MyRequest

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

public class MyRequest extends HttpServletRequestWrapper {

    public MyRequest() {
        super(null);
    }

    public MyRequest(HttpServletRequest request) {
        super(request);
        // TODO 自动生成的构造函数存根
    }

    @Override
    public HttpSession getSession(boolean create) {
        return new MySession(super.getSession(create));
    }

    @Override
    public HttpSession getSession() {
        return new MySession(super.getSession());
    }
}

(3)自定义Filter将Request包装为MyRequest

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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

@WebFilter("/*")
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO 自动生成的方法存根

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        chain.doFilter(new MyRequest((HttpServletRequest) request), response);

    }

    @Override
    public void destroy() {
        // TODO 自动生成的方法存根

    }

}

通过注解配置了Filter,也可以通过原始的web.xml方式配置。

小结:

你至少应该知道的:

(1)配置文件:ASP.NET的web.config和Java的web.xml

(2)Web核心:ASP.NET的IHttpHandler接口和Java的Servlet接口

(3)拦截器:ASP.NET的HttpModule和Java的Filter

(4)应用程序事件:ASP.NET的HttpApplication event和Java的各种Listener

(5)启动器:ASP.NET的Application_Start和Java的ServletContainerInitializer

(6)引用管理:ASP.NET的Nuget和Java的Maven

感想:

ASP.NET的核心对象不像Java Servlet一样,从一开始就基于接口,这是缺点。但Java Servlet的核心对象全靠容器实现,就连HttpSession同样如此,这也是缺点。比如自定义个Session十分麻烦,没有像ASP.NET一样简单配置即可。另外Servlet的一些抽象定义有点过头了,不够简洁。

更多java知识请关注java基础教程栏目。

The above is the detailed content of Detailed graphic explanation of Java Web project basics. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete