Servlet入门
一.Servlet概述
Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,具有独立于平台和协议的特性,主要功能在于交互式地浏览和生成数据,生成动态Web 内容。
狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口 的类,一般情况下,人们将Servlet理解为后者。Servlet运行于支持Java的应用服务器 中。从原理上讲,Servlet可以响应任何类型的请求,但绝大多数情况下Servlet只用来扩展基于HTTP 协议的Web服务器。
最早支持Servlet标准的是JavaSoft的Java [Web Server](https://baike.baidu.com/item/Web Server/9306055?fromModule=lemma_inlink),此后,一些其它的基于Java的Web服务器开始支持标准的Servlet。
Java操作数据库依赖于JDBC的技术,有了JDBC,所以java和数据库就产生了联系。如果前端要与java代码产生联系,就必须要有一个类似于JDBC的东西,这就是Servlet。
二.Servlet快速入门
仿登录:用户在登录页面输入账号和密码,Servlet获取到用户输入的内容
1.HTML页面
HTML
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action= "" method="get">
账号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
2.实现Servlet
创建类,并实现Servlet接口,重写Service方法
Java
复制代码
package com.test.servlet;
import javax.servlet.*;
import java.io.IOException;
public class LoginServlet implements Servlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
throws ServletException, IOException {
String name = servletRequest.getParameter("username");
String password = servletRequest.getParameter("password");
System.out.println(name+","+password);
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
3.注册Servlet
在web.xml文件中注册servlet, 作为前后台连接的中间件
xml
复制代码
<?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_4_0.xsd"
version="4.0">
<!--注册Servlet-->
<servlet>
<!--给要注册的Servlet取别名-->
<servlet-name>LoginServlet</servlet-name>
<!--要注册的Servlet的完全限定名-->
<servlet-class>com.test.servlet.LoginServlet</servlet-class>
</servlet>
<!--给Servlet设置访问路径-->
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<!--访问路径,最前面必须是/,代表根-->
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
</web-app>
4.添加表单请求地址
HTML
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action= "loginServlet" method="get">
账号:<input type="text" name="username"><br>
密码:<input type="password" name="pwd"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
5.loginServlet测试
通过浏览器输入对应的地址来访问测试
输入账号(非中文)密码,点击登录
6.测试运行流程
点击登录(将数据按照action指定的路径提交)
web.xml的url-pattern标签
找到servlet-name标签
找到servlet-class标签
找到指定的Servlet类
自动执行该类的service方法
三.Servlet与Tomcat关系
Tomcat在初始化Servlet时,会自动读取web.xml文件的内容,并根据当中的相关设置,生成ServletConfig和ServletContext对象。
同时会创建ServletRequest和ServletResponse交给Servlet实例,service方法就有了这两个参数。
四.Servlet体系机构
1.体系结构
基于Http协议的web项目
Servlet直接继承HttpServlet即可
2.doGet()与doPost()的调用情况
(1)doGet()的调用
a.创建test.html页面
HTML
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="testServlet" method="get">
<input type="submit" value="测试">
</form>
<a href="testServlet">测试</a>
</body>
</html>
b.创建TestServlet.java
Java
复制代码
package com.test.servlet;
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;
public class TestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doPost");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doGet");
}
}
c.doGet()调用总结
a标签发送请求时
form表单的method属性值为get
form表单未设置method属性
通过路径直接访问Servlet
(2)doPost()的调用
a.创建test.html页面
html
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="testServlet" method="post">
<input type="submit" value="测试">
</form>
</body>
</html>
b.创建TestServlet.java
java
复制代码
package com.test.servlet;
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;
public class TestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doPost");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doGet");
}
}
c.doPost()调用总结
3.doGet()与doPost()调用的原因
请求到达时,自动调用从HttpServlet中继承来的service方法,该方法中,会根据请求方式的不同,调用对应的doXxx()
若doXxx()方法重写,所以,最终调用的就是自己写的doXxx()。
4.get和post的区别
请求方式
地址携带数据
提交数据量
浏览器缓存
效率
Get
显示到浏览器地址栏最后
较少
会
较高
Post
不会
较多
不会
较低
五.简单登录
1.使用技术
HTML+Servlet+C3P0+DBUtils+MySQL
2.示例步骤
(1)创建数据库及数据表
sql
复制代码
CREATE DATABASE test;
USE test;
CREATE TABLE manager(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(20) NOT NULL UNIQUE,
password VARCHAR(20) NOT NULL
);
(2)创建模块
(3)登录页面
HTML
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="" method="get">
账号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
(4)在entity包中创建Manager.java
java
复制代码
package com.test.entity;
public class Manager {
private int id;
private String username;
private String password;
public Manager() {
}
public Manager(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 "Manager{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
(5)在dao包中创建ManagerDao.java
java
复制代码
接口:
package com.test.dao;
import com.test.entity.Manager;
public interface ManagerDao {
Manager login(String username,String password);
}
实现类:
package com.test.dao.impl;
import com.test.dao.ManagerDao;
import com.test.entity.Manager;
import com.test.util.C3P0Util;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import java.sql.SQLException;
public class ManagerDaoImpl implements ManagerDao {
QueryRunner queryRunner = new QueryRunner(C3P0Util.getDataSource());
@Override
public Manager login(String username, String password) {
Manager manager = null;
String sql = "select * from manager where username=? and password=?";
try {
manager = queryRunner.query(sql, new BeanHandler<>(Manager.class), username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return manager;
}
}
(6)在service包中创建ManagerService.java
java
复制代码
接口:
package com.test.service;
public interface ManagerService {
boolean login(String username,String password);
}
//实现类:
package com.test.service.impl;
import com.test.dao.ManagerDao;
import com.test.dao.impl.ManagerDaoImpl;
import com.test.service.ManagerService;
public class ManagerServiceImpl implements ManagerService {
ManagerDao managerDao = new ManagerDaoImpl();
@Override
public boolean login(String username, String password) {
return managerDao.login(username, password) == null ? false : true;
}
}
(7)在servlet包中创建ManagerServlet.java
java
复制代码
package com.test.servlet;
import com.test.service.ManagerService;
import com.test.service.impl.ManagerServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ManagerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ManagerService managerService = new ManagerServiceImpl();
String username = req.getParameter("username");
String password = req.getParameter("password");
boolean res = managerService.login(username, password);
if (res) {
//登录成功,进入主页面
resp.sendRedirect("index.html");
} else {
//登录失败,回到登录页
resp.sendRedirect("login.html");
}
}
}
(8)配置Servlet
xml
复制代码
<?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_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>ManagerServlet</servlet-name>
<servlet-class>com.test.servlet.ManagerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ManagerServlet</servlet-name>
<url-pattern>/managerServlet</url-pattern>
</servlet-mapping>
</web-app>
(9)在登录页面填写相关内容
html
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="managerServlet" method="get">
账号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
(10)测试
运行登录页面:输入正确的账号密码及错误的账号密码,进行测试
3.ResultSetHandler出现ClassNotFound异常的解决方案
(1)错误
(2)解决办法