JavaEE 突击 1 - Spring 框架的引入


一 . 为什么要学习框架?

  1. 学习框架相当于是从 “小作坊” 到 “工厂” 的升级 , “小作坊” 什么东西都需要自己做 , 而 “工厂” 不是 , “工厂” 是组件式装配 , 它的特点是 高效

比如我们的 Servlet 就相当于 “自行车” , 而我们的框架 , 就相当于 “摩托车” , 虽然 框架 是从 Servlet 进化来的 , 但是 “摩托车” 不比 “Servlet” 香 ?

  1. 框架更加易用 , 它相对来说比较简单 , 而且效率非常高

二 . 复习 Servlet 的创建

我们这里的 Servlet 创建 , 跟以前还有一点不一样 , 这次的 Servlet 创建更加高级

2.1 创建项目





点击 Finish

2.2 给项目添加引用

去我们的 Maven 中央仓库搜索 Servlet
链接直达

然后点进去找到 3.1.0 版本

那么我们之前说过这是 Tomcat 官方推荐我们的搭配
那么这次我带大家直接去看一眼
点进链接即可查看 Tomcat 官方推荐的版本

我们大家基本使用的都是 Tomcat 8.5.x 系列 , 按照 Tomcat 官方推荐 , 我们的 Servlet 应该使用 3.1 版本的
如果我们强行使用 4.0 / 5.0 / 6.0 版本的 , 那一定会出现问题 , 因为高版本的 Servlet 实现逻辑可能低版本的 Tomcat 就识别不了 , 在一些问题上就会报错

我们也把 3.1.0 版本的链接直接贴在这里
Servlet 3.1.0版本链接直达
把他的 Maven 复制到 pom.xml 的 <dependencies> 里面

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>


2.3 配置Maven为国内源

这个步骤非常重要 !!! 这也涉及到后面我们的 SSM 能否正常使用
打开项目配置界面(当前项目配置和新项目配置界面) , 检查并配置国内源
首先 , 我们需要关注两个位置
这两个位置 , 一个是当前项目配置 , 一个是新项目配置界面

我们先配置当前项目配置

2.3.1 当前项目配置

首先 , 点击 File , 然后点击 Settings
搜索 Maven


我们要先设置 settings.xml

打开文件资源管理器 , 在地址栏输入我们复制的内容

这是一种情况 , 那么我们只需要跳转到他的上一级即可


那么这个路径下面并没有 settings.xml
那就好办了 , 把这段代码复制下来创建个文件叫做 settings.xml , 然后拷贝到这个文件夹里即可

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.conf}/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
   <mirror>
        <id>alimaven</id>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>        
      </mirror>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

我也把这个分享出来
settings.xml

那么还有一种情况 , 那就是这个文件夹里面本来就有 settings.xml , 那么同学们说直接把你这串代码拷贝过去不就得了
告诉大家 , 不行 ! 这种情况只适用于没有 settings.xml 的同学
那么有 settings.xml 的同学怎么办 ?
用 VSCode 打开 settings.xml

那这段代码替换进去

<mirror>
        <id>alimaven</id>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>        
      </mirror>

最后 ok 即可

但是还没结束 , 我们还需要配置新项目配置界面

2.3.2 新项目配置界面


按照之前的步骤重新操作即可





那么我们为什么要修改镜像源呢 ?
正常情况是这样

但是国外仓库毕竟慢 , 我们国内的阿里云弄了一个 Jar 仓库(其实就是把人家专门的 Jar 仓库偷摸下载一份保存在自己这里 , 然后定期更新)

就因为其他镜像源不断偷摸的偷人家 Jar 仓库 , 导致人家的网站非常慢 , 所以现在访问 Maven 仓库就需要先验证你是不是机器人了


接下来 , 我们的用户就可以下载阿里云里面的依赖 , 跟中央仓库里面的依赖是一样的 , 只不过下载源在国内 , 下载速度会很快

2.3.3 重新下载 jar 包

我们强烈建议 : 之前下载的 jar 包可能不完整 , 所以要先删除之前的 jar 包

其实我们还存在一个东西 , 叫做本地仓库 , 因为从网络不断下载 , 这非常消耗带宽而且因为速度慢导致效率不高 , 所以产生了本地仓库 , 本地仓库就存储我们下载过的依赖 , 下次使用的时候直接去本地仓库里面找 , 就不用再去下载了
但是我们由于第一次没设置镜像源 , 就导致下载的 jar 包应该是不完整的 , 有可能缺胳膊少腿 , 所以在我们更换镜像源之后 , 就要删掉全部重新下载



接下来 , 我们重新下载 jar

然后我们新建个项目看一下效果



因为我们刚才把已有的依赖全部删除了 , 所以他会下载一会
下载之后的样子

2.4 完善项目路径

我们看目录结构 , 对比一下我们之前的目录结构 , 再看一下现在的目录结构

那么我们先不管 resources 这个文件夹 , 来自己创建一个 java 文件夹


然后 java 文件夹就创建好了

2.5 编写代码


要注意 : 我们目前操作的是新创建的 Maven 项目 , Servlet 依赖还没导入

导入之后如果 extends HttpServlet 报错的话 , 刷新一下即可

然后我们编写代码

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/hello")
public class Hello_Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("Hello Servlet");
    }
}

2.6 修改配置文件

<?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"
    metadata-complete="false">
</web-app>


2.7 安装 Smart Tomcat

安装过程跳过

2.8 运行项目

在 Smart Tomcat 里面添加咱们的这个项目




我们把 Content Path 修改成 Hello_Servlet
然后启动 Smart Tomcat
在浏览器的地址栏输入

127.0.0.1:8080/Hello_Servlet/hello



成功打印出来了

  • 24
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 45
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 45
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加勒比海涛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值