Maven
什么是框架?
即baiframework。指的是实现了某应用领域通用完备功能的底层服务。使用这种框架的编程人员可以在一个通用功能已经实现的基础上开始具体的系统开发。框架提供了所有应用期望的默认行为的类集合。具体的应用通过重写子类(该子类属于框架的默认行为)或组装对象来支持应用专用的行为。可以提高开发效率。
什么是Maven?
描述
- Maven Project — Apache的优秀开源项目, 基于项目对象模型,可以通过一小段描述信息来管理项目的构建、报告和文档的软件项目管理工具。
- 用Maven可以方便的创建项目,基于archetype可以创建多种类型的java项目。
- Maven仓库对jar包(artifact)进行统一管理,避免jar文件的重复拷贝和版本冲突。
- 团队开发,Maven管理项目的RELEASSE和SNAPSHOT版本,方便多模块的项目中,各个模块之间的快速集成。
优势
- 约定大于配置
- 使用简单
- 测试支持
- 构建简单
- 插件丰富
约定大于配置
1.约定是什么意思?
在开发的时候,很多时候有些东西如果你没有配置的话,程序就会取一个默认值,而这个默认值就是约定,也可以理解为:因为他有默认值,我就不需要在配置了,它会自动用默认值,比如说约定好了maven的结构中:
/src/main/java目录用来存放java源文件,所以我从来没配置过maven结构。
2.配置是什么意思?
我觉得就是配置,就是比如说要用servlet的时候,你要去web.xml中配置servlet程序的访问地址;如果你不配置程序就找不到了,因为那个servlet是你自己创建的类实现的接口,程序没有提前约定好你创建的那个类的地址,所以你就要配置。
约定大于配置:我觉得是这个意思:就是比如说大家提前都约定好了创建对象就要使用new关键字,你要是想创建这个对象,那就要先使用new,你要先按照大家约定好的去做,然后在使用这个对象去做你想做的。你要是连大家约定好的都不做,那哪来的对象?我觉得这句话更像是一个代码界的法律吧,一种写代码的行为规范。
Maven下载安装
下载
这里也不用你去下载了,我给大家准备好了压缩包
安装
免安装,谢谢,使用教师提供的maven安装包
配置
个人仓库
- 打开你解压好的这个文件
- 在这个文件内部新建一个文件夹,用作于你自己的Maven本地仓库
- 名字呢随意,我这个名字略显得粗糙,我百度查阅了一下仓库这个单词
- 各位随意
- 在这个文件下面我创建了一个仓库,所谓的仓库是一种专业术语,土味话是建一个文件夹用来存放你下载的jar包,这时也许有人就会疑惑,maven既然可以从网上下载jar包,朕的网速宇宙第一,为什么要配置这个,如果真的这样,什么无产阶级的我目瞪狗呆,无fuck可说,但是maven的大致流程是,项目在通过pom.xml文件加载jar包的过程中,首先回来到本地仓库寻找jar包,如果没有,则会根据setting.xml文件配置的中央仓库联网下载。本地maven jar包存放文件夹的目的在于避免二次下载。
环境变量
MAVEN_HOME
点击path,添加下面这个
%MAVEN_HOME%\bin
那就需要写分号: ;%MAVEN_HOME%\bin;
配置路径地址:D:\Maven相关文件\apache-maven-3.8.4\bin
查看是否配置成功,打开cmd,输入下面的代码
mvn -v
配置文件的修改
- 请使用你尊贵的小手点击该解压包下的conf文件,conf意为配置,这是我们Maven的配置文件夹
- 点开这个settings.xml文件,我们接下来需要对文件进行配置
本地仓库
点进去之后,找到差不多50多行的样子,找到这个—/path/to/local/repo,这个是被注释掉了的,复制下来
这里放你自己设置的本地仓库路径哈
中央仓库
这个本地仓库连接着中央仓库,当你需要使用一些没有使用过的jar包的时候,本地仓库没得的时候会从中央仓库中拉取,但是这个中央仓库在国外,没有翻墙软件或者vpn的话那个访问速度懂得都懂,所以国内的阿里,做的云服务器,这个服务器里面就放了我们日常开发中的绝大部分的jar包,仓库地址等等,阿里yyds,我们平常使用Maven框架的时候都会连接阿里的云服务器进行下载
比话说完,找到我们的mirrors标签,大概在150行左右
粘贴,只需要在mirros当中粘贴mirror,这里提供了两个,一个带注释一个不带注释的,自己选一个粘贴
<mirrors>
<!-- 阿里云公共仓库镜像 -->
<mirror>
<!--镜像唯一标识:id用来区分不同的mirror元素。 -->
<id>alimaven</id>
<!--镜像名称 -->
<name>aliyun maven</name>
<!--阿里云仓库地址:构建项目时会优先从该仓库获取依赖 -->
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<!--镜像服务器的id:
例如,如果我们要设置一个Maven中央仓库(http://repo1.maven.org/maven2)的镜像,
就需要将该元素设置成central。这必须和中央仓库的id central完全一致。-->
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
jdk配置
在最后配置jdk,也要夹在两个profiles标签之间(我这里使用的为jdk8),建议先配置8,因为在idea中可以手动修改
<profiles>
<profile>
<id>jdk-1.8</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
.m2
将你刚刚写好的setting.xml文件复制粘贴到用户目录下的.m2文件夹下
打开cmd,输入下面的代码
mvn help:system
偷鸡,整个setting文件的配置
<?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.2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 https://maven.apache.org/xsd/settings-1.2.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>
-->
<!-- 配置本地仓库 -->
<localRepository>D:\Maven相关文件\apache-maven-3.8.4\Maven_CK</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
| 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>
-->
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</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>
<id>jdk-1.8</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
<!-- 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>
idea使用Maven
打开你们的idea
文件,设置,搜索框输入Maven
一个简单的Web项目
项目结构
点开我们的pom.xml文件,设置其打包方式为war包形式
<!-- 这是一个web项目 -->
<packaging>war</packaging>
tomcat
Maven插件
GAV坐标
我们在Maven项目当中需要使用某些被封装好的功能的时候,就需要从本地仓库or阿里仓库当中去获取,获取的是别人为我们封装好的接口、实现类、工具类等等,我们可以通过导包的方式对这些接口进行集成or实现,这是我们导入的目的
那么什么是GAV坐标呢?
我们来写个servlet吧,servlet的编写需要什么?jar包嘛,还需要在xml配置文件中对servlet进行配置,我现在告诉你,不用这样了,我们只需要一个坐标即可
<!--
groupId和artifactId是maven管理项目包时用作区分的字段,就像是地图上的坐标。
artifactId:artifactId一般是项目名或者模块名。
groupId:groupId分为几个字段,例如cn.com.fullstack,前面的com叫【域】,后面的是你自己起的域名。
groupId一般分为多个段,这里我只说两段,第一段为域,第二段为公司名称。域又分为org、com、cn等等许多,其中org为非营利组织,com为商业组织。
-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--
举个apache公司的tomcat项目例子:这个项目的groupId是org.apache,它的域是org(因为tomcat是非营利项目),公司名称是apache,artigactId是tomcat。
-->
pom.xml
https://mvnrepository.com/artifact/mysql/mysql-connector-java
<dependencies>
<!-- servlet相关 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!--导入mysql和mybatis的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- mysql驱动,也可以理解为jdbc -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- jstl标签库和taglibs标签的依赖来使用jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 日志相关 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
Servlet模板
设置当中搜索File and Code Templates
找到web下的java代码模板
选择Servlet Annotated Class.java
原始模板很难看,我们自己设定一个
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/${Entity_Name}")
public class ${Class_Name} extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
this.doGet(request, response);
}
}
jdbc搭建
数据库的配置
数据库的搭建
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID' auto_increment,
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
password VARCHAR(20) NULL DEFAULT NULL COMMENT '密码',
PRIMARY KEY (id)
);
添加数据
INSERT INTO user (id, name, age, email,password) VALUES
(1, 'Jone', 18, 'test1@baomidou.com','123123'),
(2, 'Jack', 20, 'test2@baomidou.com','456456'),
(3, 'Tom', 28, 'test3@baomidou.com','789789'),
(4, 'Sandy', 21, 'test4@baomidou.com','111111'),
(5, 'Billie', 24, 'test5@baomidou.com','753951');
增删改查
使用jdbc
jdbc编程6步
- 加载驱动
- 建立连接
- 预处理SQL语句
- 执行SQL语句
- 处理SQL语句响应的结果集
- 释放资源
找不到类异常
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
找不到什么类啊?com.mysql.jdbc.Driver,那这个类在哪儿呢?
类型不匹配
简答简单来说就是你的数据类型和数据库当中的类型不匹配
条件查询
什么是条件查询?我可以根据某几个字段的名称,到数据库当中查询到我想要的信息
来温习一下刚刚的步骤吧
@Test
public void select() throws SQLException, ClassNotFoundException {
String url = "jdbc:mysql://localhost:3306/week11111?characterEncoding=utf8";
String userName = "root";
String password = "010115";
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取连接
Connection connection = DriverManager.getConnection(url,userName,password);
// 预处理SQL语句
PreparedStatement pst =
connection.prepareStatement(" select * from user where age < ?");
// 参数占位符填充
pst.setString(1,"24");
// 处理返回的结果集
ResultSet resultSet = pst.executeQuery();
while(resultSet.next()){
System.out.print(resultSet.getInt("id")+" ");
System.out.print(resultSet.getString("name")+" ");
System.out.print(resultSet.getString("age")+" ");
System.out.print(resultSet.getString("email")+" ");
System.out.print(resultSet.getString("password"));
System.out.println();
}
// 释放资源
resultSet.close();
pst.close();
connection.close();
}
封装工具类
package com.tf.utils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
// 请求工具类
public class DBAccess {
// 公共的两部分:1建立连接、2资源释放
// 想要程序一运行就能建立连接,连接需要的东西都写成static静态的,最先执行的。
private static String driver;
private static String url;
private static String userName;
private static String password;
static {
// 读取配置文件
Properties p = new Properties();
try {
p.load(new BufferedReader(new FileReader("D:\\spring-springboot\\Week11111\\src\\main\\resources\\jdbc.properties")));
// 映射赋值
driver = p.getProperty("mysql.driver");
url = p.getProperty("mysql.url");
userName = p.getProperty("mysql.userName");
password = p.getProperty("mysql.password");
// 加载驱动
Class.forName(driver);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 建立连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, userName, password);
}
// 2.释放资源
public static void close(ResultSet rs, PreparedStatement pst, Connection con) throws SQLException {
close(rs);
close(pst);
close(con);
}
public static void close1(PreparedStatement pst, Connection con) throws SQLException {
close(pst);
close(con);
}
private static void close(Connection con) throws SQLException {
if (con != null) {
con.close();
}
}
private static void close(PreparedStatement pst) throws SQLException {
if (pst != null) {
pst.close();
}
}
private static void close(ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
}
}
工具类–查询全部
/**
* 查询全部学生
* @param sql SQL语句
* @param clz 需要被映射的类
* @return List集合
* @throws Exception
*/
public List<T> executeQuery(String sql, Class clz) throws Exception {
List<T> list = new ArrayList<T>();
// 建立连接
Connection con = DBAccess.getConnection();
// 预处理sql语句
PreparedStatement pst = con.prepareStatement(sql);
// 执行sql语句
ResultSet rs = pst.executeQuery();
// 处理执行sql的结果
// 将我们处理的结果集中的内容封装到对象当中
T t;
while (rs.next()) {
// 反射,初始化泛型对象t
t = (T) clz.newInstance();
// 获取对象的所有属性
Field[] fields = clz.getDeclaredFields();
for (Field f : fields) {
// System.out.println("该属性为:"+f);
f.setAccessible(true);
// System.out.println("f.getName()值为:"+f.getName());
f.set(t, rs.getObject(f.getName()));
f.setAccessible(false);
}
list.add(t);
}
// 释放资源
DBAccess.close(rs, pst, con);
return list;
}
工具类–条件查询单个
/**
* 条件查询,单条数据
* @param sql
* @param clz
* @param name
* @return
* @throws Exception
*/
// 条件查询,单个
public T executeQueryName(String sql, Class clz,String name)throws Exception{
// 建立连接
Connection con = DBAccess.getConnection();
// 预处理sql语句
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1,name);
// 执行sql语句
ResultSet rs = pst.executeQuery();
// 处理执行sql的结果
T t = null;
if (rs.next()) {
// 反射
t = (T) clz.newInstance();
// 获取对象的所有属性
Field[] fields = clz.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
f.set(t, rs.getObject(f.getName()));
f.setAccessible(false);
}
t = t;
}
// 释放资源
DBAccess.close(rs, pst, con);
return t;
}
工具类–修改数据
// 修改数据
public Integer updateUserInformation(String sql,Class cls,String id,String psw) throws SQLException {
// 建立连接
Connection connection = DBAccess.getConnection();
// 预处理SQL语句
PreparedStatement pst = connection.prepareStatement(sql);
//
pst.setString(1,psw);
pst.setString(2,id);
// 执行SQL语句
int i = pst.executeUpdate();
if(i==1){
System.out.println("修改成功!");
}
// 释放资源
DBAccess.close1(pst,connection);
return i;
}
工具类–删除数据
//删除数据
public Integer deleteUser(String sql, Class clz,String id) throws SQLException {
// 建立连接
Connection con = DBAccess.getConnection();
// 预处理sql语句
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1,id);
// 执行sql语句
int i = pst.executeUpdate();
if(i==1){
System.out.println("删除成功!");
}
// 释放资源
DBAccess.close1(pst,con);
return 1;
}
小项目
注册功能编写
JSP页面分析
通过输入框中输入的四个内容,点击表单提交到该请求的资源路径下–register
Servlet编写
-
获取表单当中传递过来的数据
-
// 获得表单当中的数据 String username = request.getParameter("name"); String age = request.getParameter("age"); String email = request.getParameter("email"); String password = request.getParameter("password");
-
-
封装到user对象当中
-
// 封装在user对象当中 User user = new User(); user.setName(username); user.setAge(Integer.valueOf(age)); user.setEmail(email); user.setPassword(password);
-
-
调用封装的jdbc工具类对业务进行查询
-
判断用户是否存在—请求转发
-
插入记录
-
返回到登录页面
Get&Post
这是之前为同学们定义的表单,两个输入框用 name 属性唯一区别,也就是一个 Key;输入的内容就是一个 Value。所以,表单就是一个 Key/Value(键值对)集合。
<form >
username:<input type="text" name="username"><br>
password:<input type="text" name="password"><br>
<input type="submit" value="Login">
</form>
抛出两个问题:①表单是如何发送数据的?②表单怎么封装数据?
XMLHttpRequest
根据 MDN,form 是通过 XMLHttpRequest 对象提供的 send() 函数来发送数据。XMLHttpRequest 在 AJAX 编程中被大量使用。
XMLHttpRequest.send(FormData data);
XMLHttpRequest.send(URLSearchParams data);
表单 GET 请求
**form 默认的请求方式是 GET。如果 GET 带有查询参数,直接交给 URLSearchParams 封装;得到一个类似于 **
**http://localhost/search?username=111&password=111
**
的 URL(请求目标)。打开浏览器控制台抓取表单发送的“请求网址”时,最后的 URL 是下图这样的:
表单 POST 请求
POST 请求方式不明文显示查询参数,
而是把表单数据放在了请求体(Body)中。
打开浏览器控制台抓取表单发送的“请求网址”时,最后的 URL 是下图这样的:
HTTP请求数据
HTTP 的请求体数据必须符合规定才能让服务器识别、解析。所以 Content-Type 显得非常重要。form 的请求方式是 POST 时,Content-Type 默认是 application/x-www-form-urlencoded,表示请求体数据以键值对的形式发送。
登录功能的实现
JSP页面分析
${pageContext.request.contextPath}是JSP取得绝对路径的方法,等价于<%=request.getContextPath()%> 。
也就是取出部署的应用程序名或者是当前的项目名称
取出来的就是/demo1**,而"/"代表的含义就是**http://localhost:8080****
Servlet编写
- 获取用户登录表单的数据
- 封装实体
- 判断—成功or失败
- 重定向?请求转发?
登录成功后页面的编写
页面分析
<%-- 引入JSTL标签库 --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>