实体类
JavaBean有特定的写法:
必须要有一个无参构造
属性必须私有化
必须有对应的get/set方法;
一般用来和数据库的字段做映射 ORM;
ORM :对象关系映射
表—>类
字段–>属性
行记录---->对象
例如
Person表中有这些字段
那么Person类中就必须这样写
package com.jdbc.dao;
public class Person {
private int id;
private String name;
private int age;
private String address;
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
public Person() {
}
public Person(int id, String name, int age, String address) {
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
访问数据这样访问
<%@ page import="com.jdbc.dao.Person" %><%--
Created by IntelliJ IDEA.
User: 74485
Date: 2022/5/7
Time: 15:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Person person=new Person(2,"小白",22,"山东");
%>
<%=person.getId()%>
<%=person.getName()%>
<%=person.getAge()%>
<%=person.getAddress()%>
<jsp:useBean id="person" class="com.jdbc.dao.Person" scope="page"/>
<jsp:setProperty name="person" property="id" value="1"/>
<jsp:setProperty name="person" property="name" value="小白"/>
<jsp:setProperty name="person" property="age" value="22"/>
<jsp:setProperty name="person" property="address" value="山东"/>
编号:<jsp:getProperty name="person" property="id"/>
姓名:<jsp:getProperty name="person" property="name"/>
年龄:<jsp:getProperty name="person" property="age"/>
地址:<jsp:getProperty name="person" property="address"/>
</body>
</html>
MVC三层架构
什么是 MVC : Model View Controller 模型、视图、控制器
Model
- 业务处理:业务逻辑(Service)
- 数据持久层:CRUD
View
- 展示数据
- 提供链接发起 Servlet 请求(a,form,img…)
Controller (Servlet)
-
接收用户的请求:(req:请求参数、Session 信息…)
-
交给业务层处理对应的代码
-
控制试图的跳转
登录--->接收用户的登录请求--->处理用户的请求(获取用户登录的参数,username,password)---->交给业务层处理登录业务(判断用户名密码是否正确:事务)--->Dao层查询用户名和密码是否正确-->数据库
过滤器
Filter:过滤器,用来过滤网站的数据;
处理中文乱码
登录验证
Filter 开发步骤:
导包
编写过滤器
package com.maven.filter;
import javax.servlet.*;
import java.io.IOException;
public class charaterEncodingFilter implements Filter {
//初始化:web服务器启动,就已经初始化了,随时等待过滤对象出现
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化");
}
/*
* Chain:链
* 1.过滤器中的所有代码,在过滤特定请求的时候都会执行
* 2.必须要让过滤器继续通行
* chain.diFilter(request,response);
* */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("CharacterEncodingFilter执行前");
//让我们的请求继续走,如果不写,程序到这里就被拦截停止
chain.doFilter(request,response);
System.out.println("CharacterEncodingFilter执行后");
}
//销毁:web服务器关闭的时候,过滤会销毁
@Override
public void destroy() {
System.out.println("CharacterEncodingFilter销毁");
}
}
在 web.xml 中配置Filter
<servlet>
<servlet-name>showFilter</servlet-name>
<servlet-class>com.maven.servlet.ShowFilter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showFilter</servlet-name>
<url-pattern>/servlet/show</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>showFilter</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
<filter>
<filter-name>charaterEncodingFilter</filter-name>
<filter-class>com.maven.filter.charaterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>charaterEncodingFilter</filter-name>
<!-- 只要是/servlet的任何请求,都会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
监听器
实现一个监听器;
编写一个监听器
实现监听器的接口…
//统计网站在线人数 : 统计session
public class OnlineCountListener implements HttpSessionListener {
//创建session监听: 看你的一举一动
//一旦创建Session就会触发一次这个事件!
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
//销毁session监听
//一旦销毁Session就会触发一次这个事件!
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(0);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count-1);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
/*
Session销毁:
1. 手动销毁 getSession().invalidate();
2. 自动销毁
*/
}
<!--注册监听器-->
<listener>
<listener-class>com.kuang.listener.OnlineCountListener</listener-class>
</listener>
<h1>当前有<%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")%>人在线</h1>
Filter实现权限拦截
登录页面login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form method="post" action="/servlet/login">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
错误页面error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>失败</h1>
<h1>没有权限,用户输入有误</h1>
<p><a href="login.jsp">返回登录页面</a></p>
</body>
</html>
登录接口LoginServlet
import com.zyy.utils.Constant;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @ClassName: LoginServlet
* @Description: TODO 类描述
* @Author: zyy
* @Date: 2021/12/02 15:32
* @Version: 1.0
*/
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userName = req.getParameter("username");
if ("admin".equals(userName)) {
//登录成功
req.getSession().setAttribute(Constant.USER_SESSION, req.getSession().getId());
//跳转
resp.sendRedirect("/sys/success.jsp");
} else {
//登录失败
resp.sendRedirect("/error.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注销页面LogoutServlet
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @ClassName: LogoutServlet
* @Description: TODO 类描述
* @Author: zyy
* @Date: 2021/12/02 16:28
* @Version: 1.0
*/
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object userSession = req.getSession().getAttribute(Constant.USER_SESSION);
if (userSession != null) {
req.getSession().removeAttribute(Constant.USER_SESSION);
//跳转到登录页面
resp.sendRedirect("/login.jsp");
} else {
//跳转到登录页面
resp.sendRedirect("/login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
常量类Constant
public class Constant {
public static final String USER_SESSION = "USER_SESSION";
}
过滤器LoginFilter
import com.zyy.utils.Constant;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @ClassName: LoginFilter
* @Description: TODO 类描述
* @Author: zyy
* @Date: 2021/12/02 17:27
* @Version: 1.0
*/
public class LoginFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rep = (HttpServletResponse) response;
Object userSession = req.getSession().getAttribute(Constant.USER_SESSION);
if (userSession == null) {
//跳转错误页面
rep.sendRedirect("/error.jsp");
}
chain.doFilter(request, response);
}
public void destroy() {
}
}
接口配置web.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_3_1.xsd"
version="3.1"
metadata-complete="true">
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.zyy.filters.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/sys/*</url-pattern>
</filter-mapping>
<!-- 注册监听器-->
<listener>
<listener-class>com.zyy.listeners.OnLineCountListener</listener-class>
</listener>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
</web-app>