2021-12-31 IDEA创建Maven Webapp项目

OS:macOS High Sierra (Version: 10.13.6)

IDEA:IntelliJ IDEA 2020.1.4 (Community Edition)

Database: MariaDB 10.1.13 (MariaDB是MySQL源代码的一个分支)

Java, Maven 和 IDEA 的安装配置过程,见 IDEA创建Maven Quickstart项目


1. 在 IDEA上创建 Maven Webapp 项目

    New Project -> Project Type: Maven -> Project SDK: 1.8 -> Select maven-archtype-webapp: Next

        Name: MavenWebapp

        GroupId: com.example

        ArtifactId: MavenWebapp

    -> Finish

    生成的项目目录结构

        |-- src

        |      |-- main

        |          |-- webapp

        |                  |-- WEB-INF

        |                  |         |- web.xml

        |                  |-- index.jsp

        |-- pom.xml


2. 使用 tomcat7-maven-plugin, 将 tomcat 内嵌运行

    1) 修改 pom.xml:

        

            

                

                    

                        org.apache.tomcat.maven

                        tomcat7-maven-plugin

                        2.2

                                       

                            /

                            9090

                            UTF-8

                        

                    

                

            

        

        *注: path 项目访问路径, 本例:localhost:9090, 如果配置的aa,则访问路径为localhost:9090/aa;uriEncoding 非必选项。

        2) 运行

            Run -> Edit configurations -> Click "+" -> Select "Maven"

                Command line: clean tomcat7:run

                Name: MavenWebapp [clean,tomcat7:run]

                Before Launch:

                    Click "+", select "Launch Web Browser"

                    Browser: default

                    Url: http://localhost:9090

            -> OK

            Run -> Run "MavenWebapp [clean,tomcat7:run]"

            * tomcat7 除了支持 run, 还可以支持如下 Goal: 

                        help, deploy, deploy-only, redeploy, redeploy-only, undeploy,

                        exec-war, exec-war-only, run-war, run-war-only,

                        standalone-war, standalone-war-only,  shutdown

        3) 打包 War

            Run -> Edit configurations -> Click "+" -> Select "Maven"

                Command line: clean tomcat7:run-war

                Name: MavenWebapp [clean,tomcat7:run-war]

                Before Launch:

                    Click "+", select "Launch Web Browser"

                    Browser: default

                    Url: http://localhost:9090

            -> OK

            Run -> Run "MavenWebapp [clean,tomcat7:run-war]"

            可见到 target/MavenWebapp.war


3. 导入 Servlet 依赖包

    访问 http://www.mvnrepository.com/,查询 Servlet

    修改 pom.xml:

        

            

                ...

               

                

                      javax.servlet

                      javax.servlet-api

                      4.0.1

                      provided

                 

                  ...

            

        

        在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project


