一、http协议
1、概述
HTTP协议,全称"超文本传输协议(HyperText Transfer Protocol)"
协议版本:
- [x] HTTP/1.0,发送请求,创建一次连接,获得一个web资源,连接断开。
- [x] HTTP/1.1,发送请求,创建一次连接,获得多个web资源,连接断开。
HTTP协议的特点
基于请求/响应模型的协议。请求和响应必须成对,先有请求后有响应。
浏览器是通过请求协议将数据传递到服务器,浏览器访问服务器几种方式: ,其中掌握的就是get和post方式,
下面我们使用抓包工具来分析get和post请求有何不同。
请求方式 | 请求说明 |
---|---|
OPTIONS | 返回服务器针对特定资源所支持的HTTP请求方法。也可以利用向Web服务器发送'*'的请求来测试服务器的功能性。 |
HEAD | 向服务器索要与GET请求相一致的响应,只不过响应体将不会被返回。这一方法可以在不必传输整个响应内容的情况下,就可以获取包含在响应消息头中的元信息 |
GET | 向特定的资源发出请求(a href="servlet"标签/js location.href="servlet",在浏览器输入网址) |
POST | 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST请求可能会导致新的资源的创建和/或已有资源的修改 |
PUT | 向指定资源位置上传其最新内容 |
DELETE | 请求服务器删除Request-URI所标识的资源 |
TRACE | 回显服务器收到的请求,主要用于测试或诊断 |
CONNECT | HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器 |
HTTP协议的结构
请求报文:浏览器给服务器发送的请求数据的格式。请求报文主要包括:请求行 ,请求头 ,请求体 。
响应报文:服务器给客户端(浏览器)响应的报数据格式。响应报文主要包括:响应行 ,响应头 ,响应体 ;
2、浏览器抓包(重要)
方法一:浏览器抓包
打开网页按F12、我使用的是360
方案二、模拟GET和POST方式提交并抓取数据
GET提交抓取数据:
demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>GET请求</h2>
<form action="/getServlet" method="get">
用户名:<input type="text" name="userName" value="zhangsan" /><br>
密码:<input type="text" name="pwd" value="123" /><br>
<input type="submit" value="提交"/>
</form>
<h2>POST请求</h2>
<form action="postServlet" method="post">
用户名:<input type="text" name="userName" value="zhangsan"/><br>
密码:<input type="text" name="pwd" value="123"/><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
java代码:
package com.sswblog.demo01;
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("/getServlet")
public class GetServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
html如图
POST提交获取数据
html如上:
java代码:
package com.sswblog.demo01;
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("/postServlet")
public class GetServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
3、请求报文
【请求行】
请求行位于请求报文的第一行,由:请求方式 url 协议/版本 组成
Request URL: http://localhost:8080/postServlet
Request Method: POST
【请求头】
位于请求行的下面,以键值对 的形式给服务器传递信息,有些请求头信息是非必须的。
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.9
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:25
Content-Type:application/x-www-form-urlencoded
Cookie:__guid=111872281.4307970305335101400.1535763888139.0208; JSESSIONID=01E036ABE43DC944D8BD94F70009665F
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/demo.html
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
【请求体】
get请求请求体为空;post请求的请求体传递请求参数 。
userName:zhangsan
pwd:123
二、request请求数据获取
1、概述
HttpServletRequest 对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求中的所有信息都封装在这个对象中,开发人员通过这个对象的方法,可以获得客户这些信息。
HttpServletRequest作用:
1. 获取请求行信息:请求方式,url和HTTP版本。
2. 获取请求头信息:浏览器类型,ip地址等。
3. 获取请求参数:url后面拼接的参数或者请求体中提交的参数;
2、获取数据
2.1、获取请求行信息、url、协议、版本
方法 | 说明 |
---|---|
String getMethod() | 获取请求方式的类型 |
StringBuffer getRequestURL() | 获取客户端发出请求完整URL |
String getRemoteAddr() | 获取IP地址 |
String getProtocol() | 获取当前协议的名称和版本 |
代码:
package com.sswblog.demo01;
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("/rowServlet")
public class rowServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求行的请求方式
String method = request.getMethod();
System.out.println("method = " + method);
//获取请求行的请求URL
StringBuffer requesturl = request.getRequestURL();
System.out.println("requesturl = " + requesturl);
//获取请求行的IP
String getaddr = request.getRemoteAddr();
System.out.println("getaddr = " + getaddr);
//获取请求行的协议版本号
String getprotocol = request.getProtocol();
System.out.println("getprotocol = " + getprotocol);
}
}
2.2、获取请求头信息
请求头是以 键值对 组成的
方法 | 作用 |
---|---|
String getHeader(String name) | 根据请求头的k关键字获取请求头信息 |
Enumeration getHeaderNames() | 返回此请求包含的所有头信息的枚举 |
请求头以键关键字如下表所示:
请求头key | 请求头value |
---|---|
referer | 浏览器通知服务器,当前请求来自何处,如果是直接访问,则不会有这个头。常用于:防盗链 |
If-modified-Since | 浏览器通知服务器,本地缓存的最后变更时间。与另一个响应头组合控制浏览器页面的缓存。 |
cookie | 与会话有关技术,用于存放浏览器缓存的cookie信息。 |
user‐agent | 浏览器通知服务器,客户端浏览器与操作系统相关信息 |
connection | 保持连接状态。Keep-Alive 连接中,close 已关闭 |
host | 请求的服务器主机名 |
content-length | 请求体的长度 |
content-type | 如果是POST请求,会有这个头,默认值为application/x-www-form-urlencoded,表示请求体内容使用url编码 |
accept | 浏览器可支持的MIME类型。文件类型的一种描述方式。 |
mime格式 | 浏览器请求数据的类型,例如: text/html ,html文件 text/css,css文件 text/javascript,js文件 image/*,所有图片文件 |
accept-encoding | 浏览器通知服务器,浏览器支持的数据压缩格式。如:GZIP压缩 |
accept-language | 浏览器通知服务器,浏览器支持的语言。各国语言(国际化i18n) |
演示:
package com.sswblog.demo01;
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;
import java.util.Enumeration;
@WebServlet("/headerServlet")
public class HeaderServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取user-agent对应的value值
String header = request.getHeader("user-agent");
System.out.println("header = " + header);
System.out.println("-------------");
//获取所有请求key信息
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()){
System.out.println(headerNames.nextElement());
}
}
}
2.3、获取请求体
get请求:get请求提交的数据是拼接在url后面的,如下图所示:
post请求:post请求的数据是在请求体中发送到后台的:
【请求体】
username: lisi
password: 1234
2.4、获取请求参数的方法:
方法名 | 描述 |
---|---|
String getParameter(String name) | getParameter获得指定参数名对应的值。如果没有返回null,如果只有多个获得第一个。 例如:username=jack |
String[] getParameterValues(name) | getParameterValues[] 获取请求数据key相同的多个数据 |
request.getParameterMap(); | 获得所有表单的数据 |
演示:
demo1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="requestServlet" method="post">
用户名:<input type="text" name="username"/><br/>
密码:<input type="text" name="password"/><br/>
爱好:<input type="checkbox" name="hobby"value="smoking"/> 抽烟
<input type="checkbox" name="hobby"value="drinking"/> 喝酒
<input type="checkbox" name="hobby" value="tangtou"/> 烫头 <br/>
学历:<select name="education">
<option value="gaozhong">高中</option>
<option value="dazhuan">大专</option>
<option value="benke">本科</option>
</select><br>
<input type="submit"value="post提交" />
</form>
</body>
</html>
Java代码:
package com.sswblog.demo01;
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;
import java.util.Arrays;
import java.util.Map;
@WebServlet("/requestServlet")
public class RequestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取用户名
String username = request.getParameter("username");
System.out.println("username = " + username);
String password = request.getParameter("password");
System.out.println("password = " + password);
//请求爱好
String[] hobby = request.getParameterValues("hobby");
System.out.println(Arrays.toString(hobby));
//获取表单所有信息
Map<String, String[]> maps = request.getParameterMap();
for (String[] map : maps.values()){
System.out.println(Arrays.toString(map));
}
}
}
三、request作用域
1、request生命周期
【一次请求和响应的完整流程】
1、浏览器向servlet发送请求
2、tomcat收到请求后,创建Request和Response两个对象,并将请求数据封装到request对象中,然后传递给Servlet
3、Servlet接收到请求后,调用doget或者dopost方法。处理浏览器的请求信息,然后通过Response返回信息
4、tomcat接收到返回的信息,返回给浏览器。
5、浏览器接收到返回消息后,tomcat销毁Request和Response两个对象,同时销毁这两个对象所获得的信息。
2、request域对象(重要)
request域对象,一个存储数据的区域对象.是把request当成一个容器来存储数据,request域存储数据主要是用于在两个servlet之间传递数据。request作为域对象,常用的方法如下
方法 | 说明 |
---|---|
void setAttribute(String name, Object o) | 往request域中设置值 |
Object getAttribute(String name) | 从request域中取值 |
void removeAttribute(String name) | 从request域中移除值 |
演示:
student类
package com.sswblog.demo01;
public class Student {
private int id;
private String name;
private String password;
public Student(String name, String password) {
this.name = name;
this.password = password;
}
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
Java代码:
package com.sswblog.demo01;
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("/valueServlet")
public class ValueServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Student student1 = new Student("zhansan","1234");
//向request存储值
request.setAttribute("msg","王五");
request.setAttribute("student",student1);
//获取值
String msg = (String)request.getAttribute("msg");
System.out.println("msg = " + msg);
//移除request值
request.removeAttribute("msg");
if (null == request.getAttribute("msg")){
System.out.println("没有获取到值");
}
Student student = (Student)request.getAttribute("student");
System.out.println("student = " + student);
}
}
3、请求转发(重要)
请求转发:在Servlet中。请求也可以从一个Servlet发起,然后请求到另一个Servlet或静态页面。
方法 | 说明 |
---|---|
RequestDispatcher getRequestDispatcher(String path) | 获取请求转发器(request对象方法) |
void forward(ServletRequest request, ServletResponse response) | 将请求转发到另一个资源(Servlet)上 |
演示一:从一个aServlet转发到bServlet
aServlet代码:
package com.sswblog.demo01;
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("/aServlet")
public class AServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("msg","张三");
request.getRequestDispatcher("/bServlet").forward(request,response);
}
}
bServlet代码:
package com.sswblog.demo01;
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("/bServlet")
public class BServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String msg = (String) request.getAttribute("msg");
System.out.println("msg = " + msg);
}
}
回车后,aServlet会转发到bServlet,我们可以从bServlet中获取域对象中的数据,查看控制台:
演示二:从一个Servlet转发到dispatcher.html
dispatcher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>转发到html静态资源</h1>
</body>
</html>
java代码:
package com.sswblog.demo01;
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("/aServlet")
public class AServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/dispatcher.html").forward(request,response);
}
}
浏览器访问:
四、登录案例
1、需求
完成一个完整的从前端到后台的登录案例
开发准备:
2、开发步骤:
1、新建数据库
2、前端js html css web文件夹
3、新建包 web service dao domain/entity utils
4、导入配置文件 c3p0-config.xml
5、导入jar包
6、启动tomcat查看页面和测试数据库连接
3、业务逻辑图:
![](https://img-blog.csdn.net/20181002104815559?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3Nzd3F6eA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
4、用户登录实现
4.1、数据库设计
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('1', 'zhangsan', '123456');
INSERT INTO `t_user` VALUES ('2', 'lisi', '123456');
INSERT INTO `t_user` VALUES ('3', 'wangwu', '123456');
INSERT INTO `t_user` VALUES ('4', 'zhaoliu', '123456');
4.2、登录页面
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>登录页面</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<div class="container text-center">
<form class="form-signin" action="http://localhost:8080/loginServlet">
<h2 class="form-signin-heading">登录页面</h2>
<input type="email" name="username" class="form-control" placeholder="用户名" required autofocus>
<input type="password" name="password" class="form-control" placeholder="密码" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
</form>
</div>
</body>
</html>
error.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户名或密码错误,请重新登录!</h1>
</body>
</html>
success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录成功!</h1>
</body>
</html>
4.3、后台环境
在src下创建如下包:
com.heima.login.web
com.heima.login.service
com.heima.login.dao
com.heima.login.bean
com.heima.login.utils
在WEB-INF目录下新建lib包、将jar包导入、并添加到library中、如下图:
4.4、工具类和c3p0-config.xml
创建JDBCUtils工具类、c3p0-config.xml复制到src目录下。代码如下
package com.sswblog.login.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class JDBCUtils {
private static ComboPooledDataSource dataSource = null;
private static JdbcTemplate jdbcTemplate = null;
static {
dataSource = new ComboPooledDataSource();
}
public static JdbcTemplate getJdbcTemplate(){
jdbcTemplate = new JdbcTemplate(dataSource);
return jdbcTemplate;
}
}
c3p0-config.xml
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db1</property>
<property name="user">root</property>
<property name="password">sswqzx</property>
</default-config>
</c3p0-config>
全部环境图:
5、编码
做好上面的准备后。我们就可以开始码代码了。
5.1、实体类User
package com.sswblog.login.bean;
public class User {
private int id;
private String username;
private String password;
public User(){}
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
5.2、web层LoginServlet
package com.sswblog.login.web;
import com.sswblog.login.service.UserService;
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("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//修改字符集
request.setCharacterEncoding("utf-8");
//得到用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//将用户名和密码传到service层
UserService service = new UserService();
boolean ulogin = service.login(username,password);
//判断ulogin状态
if (ulogin) {
request.getRequestDispatcher("/success.html").forward(request,response);
}else {
request.getRequestDispatcher("/error.html").forward(request,response);
}
}
}
5.3、service层
package com.sswblog.login.service;
import com.sswblog.login.bean.User;
import com.sswblog.login.dao.UserDao;
import java.util.List;
public class UserService {
public boolean login(String username, String password) {
//将数据传到dao层
UserDao userDao = new UserDao();
List<User> udao = userDao.login(username,password);
if (udao.size() == 0) {
return false;
}else {
return true;
}
}
}
5.4、Dao层代码
package com.sswblog.login.dao;
import com.sswblog.login.bean.User;
import com.sswblog.login.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class UserDao {
public List<User> login(String username, String password) {
//连接数据库返回查询数据
JdbcTemplate jdbcTemplate = JDBCUtils.getJdbcTemplate();
String sql = "select * from t_user where username = ? and password = ?";
List<User> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), username, password);
return list;
}
}
效果图:
五、面向接口编程
1、编程思想
面向接口编程:面向接口意味着面向抽象,将各个实体之间的耦合程度由组件之间的耦合提升到接口层次,由接口做为粘合剂去维护关系,让一个实体由依赖另一个实体,转变成依赖一个接口,将被依赖实体的变化隔绝于接口之外。
接口就是标准规范,一种规范约束,有了标准去遵守就容易扩展!我们只需要面向标准编程,而不用针对具体的实现类!面向接口编程好处:(1)抽象;(2)高内聚,低耦合,降低开发成本/维护成本
接口
package com.sswblog.login.Test;
public interface Database {
public abstract void getConnection();
}
实现类
package com.sswblog.login.Test;
public class Mysql implements Database {
@Override
public void getConnection() {
System.out.println("mysql数据库。。。");
}
}
实现类
package com.sswblog.login.Test;
public class Oracle implements Database {
@Override
public void getConnection() {
System.out.println("oracle数据库。。。。");
}
}
测试类
package com.sswblog.login.Test;
public class TestData {
public static void main(String[] args) {
// Database database = new Mysql();
Database database = new Oracle();
database.getConnection();
}
}
2、用户登录代码优化
数据库同上
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>登录页面</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<div class="container text-center">
<form class="form-signin" action="/loginStudentServlet" method="post">
<h2 class="form-signin-heading">登录页面</h2>
<input type="text" name="username" class="form-control" placeholder="用户名" required autofocus>
<input type="password" name="password" class="form-control" placeholder="密码" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
</form>
</div>
</body>
</html>
susscess.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录成功!</h1>
</body>
</html>
error.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户名或密码错误,请重新登录!</h1>
</body>
</html>
JDBCUtils
package com.sswblog.login.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class JDBCUtils {
private static ComboPooledDataSource dataSource = null;
private static JdbcTemplate jdbcTemplate = null;
static {
dataSource = new ComboPooledDataSource();
}
public static JdbcTemplate getJdbcTemplate(){
jdbcTemplate = new JdbcTemplate(dataSource);
return jdbcTemplate;
}
}
c3p0-config.xml
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db1</property>
<property name="user">root</property>
<property name="password">sswqzx</property>
</default-config>
</c3p0-config>
bean类Student
package com.sswblog.login.bean;
public class Student {
private int id;
private String username;
private String password;
public Student(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Student(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
web层LoginStudentServlet
package com.sswblog.login.web;
import com.sswblog.login.service.StudentService;
import com.sswblog.login.service.StudentServiceImpl;
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("/loginStudentServlet")
public class LoginStudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
StudentService service = new StudentServiceImpl();
boolean result = service.login(username,password);
if (result) {
request.getRequestDispatcher("/succes.html").forward(request,response);
}else {
request.getRequestDispatcher("/error.html").forward(request,response);
}
}
}
service层接口StudentService
package com.sswblog.login.service;
public interface StudentService {
boolean login(String username, String password);
}
service层实现类StudentServiceImpl
package com.sswblog.login.service;
import com.sswblog.login.bean.Student;
import com.sswblog.login.dao.StudentDao;
import com.sswblog.login.dao.StudentDaoImpl;
import java.util.List;
public class StudentServiceImpl implements StudentService {
@Override
public boolean login(String username, String password) {
StudentDao dao = new StudentDaoImpl();
List<Student> studentList = dao.login(username,password);
if (studentList.size() ==0){
return false;
}else {
return true;
}
}
}
dao层接口StudentDao
package com.sswblog.login.dao;
import com.sswblog.login.bean.Student;
import java.util.List;
public interface StudentDao {
List<Student> login(String username, String password);
}
Dao层实现类StudentDaoImpl
package com.sswblog.login.dao;
import com.sswblog.login.bean.Student;
import com.sswblog.login.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class StudentDaoImpl implements StudentDao {
@Override
public List<Student> login(String username, String password) {
JdbcTemplate jdbcTemplate = JDBCUtils.getJdbcTemplate();
String sql = "select * from t_user where username = ? and password = ?";
List<Student> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class), username, password);
return list;
}
}