特点: 必须在客户端安装特定软件
优点: 图形效果显示较好(如: 3D游戏)
缺点: 服务器的软件和功能进行升级, 客户端也必须升级
常见的C/S程序: QQ, 微信等
客 ---请求---> web服务器
<---响应---
户
---请求---> 数据库服务器
端 <---响应---
特点: 无需安装客户端, 任何浏览器都可直接访问
优点: 设涉及到功能的升级, 只需要升级服务器端
缺点: 图形显示效果不如C/S架构
需要通过HTTP协议访问
Browser ---请求---> Web 数据
浏览器 <---响应--- 服务器 <---> 库
开源: OpenSource (1. 开放源代码 2. 免费)
收费
bin
该目录下存放的是二进制可执行文件
conf
这是一个非常重要的目录, 这个目录下有两个最为重要的文件server.xml和web.xml
lib
logs
temp
webapps
work
运行时生成的文件, 最终运行的文件都在这里
Tomcat默认端口号为8080, 可以通过conf/server.xml文件修改
注意: 修改端口号需要重新启动Tomcat才能生效
在webapps中建立文件夹(项目应用), 比如: myweb
创建WEB-INF文件夹, 用于存放项目的核心内容
把网页hello.html复制到myweb文件夹中, 与WEB-INF在同级目录
Client(Browser)
http://localhost:8080/myweb/hello.html
|requests(请求) |
| |
| |
| |response(响应)
Tomcat
webapps(存放所有项目)
MyWeb(项目)
WEB-INF(核心内容)
classes(.class文件)
lib(网站需要的jar包)
hello.html
Servlet: Server Applet的简称, 是服务器端的程序 (代码, 功能实现), 可交互式的处理客户端发送到服务器的请求, 并完成操作响应
动态网页技术
JavaWeb程序开发的基础, JavaEE规范 (一套接口) 的一个组成部分
用户若想用发一个动态web资源(即开发一个Java程序向浏览器输出数据),需要完成以下2个步骤:
按照一种约定俗成的称呼习惯,通常我们把实现servlet接口或继承实现servlet接口的类的java程序,称之为Servlet
实现javax.servlet.Servlet
重写5个主要方法
在核心的service() 方法中编写输出语句, 打印访问结果
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
public class MyServlet implements Servlet {
public void init(ServletConfig servletConfig) throws ServletException {
}
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
System.out.println("My First Servlet");
}
public void destroy() {
}
public ServletConfig getServletConfig() {
return null;
}
public String getServletInfo() {
return null;
}
}
编写WEB-INF下项目配置文件web.xml
Servlet-class: 如果有包名的话要写完整
注意: url-pattern配置的内容就是浏览器地址栏输入的URL中项目名称后资源的内容
<?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">
<!--1. 添加servlet节点-->
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.dz.servlet.MyServlet</servlet-class>
</servlet>
<!--2. 添加servlet-mapping节点-->
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
在Tomcat的webapps目录下, 新建WebProject文件夹
问题: 每当我们编写了新的Servlet或者重新编译, 都需要手工将新的.class部署到Tomcat中, 较为麻烦, 如何实现自动部署?
方法一:
方法二[推荐]:
支持客户端(浏览器) / 服务器模式
简单快递: 客户端只向服务器发送请求方法和路径, 服务器即可响应数据, 因而通信速度很快. 请求方法常用的有GET, POST等
灵活: HTTP允许传输任意类型的数据, 传输的数据类型由Content-Type标识
无连接: 无连接指的是每次TCP连接只处理一个或多个请求, 服务器处理完客户的请求后, 即断开连接, 采用这种方式可以节省传输时间
无状态: HTTP协议是无状态协议
在Servlet API中最重要的是Servlet接口, 所有Servlet都会直接或间接的与该接口发生联系, 或是直接实现该接口, 或间接继承自实现了该接口的类, 该接口包括以下5个方法:
GenericServlet使编写Servlet变得更容易, 它提供声明周期方法 init 和 destroy 的简单实现, 要编写一般的Servlet, 只需重写抽象Service 方法即可
public class GenServlet extends GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("继承了GenericServlet抽象类!");
}
}
public class MyServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("My First Web Project!");
System.out.println(new Date());
System.out.println("成功导出war包!");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
public class HttpsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("这是get请求的内容!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("这是post请求的内容!");
}
}
HTTP Status 404 资源找不到
Servlet地址配置重复
Servlet地址配置错误
<?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">
<!--Servlet配置-->
<servlet>
<!--名称-->
<servlet-name>MyServlet</servlet-name>
<!--Servlet的全程类名-->
<servlet-class>com.dz.servlet.MyServlet</servlet-class>
<!--启动的优先级, 数字越小越先起作用-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--映射配置-->
<servlet-mapping>
<!--名称-->
<servlet-name>MyServlet</servlet-name>
<!--资源的匹配规则:精确匹配-->
<url-pattern>/ms</url-pattern>
</servlet-mapping>
</web-app>
url-pattern定义匹配规则, 取值说明:
精确匹配 /具体的名称 只有url路径是具体的名称时才会触发Servlet
后缀匹配 *.xxx 只要是以xxx结尾的就匹配触发Servlet
通配符匹配 /* 匹配所有请求, 包含服务器的所有资源
通配符匹配 / 匹配所有请求, 包含服务器的所有资源, 不包括.jsp
load-on-startup
1. 元素标记容器是否应该在web应用程序启动时就加载这个servlet
2. 它的值必须是一个整数, 表示servlet被加载的先后顺序
3. 如果该元素的值为负数或者没有设置, 则容器会认为Servlet被请求时再加载
4. 如果值为整数或者0时, 表示容器在应用启动时就加载并初始化这个servlet, 值越小, servlet的优先级越高, 就越先被加载, 值相同时, 容器就会自己选择顺序来加载
@WebServlet(value = {"/bs", "/bss"},loadOnStartup = 0)
public class BasicServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("这是GET!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("这是POST!");
}
}
get请求
post请求
String getParameter(String name)
void setCharacterEncoding(String charset)
HTML页面
Servlet代码
@WebServlet(value = {"/rs"})
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 获取用户请求发送的数据
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("提交的数据: " + username + "\t" + password );
}
}
在Tomcat7及以下版本, 客户端以UTF-8的编码传输数据到服务器, 而服务器端的request对象使用的是ISO8859-1 这个字符编码来接收数据, 服务器和客户端沟通的编码不一致因此才会产生中文乱码的
解决get中文乱码的代码
@WebServlet(value = {"/rs"})
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 获取用户请求发送的数据
String username = req.getParameter("username");
username = new String(username.getBytes("ISO8859-1"),"UTF-8");
String password = req.getParameter("password");
System.out.println("提交的数据: " + username + "\t" + password );
}
}
由于客户端是以UTF-8字符编码将表单数据传输到服务器的, 因此服务器也需要设置以UTF-8字符编码进行接收
@WebServlet(value = {"/rs"})
public class RegisterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置POST请求的统一编码格式为UTF-8
req.setCharacterEncoding("UTF-8");
//1. 获取用户请求发送的数据
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("提交的数据: " + username + "\t" + password );
}
}
setHeader(name, value)
setContentType(String)
setCharacterEncoding(String)
getWriter()
//获取请求参数的代码此处省略
//获取输出流
PrintWriter printWriter = resp.getWriter();
printWriter.println("register success!!");
设置服务器端响应的编码格式
设置客户端响应内容的头内容的文件类型及编码格式
//设置POST响应的统一编码格式为UTF-8
resp.setCharacterEncoding("UTF-8");
resp.setHeader("Content-type", "text/html;charset=UTF-8");
不推荐
同时设置服务端的编码格式和客户端响应的文件类型及响应时的编码格式
resp.setContentType("text/html;charset=UTF-8");
推荐
步骤:
MySQL数据库中
Servlet项目中
将所需的jar包导入到web---WEB-INF---lib中
src下创建database.properties
src下创建com.dz.servletProject目录,在此目录下分别有以下操作
以下是部分代码
CREATE TABLE admin(
username VARCHAR(20) PRIMARY KEY NOT NULL,
PASSWORD VARCHAR(20) NOT NULL,
phone VARCHAR(11) NOT NULL,
address VARCHAR(20) NOT NULL
)CHARSET=utf8;
SELECT * FROM admin;
INSERT INTO admin(username,PASSWORD,phone,address)
VALUE('张三','123456','12345678901','地球');
INSERT INTO admin(username,PASSWORD,phone,address)
VALUE('李四','123456','12345678902','地球');
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/companydb?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
initialSize=10
maxActive=20
minIdle=5
maxWait=3000
public class DbUtils {
private static DruidDataSource ds;
private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();
static {
Properties properties = new Properties();
InputStream inputStream = DbUtils.class.getResourceAsStream("/database.properties");
try {
properties.load(inputStream);
ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection conn = THREAD_LOCAL.get();
try {
if (conn == null) {
conn = ds.getConnection();
THREAD_LOCAL.set(conn);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return conn;
}
public static void begin() {
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void commit() {
Connection conn = null;
try {
conn = getConnection();
conn.commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
closeAll(conn,null,null);
}
}
public static void rollback() {
Connection conn = null;
try {
conn = getConnection();
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
closeAll(conn,null,null);
}
}
public static void closeAll(Connection conn, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (conn != null) {
conn.close();
THREAD_LOCAL.remove();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public class Admin {
private String username;
private String password;
private String phone;
private String address;
public Admin() {
}
public Admin(String username, String password, String phone, String address) {
this.username = username;
this.password = password;
this.phone = phone;
this.address = address;
}
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;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Admin{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
'}';
}
}
public interface AdminDao {
int insert(Admin admin);
int delete(String username);
int update(Admin admin);
Admin select(String username);
List<Admin> selectAll();
}
public class AdminDaoImpl implements AdminDao {
private QueryRunner queryRunner = new QueryRunner();
@Override
public int insert(Admin admin) {
return 0;
}
@Override
public int delete(String username) {
return 0;
}
@Override
public int update(Admin admin) {
return 0;
}
@Override
public Admin select(String username) {
try {
Admin admin = queryRunner.query(DbUtils.getConnection(), "select * from admin where username=?", new BeanHandler<Admin>(Admin.class), username);
return admin;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
@Override
public List<Admin> selectAll() {
try {
List<Admin> adminList = queryRunner.query(DbUtils.getConnection(), "select * from admin", new BeanListHandler<Admin>(Admin.class));
return adminList;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
public interface AdminService {
Admin login(String username, String password);
List<Admin> showALlAdmin();
}
public class AdminServiceImpl implements AdminService {
private AdminDao adminDao = new AdminDaoImpl();
@Override
public Admin login(String username, String password) {
Admin result = null;
try {
DbUtils.begin();
Admin admin = adminDao.select(username);
if (admin != null) {
if (admin.getPassword().equals(password)) {
result = admin;
}
}
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return result;
}
@Override
public List<Admin> showALlAdmin() {
List<Admin> adminList = null;
try {
DbUtils.begin();
adminList = adminDao.selectAll();
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return adminList;
}
}
@WebServlet(value = "/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置统一编码格式
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//1. 收参
String username = req.getParameter("username");
String password = req.getParameter("password");
//2. 调用业务逻辑
AdminService adminService = new AdminServiceImpl();
Admin admin = adminService.login(username, password);
//3. 处理结果
PrintWriter printWriter = resp.getWriter();
if (admin != null) {
//响应给客户端一个结果页面, 显示登陆成功
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>结果页面</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h1>登陆成功!</h1>");
printWriter.println("</body>");
printWriter.println("</html>");
}else {
//响应给客户端一个结果页面, 显示登陆失败
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>结果页面</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h1>登陆失败!</h1>");
printWriter.println("</body>");
printWriter.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
@WebServlet(value = "/showAll")
public class ShowAllAdminServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
AdminService adminService = new AdminServiceImpl();
List<Admin> adminList = adminService.showALlAdmin();
PrintWriter printWriter = resp.getWriter();
if (adminList != null) {
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>展示所有用户</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<table border='1'>");
printWriter.println("<tr>");
printWriter.println(" <th>username</th>");
printWriter.println(" <th>password</th>");
printWriter.println(" <th>phone</th>");
printWriter.println(" <th>address</th>");
printWriter.println("</tr>");
for (Admin admin : adminList) {
printWriter.println("<tr>");
printWriter.println(" <td>"+admin.getUsername()+"</td>");
printWriter.println(" <td>"+admin.getPassword()+"</td>");
printWriter.println(" <td>"+admin.getPhone()+"</td>");
printWriter.println(" <td>"+admin.getAddress()+"</td>");
printWriter.println("</tr>");
}
printWriter.println("</table>");
printWriter.println("</body>");
printWriter.println("</html>");
}else {
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>展示所有用户</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h3>当前没有用户!</h3>");
printWriter.println("</body>");
printWriter.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆页面</title>
</head>
<body>
<form action="/WebProject_war_exploded/login" method="post">
<p>
<label for="1">用户名:</label>
<input type="text" name="username" id="1">
</p>
<p>
<label for="2">密码: </label>
<input type="password" name="password" id="2">
</p>
<p>
<input type="submit" value="登陆">
</p>
</form>
</body>
</html>
在之前案例中, 调用业务逻辑和显示结果页面都在同一个Servlet中, 就会产生设计问题
应该将业务逻辑和显示结果分离开
XxxController extends HttpServlet{
//调用业务逻辑
}
XXXJSP extends HttpServlet{
//显示页面结果
}
调用业务逻辑的Server中, 编写以下代码
使用forward跳转时, 是在服务器内部跳转, 地址栏不发生变化, 属于同一次请求
forward表示一次请求, 是在服务器内部跳转, 可以共享同一次request作用域中的数据
request作用域: 拥有存储数据的空间, 作用范围是一次请求有效(一次请求可以经过多次转发)
存数据: request.setAttribute(key, value);
取数据: request.getAttribute(key);
调用业务逻辑
@WebServlet(value = "/showAllController")
public class ShowAllAdminController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//只负责调用业务逻辑功能
AdminService adminService = new AdminServiceImpl();
List<Admin> adminList = adminService.showALlAdmin();
//request作用域存储数据
req.setAttribute("adminList", adminList);
//通过转发, 跳转到显示结果的servlet
req.getRequestDispatcher("/showAllJSP").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
显示
@WebServlet(value = "/showAllJSP")
public class ShowAllAdminJSP extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
List<Admin> adminList = (List)req.getAttribute("adminList");
PrintWriter printWriter = resp.getWriter();
if (adminList != null) {
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>展示所有用户</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<table border='1'>");
printWriter.println("<tr>");
printWriter.println(" <th>username</th>");
printWriter.println(" <th>password</th>");
printWriter.println(" <th>phone</th>");
printWriter.println(" <th>address</th>");
printWriter.println("</tr>");
for (Admin admin : adminList) {
printWriter.println("<tr>");
printWriter.println(" <td>"+admin.getUsername()+"</td>");
printWriter.println(" <td>"+admin.getPassword()+"</td>");
printWriter.println(" <td>"+admin.getPhone()+"</td>");
printWriter.println(" <td>"+admin.getAddress()+"</td>");
printWriter.println("</tr>");
}
printWriter.println("</table>");
printWriter.println("</body>");
printWriter.println("</html>");
}else {
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>展示所有用户</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h3>当前没有用户!</h3>");
printWriter.println("</body>");
printWriter.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
在调用业务逻辑的Servlet中, 编写以下代码
URI统一资源标识符(Uniform Resource Identifier), 用来表示服务器中定位一个资源, 资源在web项目中的路径(/project/source)
使用redirect跳转时, 是在客户端跳转, 地址栏发生变化, 属于多次请求
sendRedirect跳转时, 地址栏改变, 代表客户端重新发送的请求. 属于两次请求
当用户第一次访问Servlet时, 由容器(Tomcat服务器)调用Servlet的构造器创建具体的Servlet对象. 也可以在容器启动之后立刻创建实例. 使用如下代码可以设置Servlet是否在服务器启动时就创建
< load-on-startup>1< /load-on-startup>
注意: 只执行一次
当客户端有一个请求时, 容器就会将请求ServletRequest与响应ServletResponse对象转给Servlet, 以参数的形式传给service 方法
当Servlet容器(Tomcat服务器)停止或重新启动都会引起销毁Servlet对象并调用destroy方法
synchronized
实现SingleThreadModel接口
尽可能使用局部变量
@WebServlet(value = "/ss")
public class SafeServlet extends HttpsServlet {
//private String message = "";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//假设1. 接收参数
//假设2. 调用业务逻辑, 得到登陆结果
//尽量使用局部变量可以避免线程安全问题
String message = "登陆成功!";//登陆失败!
resp.setContentType("text/html;charset=UTF-8");
PrintWriter printWriter = resp.getWriter();
printWriter.println(message);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
Cookie是在浏览器访问Web服务器的某个资源时, 由Web服务器在HTTP响应消息头中附带传送给浏览器的一小段数据
一旦Web浏览器保存了某个Cookie, 那么它在以后每次访问该该Web服务器时, 都应在HTTP请求头中将这个Cookie回传给Web服务器
一个Cookie主要由标识该信息的名称(name) 和 值(value)组成
Client
//1. 访问登陆Servlet
http://localhost:8080/web/ls
//2. 接收ls响应的cookie, 存储
//3. 访问显示Servlet, 携带Cookie
Server
Client首次请求Server
LoginServlet extends HttpServlet{
//创建Cookie对象(键值对)
//通过response将Cookie响应给Client
}
Client再次请求Server
ShowServlet extends HttpServlet{
//从请求中查找Cookie, 存在就获取
}
@WebServlet(value = "/cs")
public class CookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 服务端创建Cookie对象
Cookie cookie = new Cookie("username","dz");
//1.1. 设置Cookie的路径
cookie.setPath("/WebProject_war_exploded/get");
//1.2 设置Cookie的有效期
cookie.setMaxAge(60*60);//内存存储, 取值有3种, >0有效期: 单位秒, =0: 浏览器关闭, <0内存存储: 默认-1
//2. 将Cookie响应给客户端
resp.addCookie(cookie);
//注意: 有效路径: 当前访问资源的上一级目录, 不带主机名
}
}
@WebServlet(value = "/get")
public class GetServlet extends HttpsServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 通过request获取所有的cookie
Cookie[] cookies = req.getCookies();
//2. 通过循环遍历Cookie
if (cookies != null) {
for (Cookie cookie : cookies) {
//检索出自己的Cookie
if (cookie.getName().equals("username")) {
//记录Cookie的值
String value = cookie.getValue();
System.out.println(cookie.getName() + ":" + value);
break;
}
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
只需要保证Cookie的名称和路径一致即可修改
Cookie cookie2 = new Cookie("username","dz2");cookie2.setPath("/WebProject_war_exploded/get");
cookie2.setMaxAge(60*60*24*7);
resp.addCookie(cookie2);</code></pre></li>
注意: 如果改变Cookie的name和有效路径会新建Cookie, 而改变Cookie的值,和有效期会覆盖原有Cookie
Cookie默认不支持中文, 只能包含ASCII字符, 所以Cookie需要对Unicode字符进行编码, 否则会出现乱码
//使用中文的Cookie name和value都使用UTF-8编码
Cookie cookie = new Cookie(URLEncoder.encode("姓名","UTF-8"),URLEncoder.encode("张三","UTF-8"));
cookie.setPath("/WebProject_war_exploded/get");
cookie.setMaxAge(60*60);
//发送到客户端
resp.addCookie(cookie);
//1. 通过request获取所有的cookie
Cookie[] cookies = req.getCookies();
//2. 通过循环遍历Cookie
if (cookies != null) {
for (Cookie cookie : cookies) {
String cookieName = URLDecoder.decode(cookie.getName(),"UTF-8");
String cookieValue = URLDecoder.decode(cookie.getValue(),"UTF-8");
System.out.println(cookieName + ":" + cookieValue);
}
}
Session作用域: 拥有存储数据的空间, 作用范围是一次会话有效
session是服务器自动创建的, 通过request对象获取
//获取Session
HTTPSession session = request.getSession();
System.out.println("Id: " + session.getId());//唯一标记
setAttribute(属性名,Object) 保存数据到session中
session.setAttribute("key", value);//以键值对形式存储在Session中
getAttribute(属性名); 获取session中的数据
session.getAttribute("key");//通过String类型的key访问Object类型的value
removeAttribute(属性名); 从session中删除数据
session.removeAttribute("key");//通过键移除session作用域中的值
@WebServlet(name = "SessionServlet", value = "/sss")
public class SessionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 通过request对象获取Session对象
HttpSession session = request.getSession();
//2. 使用session保存数据
session.setAttribute("username","dz");
//request是一次请求有效, 在重定向后属于第二次请求, 就失效了
request.setAttribute("password","1234");
response.sendRedirect("/WebProject_war_exploded/getValue");//重定向跳转到getValue下
System.out.println(session.getId());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebServlet(name = "GetValueServlet",value = "/getValue")
public class GetValueServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 通过request获取session对象
HttpSession session = request.getSession();
String s = (String)session.getAttribute("username");
String password = (String)request.getAttribute("password");
System.out.println("从session中获得了: " + s);//从session中获得了: dz
System.out.println("从request中获得了: " + password);//从request中获得了: null
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
session.setMaxInactiveInterval(60*60);//设置session最大有效期为一小时
session.invalidate();//手工销毁
response.encodeRedirectURL(String url)生成重写的URL
HttpSession session = request.getSession();
//重写URL追加sessionID
String newUrl = response.encodeRedirectURL("/WebProject_war_exploded/gets");
response.sendRedirect(newUrl);
CREATE TABLE manager(
username VARCHAR(20) PRIMARY KEY,
PASSWORD VARCHAR(20) NOT NULL
)CHARSET=utf8;
ManagerDao接口
public interface ManagerDao {
Manager select(String username);
}
ManagerDaoImpl实现类
public class ManagerDaoImpl implements ManagerDao {
private QueryRunner queryRunner = new QueryRunner();
@Override
public Manager select(String username) {
try {
Manager manager = queryRunner.query(DbUtils.getConnection(), "select * from manager where username=?", new BeanHandler<Manager>(Manager.class),username);
return manager;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
ManagerService接口
public interface ManagerService {
Manager login(String username,String password);
}
ManagerServiceImpl实现类
public class ManagerServiceImpl implements ManagerService {
private ManagerDao managerDao = new ManagerDaoImpl();
@Override
public Manager login(String username, String password) {
Manager manager = null;
try {
DbUtils.begin();
Manager temp = managerDao.select(username);
if (temp != null) {
if (temp.getPassword().equals(password)) {
manager = temp;
}
}
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return manager;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>管理员登录</title>
</head>
<body>
<form action="/WebProject_war_exploded/loginMgr" method="post">
<p>
<label for="1">用户名:</label>
<input type="text" name="username" id="1">
</p>
<p>
<label for="2">密码: </label>
<input type="password" name="password" id="2">
</p>
<p>
<input type="submit" value="登陆">
</p>
</form>
</body>
</html>
servlet下的controller目录下, 负责调用业务逻辑(管理员登陆)
@WebServlet(name = "LoginMgrController",value = "/loginMgr")
public class LoginMgrController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 处理乱码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//2. 收参
String username = request.getParameter("username");
String password = request.getParameter("password");
//3. 调用业务方法
ManagerService managerService = new ManagerServiceImpl();
Manager mgr = managerService.login(username, password);
//4. 处理结果, 流程跳转
if (mgr != null) {
//登陆成功
//将管理员信息mgr存储在Session中
HttpSession session = request.getSession();
session.setAttribute("mgr",mgr);
//跳转,目标,方式(重定向)
response.sendRedirect("/WebProject_war_exploded/showAllController");
}else {
//如果管理员信息为空则跳转到管理员登陆界面
response.sendRedirect("/WebProject_war_exploded/loginMgr.html");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
servlet下的controller目录下, 负责调用业务逻辑(查所有用户信息)
@WebServlet(value = "/showAllController")
public class ShowAllAdminController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 通过HttpSession完成权限控制
HttpSession session = req.getSession();
Manager mgr = (Manager)session.getAttribute("mgr");
if (mgr != null) {
//2. 调用业务逻辑
AdminService adminService = new AdminServiceImpl();
//查用户列表
List
//session作用域存储数据(存储adminList到session中)
session.setAttribute("adminList", adminList);
//通过重定向, 跳转到显示结果的servlet
resp.sendRedirect("/WebProject_war_exploded/showAllJSP");
}else {
//如果管理员信息为空则跳转到管理员登陆界面
resp.sendRedirect("/WebProject_war_exploded/loginMgr.html");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
servlet下的jsp目录下, 负责展示最终结果
@WebServlet(value = "/showAllJSP")
public class ShowAllAdminJSP extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 通过HttpSession完成权限控制
HttpSession session = req.getSession();
//3. 从session中取出管理员信息
Manager mgr = (Manager)session.getAttribute("mgr");
//3. 从session中取出用户列表信息
List
resp.setContentType("text/html;charset=UTF-8");
PrintWriter printWriter = resp.getWriter();
if (adminList != null) {
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>展示所有用户</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h1>欢迎您: "+ mgr.getUsername() +"</h1>");
printWriter.println("<table border='1'>");
printWriter.println("<tr>");
printWriter.println(" <th>username</th>");
printWriter.println(" <th>password</th>");
printWriter.println(" <th>phone</th>");
printWriter.println(" <th>address</th>");
printWriter.println("</tr>");
for (Admin admin : adminList) {
printWriter.println("<tr>");
printWriter.println(" <td>"+admin.getUsername()+"</td>");
printWriter.println(" <td>"+admin.getPassword()+"</td>");
printWriter.println(" <td>"+admin.getPhone()+"</td>");
printWriter.println(" <td>"+admin.getAddress()+"</td>");
printWriter.println("</tr>");
}
printWriter.println("</table>");
printWriter.println("</body>");
printWriter.println("</html>");
}else {
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>展示所有用户</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h3>当前没有用户!</h3>");
printWriter.println("</body>");
printWriter.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
导入ValidateCode.jar
创建生成验证码的Servlet
@WebServlet(name = "CreateCodeController",value = "/createCode")
public class CreateCodeController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 创建验证码图片
ValidateCode code = new ValidateCode(200, 30, 4, 20);
String codes = code.getCode();
HttpSession session = request.getSession();
session.setAttribute("codes",codes);
//2. 验证码图片响应给客户端
code.write(response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>管理员登录</title>
</head>
<body>
<form action="/WebProject_war_exploded/loginMgr" method="post">
<p>
<label for="1">用户名:</label>
<input type="text" name="username" id="1">
</p>
<p>
<label for="2">密码: </label>
<input type="password" name="password" id="2">
</p>
<p>
<label for="3">验证码:</label>
<input type="text" name="inputVcode" id="3">
<img src="/WebProject_war_exploded/createCode" alt="验证码">
</p>
<p>
<input type="submit" value="登陆">
</p>
</form>
</body>
</html>
@WebServlet(name = "LoginMgrController",value = "/loginMgr")
public class LoginMgrController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 处理乱码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//2. 收参
String username = request.getParameter("username");
String password = request.getParameter("password");
String inputVcode = request.getParameter("inputVcode");
String codes = (String)request.getSession().getAttribute("codes");
if (!inputVcode.isEmpty() && inputVcode.equalsIgnoreCase(codes)) {
//3. 调用业务方法
ManagerService managerService = new ManagerServiceImpl();
Manager mgr = managerService.login(username, password);
//4. 处理结果, 流程跳转
if (mgr != null) {
//登陆成功
//将管理员信息mgr存储在Session中
HttpSession session = request.getSession();
session.setAttribute("mgr",mgr);
//跳转,目标,方式
response.sendRedirect("/WebProject_war_exploded/showAllController");
}else {
//如果管理员信息为空则跳转到管理员登陆界面
response.sendRedirect("/WebProject_war_exploded/loginMgr.html");
}
}else {
//如果验证码为空或者不正确则跳转到登陆页面
response.sendRedirect("/WebProject_war_exploded/loginMgr.html");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
获取当前项目在服务器发布的真实路径
String realpath=servletContext.getRealPath("/");
获取当前项目上下文路径(应用程序名称)
System.out.println(servletContext.getContextPath());//上下文路径(应用程序名称)
System.out.println(request.getContextPath());
ServletContext拥有作用域, 可以存储数据到全局容器中
ServletContext统计当前项目访问次数
@WebServlet(name = "ShowCounterController",value = "/showCounterController")
public class ShowCounterController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取servletContext对象
ServletContext servletContext = request.getServletContext();
//2. 获取计数器
Integer counter = (Integer) servletContext.getAttribute("counter");
if (counter == null) {
counter = 1;
}else {
counter += 1;
}
servletContext.setAttribute("counter",counter);
System.out.println("Servlet被访问次数: " + counter);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
过滤器
@WebFilter(value = "/t")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("---My Filter---");
//让请求继续
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("---end---");
}
@Override
public void destroy() {
}
}
Servlet
@WebServlet(name = "TargetServlet",value = "/t")
public class TargetServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("---Target---");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
<!--过滤器的xml配置-->
<filter>
<!--名称-->
<filter-name>Xml</filter-name>
<!--过滤器类全程-->
<filter-class>com.dz.filter.XmlFilter</filter-class>
</filter>
<!--映射路径配置-->
<filter-mapping>
<!--名称-->
<filter-name>Xml</filter-name>
<!--过滤的url匹配规则和Servlet类似-->
<url-pattern>/test</url-pattern>
</filter-mapping>
过滤器的过滤路径通常有三种形式
精确过滤匹配 如: /index.jsp, /myservlet1
后缀过滤匹配 如: *.jsp, *.html, *.jpg
通配符过滤匹配/*, 表示拦截所有. 注意过滤器不能使用/匹配. /aaa/bbb/*允许
在一个Web应用中, 可以开发编写多个Filter, 这些Filter组合起来称之为一个Filter链. 优先级:
@WebFilter(filterName = "EncodingFilter",value = "/*")
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//设置统一编码格式
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
showAllAdminController
@WebServlet(value = "/showAllController")
public class ShowAllAdminController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 调用业务逻辑
AdminService adminService = new AdminServiceImpl();
//查用户列表
List
//session作用域存储数据(存储adminList到session中)
req.getSession().setAttribute("adminList", adminList);
//通过重定向, 跳转到显示结果的servlet
resp.sendRedirect("/WebProject_war_exploded/showAllJSP");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
CheckFilter
@WebFilter(filterName = "CheckFilter",value = "/showAllController")
public class CheckFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//权限验证, 验证管理员是否登陆
//先向下转型 拆箱
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
HttpSession session = request.getSession();
Manager mgr = (Manager)session.getAttribute("mgr");
if (mgr != null) {//证明登陆过,验证通过
chain.doFilter(request, response);
}else {//验证未通过,重新登陆
response.sendRedirect(request.getContextPath() + "/loginMgr.html");
}
}
public void init(FilterConfig config) throws ServletException {
}
}
该案例是EmpProject员工管理系统, 使用了两张表
CREATE DATABASE emp;
USE emp;
CREATE TABLE emp(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
salary DOUBLE NOT NULL,
age INT NOT NULL
)CHARSET=utf8;
CREATE TABLE empManager(
username VARCHAR(20) NOT NULL,
PASSWORD VARCHAR(20) NOT NULL
)CHARSET=utf8;
创建Web项目, 导入相关jar包
项目下创建包目录结构
web下创建empLogin.html
#<!-- 连接设置 -->
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/emp?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
#<!-- 初始化连接 -->
initialSize=10
#<!-- 最大连接数量 -->
maxActive=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 60000毫秒/1000等于60秒 -->
maxWait=3000
public class DbUtils {
//声明连接池对象
private static DruidDataSource ds;
//一个线程共享同一个ThreadLocal, 在整个流程中任一环节可以存值或取值
private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();
static {
Properties properties = new Properties();
try {
InputStream inputStream = DbUtils.class.getResourceAsStream("/database.properties");
properties.load(inputStream);
ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn = THREAD_LOCAL.get();
try {
if (conn == null) {
conn = ds.getConnection();
THREAD_LOCAL.set(conn);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return conn;
}
public static void begin() {
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void commit() {
Connection conn = null;
try {
conn = getConnection();
conn.commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
closeAll(conn,null,null);
}
}
public static void rollback() {
Connection conn = null;
try {
conn = getConnection();
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
closeAll(conn,null,null);
}
}
public static void closeAll(Connection conn, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (conn != null) {
conn.close();
THREAD_LOCAL.remove();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public interface EmpManagerDao {
EmpManager select(String username);
}
public interface EmpDao {
int insert(Emp emp);
int delete(int id);
int update(Emp emp);
Emp select(int id);
List<Emp> selectAll();
}
public class EmpManagerDaoImpl implements EmpManagerDao {
private QueryRunner queryRunner = new QueryRunner();
@Override
public EmpManager select(String username) {
try {
EmpManager empManager = queryRunner.query(DbUtils.getConnection(),"select * from empManager where username=?", new BeanHandler<EmpManager>(EmpManager.class), username);
return empManager;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
public class EmpDaoImpl implements EmpDao {
private QueryRunner queryRunner = new QueryRunner();
@Override
public int insert(Emp emp) {
try {
int result = queryRunner.update(DbUtils.getConnection(), "insert into emp(name,salary,age) values(?,?,?)", emp.getName(), emp.getSalary(), emp.getAge());
return result;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return 0;
}
@Override
public int delete(int id) {
try {
int result = queryRunner.update(DbUtils.getConnection(),"delete from emp where id = ?",id);
return result;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return 0;
}
@Override
public int update(Emp emp) {
try {
int result = queryRunner.update(DbUtils.getConnection(), "update emp set name=?,salary=?,age=? where id=?", emp.getName(), emp.getSalary(), emp.getAge(), emp.getId());
return result;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return 0;
}
@Override
public Emp select(int id) {
try {
Emp emp = queryRunner.query(DbUtils.getConnection(), "select * from emp where id=?", new BeanHandler<Emp>(Emp.class), id);
return emp;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
@Override
public List<Emp> selectAll() {
try {
List<Emp> empList = queryRunner.query(DbUtils.getConnection(), "select * from emp", new BeanListHandler<Emp>(Emp.class));
return empList;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
public interface EmpManagerService {
EmpManager login(String username,String password);
}
public interface EmpService {
int addEmp(Emp emp);
int removeEmp(int id);
int modify(Emp emp);
Emp showEmp(int id);
List<Emp> showAllEmp();
}
public class EmpManagerServiceImpl implements EmpManagerService {
private EmpManagerDao empManagerDao = new EmpManagerDaoImpl();
@Override
public EmpManager login(String username, String password) {
EmpManager empManager = null;
try {
DbUtils.begin();
EmpManager temp = empManagerDao.select(username);
if (temp != null) {
if (temp.getPassword().equals(password)) {
empManager = temp;
}
}
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return empManager;
}
}
public class EmpServiceImpl implements EmpService {
private EmpDao empDao = new EmpDaoImpl();
@Override
public int addEmp(Emp emp) {
int result = 0;
try {
DbUtils.begin();
result = empDao.insert(emp);
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return result;
}
@Override
public int removeEmp(int id) {
int result = 0;
try {
DbUtils.begin();
result = empDao.delete(id);
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return result;
}
@Override
public int modify(Emp emp) {
int result = 0;
try {
DbUtils.begin();
result = empDao.update(emp);
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return 0;
}
@Override
public Emp showEmp(int id) {
Emp emp = null;
try {
DbUtils.begin();
emp = empDao.select(id);
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return emp;
}
@Override
public List<Emp> showAllEmp() {
List<Emp> empList = new ArrayList<>();
try {
DbUtils.begin();
List<Emp> temp = empDao.selectAll();
if (temp != null) {
empList = temp;
}
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return empList;
}
}
@WebServlet(name = "CreateCodeController",value = "/createCode")
public class CreateCodeController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//创建验证码对象
ValidateCode validateCode = new ValidateCode(200, 30, 4, 20);
//获取验证码
String codes = validateCode.getCode();
//将验证码存入session
HttpSession session = request.getSession();
session.setAttribute("codes",codes);
//响应到客户端
validateCode.write(response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebServlet(name = "EmpManagerLoginController",value = "/manager/EmpManagerLoginController")
public class EmpManagerLoginController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一编码格式放在过滤器里, 此处不必再写
//1. 收参
String username = request.getParameter("username");
String password = request.getParameter("password");
String inputVcode = request.getParameter("inputVcode");
//2. 校验验证码
String codes = (String)request.getSession().getAttribute("codes");
if (!inputVcode.isEmpty() && inputVcode.equalsIgnoreCase(codes)) {
//调用业务逻辑实现登陆
EmpManagerService empManagerService = new EmpManagerServiceImpl();
EmpManager empManager = empManagerService.login(username,password);
if (empManager != null) {
//登陆成功
//存储到session作用域
HttpSession session = request.getSession();
session.setAttribute("empManager",empManager);
//跳转到查询所有的Controller
response.sendRedirect(request.getContextPath() + "/manager/safe/showAllEmpController");
}else {
response.sendRedirect( request.getContextPath() + "/empLogin.html");
}
}else {
//如果验证码错误则跳转到登陆界面
response.sendRedirect( request.getContextPath() + "/empLogin.html");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebServlet(name = "ShowAllEmpController",value = "/manager/safe/showAllEmpController")
public class ShowAllEmpController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//权限验证放在过滤器里, 此处不必再写
EmpService empService = new EmpServiceImpl();
List<Emp> empList = empService.showAllEmp();
if (empList != null) {
// HttpSession session = request.getSession();
// session.setAttribute("empList",empList);//存到session作用域中,本次会话有效
// response.sendRedirect(request.getContextPath() + "/manager/safe/showAllEmpJSP");
request.setAttribute("empList",empList);//存到request作用域中,临时存储
request.getRequestDispatcher("/manager/safe/showAllEmpJSP").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebServlet(name = "ShowEmpController",value = "/manager/safe/showEmpController")
public class ShowEmpController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer id = Integer.valueOf(request.getParameter("id"));
EmpService empService = new EmpServiceImpl();
//根据传过来的id查询数据库得到最新的数据
Emp emp = empService.showEmp(id);
request.setAttribute("emp",emp);
request.getRequestDispatcher("/manager/safe/showUpdateEmpInfoJSP").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebServlet(name = "InsertEmpController",value = "/manager/safe/insertEmpController")
public class InsertEmpController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
Double salary = Double.valueOf(request.getParameter("salary"));
Integer age = Integer.valueOf(request.getParameter("age"));
Emp emp = new Emp(name,salary,age);
EmpService empService = new EmpServiceImpl();
empService.addEmp(emp);
response.sendRedirect(request.getContextPath() + "/manager/safe/showAllEmpController");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebServlet(name = "RemoveEmpController",value = "/manager/safe/removeEmpController")
public class RemoveEmpController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//装箱: 基本数据类型转为引用类型,把拿到的字符串类型的id转为Integer类型
Integer id = Integer.valueOf(request.getParameter("id"));
EmpService empService = new EmpServiceImpl();
empService.removeEmp(id);
response.sendRedirect(request.getContextPath() + "/manager/safe/showAllEmpController");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebServlet(name = "UpdateEmpController",value = "/manager/safe/updateEmpController")
public class UpdateEmpController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 收参
Integer id = Integer.valueOf(request.getParameter("id"));
String name = request.getParameter("name");
Double salary = Double.valueOf(request.getParameter("salary"));
Integer age = Integer.valueOf(request.getParameter("age"));
Emp emp = new Emp(id, name, salary, age);
EmpService empService = new EmpServiceImpl();
empService.modify(emp);
response.sendRedirect(request.getContextPath() + "/manager/safe/showAllEmpController");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebFilter(filterName = "EncodingFilter",value = "/manager/*")//manager目录下的所有文件都生效
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
@WebFilter(filterName = "CheckFilter",value = "/manager/safe/*")//manager下的safe目录下的文件都生效,管理员登陆操作和增删改查操作都在此目录下
public class CheckFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
HttpSession session = request.getSession();
EmpManager empManager = (EmpManager) session.getAttribute("empManager");
if (empManager != null) {//证明登陆过
chain.doFilter(request, response);
}else {
response.sendRedirect(request.getContextPath() + "/empLogin.html");
}
}
public void init(FilterConfig config) throws ServletException {
}
}
@WebServlet(name = "showAllEmpJSP",value = "/manager/safe/showAllEmpJSP")
public class showAllEmpJSP extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取集合数据
// List<Emp> empList = (List<Emp>)request.getSession().getAttribute("empList");//从session中拿数据
List<Emp> empList = (List<Emp>)request.getAttribute("empList");//从request中拿数据
PrintWriter printWriter = response.getWriter();
printWriter.println("<html>");
printWriter.println(" <head>");
printWriter.println(" <meta charset='UTF-8'>");
printWriter.println(" <title>查询所有员工页面</title>");
printWriter.println(" </head>");
printWriter.println(" <body>");
printWriter.println(" <form action='/EmpProject/manager/safe/showInsertEmpJSP'>");
printWriter.println(" <p><input type='submit' value='新增'></p>");
printWriter.println(" </form>");
printWriter.println(" <table border='1'>");
printWriter.println(" <tr>");
printWriter.println(" <td>编号</td>");
printWriter.println(" <td>姓名</td>");
printWriter.println(" <td>工资</td>");
printWriter.println(" <td>年龄</td>");
printWriter.println(" <td colspan='2'>操作</td>");
printWriter.println(" </tr>");
for (Emp emp : empList) {
printWriter.println(" <tr>");
printWriter.println(" <td>"+emp.getId()+"</td>");
printWriter.println(" <td>"+emp.getName()+"</td>");
printWriter.println(" <td>"+emp.getSalary()+"</td>");
printWriter.println(" <td>"+emp.getAge()+"</td>");
printWriter.println(" <td><a href='"+request.getContextPath() + "/manager/safe/removeEmpController?id="+emp.getId()+"" +"'>删除</a></td>");
printWriter.println(" <td><a href = "+request.getContextPath() + "/manager/safe/showEmpController?id="+emp.getId()+"" +">修改</a></td>");
printWriter.println(" </tr>");
}
printWriter.println(" </table>");
printWriter.println(" </body>");
printWriter.println("</html>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebServlet(name = "ShowInsertEmpJSP",value = "/manager/safe/showInsertEmpJSP")
public class ShowInsertEmpJSP extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
printWriter.println("<html>");
printWriter.println(" <head>");
printWriter.println(" <meta charset='UTF-8'>");
printWriter.println(" <title>新增员工信息页面</title>");
printWriter.println(" </head>");
printWriter.println(" <body>");
printWriter.println(" <form action='/EmpProject/manager/safe/insertEmpController' method='post'>");
printWriter.println(" <p>姓名:<input type='text' name='name'></p>");
printWriter.println(" <p>工资:<input type='text' name='salary'></p>");
printWriter.println(" <p>年龄:<input type='text' name='age'></p>");
printWriter.println(" <p><input type='submit' value='提交'></p>");
printWriter.println(" </form>");
printWriter.println(" </body>");
printWriter.println("</html>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
@WebServlet(name = "ShowUpdateEmpInfoJSP",value = "/manager/safe/showUpdateEmpInfoJSP")
public class ShowUpdateEmpInfoJSP extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Emp emp = (Emp) request.getAttribute("emp");
PrintWriter printWriter = response.getWriter();
printWriter.println("<html>");
printWriter.println(" <head>");
printWriter.println(" <meta charset='UTF-8'>");
printWriter.println(" <title>修改员工信息页面</title>");
printWriter.println(" </head>");
printWriter.println(" <body>");
printWriter.println(" <form action='/EmpProject/manager/safe/updateEmpController' method='post'>");
printWriter.println(" <p>编号:<input type='text' name='id' value='"+emp.getId()+"' readonly></p>");
printWriter.println(" <p>姓名:<input type='text' name='name' value='"+emp.getName()+"'></p>");
printWriter.println(" <p>工资:<input type='text' name='salary' value='"+emp.getSalary()+"'></p>");
printWriter.println(" <p>年龄:<input type='text' name='age' value='"+emp.getAge()+"'></p>");
printWriter.println(" <p><input type='submit' value='修改'></p>");
printWriter.println(" </form>");
printWriter.println(" </body>");
printWriter.println("</html>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
管理员登陆界面
手机扫一扫
移动阅读更方便
你可能感兴趣的文章