4. 添加基于 web.xml 的 Servlet

    1) 添加 src/main/java/com/example/BaseXmlServlet.java ,如果src/main/java 目录不存在,新增该目录并把它 Mark as "Sources Root"

        package com.example;

        import java.io.IOException;

        import java.io.PrintWriter;

        import javax.servlet.ServletConfig;

        import javax.servlet.ServletException;

        import javax.servlet.http.HttpServlet;

        import javax.servlet.http.HttpServletRequest;

        import javax.servlet.http.HttpServletResponse;

        public class BaseXmlServlet extends HttpServlet {

            protected void doGet(HttpServletRequest request, HttpServletResponse response)

                        throws ServletException, IOException {

                ServletConfig config = getServletConfig();

                response.setContentType("text/html;charset=UTF-8");

                PrintWriter writer = response.getWriter();

                writer.write(config.getServletName() + " -> doGet()
");

                writer.close();

            }

            protected void doPost(HttpServletRequest request, HttpServletResponse response)

                        throws ServletException, IOException {

                //doGet(request, response);

            }

        }

        2) 修改 src/main/webapp/WEB-INF/web.xml

            

               ...

               

                    BaseXmlServlet

               

               

                   BaseXmlServlet

                   com.example.BaseXmlServlet

                   1

               

               

                    BaseXmlServlet

                    /

                

                ...

            

        3)  从 web.xml 读取 context-param参数

                修改  src/main/webapp/WEB-INF/web.xml

                

                    ...

                    

                        Username

                        Webapp

                    

                    

                        Url

                        http://www.jianshu.com

                    

                    ...

                

              添加代码到 BaseXmlServlet.java :

                import java.util.Enumeration;

                import javax.servlet.ServletContext;

                ...

                ServletContext context = request.getServletContext();

                Enumeration initParameterNames = context.getInitParameterNames();

                while (initParameterNames.hasMoreElements()) {

                    String initParamName = initParameterNames.nextElement();

                    String initParamValue = context.getInitParameter(initParamName);

                    writer.write(initParamName + ":  " + initParamValue + "
");

                }

      访问 http://localhost:9090


5. 添加基于注解 @WebServlet 的 Servlet

    1) 添加 src/main/java/com/example/BaseAnnotationServlet.java

        package com.example;

        import java.io.IOException;

        //import java.io.PrintWriter;

        import java.io.OutputStream;

        import javax.servlet.ServletConfig;

        import javax.servlet.ServletException;

        import javax.servlet.http.HttpServlet;

        import javax.servlet.http.HttpServletRequest;

        import javax.servlet.http.HttpServletResponse;

        import javax.servlet.annotation.WebServlet;

        import javax.servlet.annotation.WebInitParam;

        @WebServlet(name = "BaseAnnotationServlet",

            urlPatterns = {"/annotation" },

            description = "des full",

            loadOnStartup = 1,

            asyncSupported = false,

            initParams = {

                @WebInitParam(name = "name1", value = "value 1", description = "des 1"),

                @WebInitParam(name = "name2", value = "value 2", description = "des 2")

         }) 

        public class BaseAnnotationServlet extends HttpServlet {

            protected void doGet(HttpServletRequest request, HttpServletResponse response)

                    throws ServletException, IOException {

                ServletConfig config = getServletConfig();

                String strOutPut = config.getServletName() + " -> doGet()
";

                strOutPut += "name1: " + config.getInitParameter("name1") + "
";

                strOutPut += "name2: " + config.getInitParameter("name2") + "
";

                response.setContentType("text/html;charset=UTF-8");

                OutputStream os = response.getOutputStream();

                os.write(strOutPut.getBytes());

            }

            protected void doPost(HttpServletRequest request, HttpServletResponse response)

                    throws ServletException, IOException {

                //doGet(request, response);

            }

        }

    2) 读取资源文件

        添加 src/main/resources/config.properties, 如果src/main/resources 目录不存在,新增该目录并把它 Mark as “Resources Root”,增加如下内容:

            db_driverClassName=org.mariadb.jdbc.Driver

            db_url=jdbc:mysql://localhost/testdb?characterEncoding=utf8

            db_username=root

            db_password=123456

        用 Servlet 的 getClass() 导入资源文件。

        添加代码到BaseAnnotationServlet.java:

            import java.io.InputStream;

            import java.util.Properties;

            ...

            InputStream resStream = this.getClass().getResourceAsStream("/config.properties");

            Properties properties = new Properties();

            properties.load(resStream);

            writer.write("Config Properties
");

            writer.write("db_driverClassName: " + properties.getProperty("db_driverClassName") + "
");

            writer.write("db_url: " + properties.getProperty("db_url") + "
");

            writer.write("db_username: " + properties.getProperty("db_username") + "
");

            writer.write("db_password: " + properties.getProperty("db_password") + "
");

            ...

        访问 http://localhost:9090/annotation

你可能感兴趣的:(2021-12-31 IDEA创建Maven Webapp项目)