目录
1. jsp
servle逻辑处理方便 html页面表现麻烦
jsp 页面表现方便 但是逻辑处理麻烦
JSP
是一种页面技术 JSP本质上是servlet类 通过JSP引擎翻译成servlet
jsp 约等于 java+html
注意:jsp不是访问静态的html文件
index.jsp修改成如下代码:
<%--
Created by IntelliJ IDEA.
User: chenw
Date: 2023/10/19
Time: 22:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" import="java.util.*,java.lang.*" pageEncoding="utf-8" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%
int i = new Random().nextInt(10);
if(i>5){
%>
<b>今天天气很好 !</b>
<%}else{
%>
<b>今天天气不好~~</b>
<%}%>
</body>
</html>
2. 过滤器
作用:
分析请求 对请求的数据进行预处理
阻止请求的进行
web资源的协作
修改请求他的内容
servlet1
response.getWriter().write("学习 filter1");
servlet2
response.getWriter().write("学习 filter2");
启服务 访问
http://localhost:8080/learningfilter/serv1
http://localhost:8080/learningfilter/serv2
都会有乱码
如何用filter解决
new filter
web.xml增加如下配置
<filter>
<filter-name>SetEncodingFilter</filter-name>
<filter-class>com.msb.filter.SetEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SetEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
所有的请求都需要经过 SetEncodingFilter处理
public class SetEncodingFilter 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 {
}
}
没有中文乱码了
用过滤启 来做一个登录拦截 条件是session里面含有user
LoginFilter
package com.msb.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* @Auther: jack.chen
* @Date: 2023/10/21 - 10 - 21 - 10:36
* @Description: ${PACKAGE_NAME}
* @version: 1.0
*/
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpSession session = ((HttpServletRequest)req).getSession();
if(session.getAttribute("user") == null){
((HttpServletResponse)resp).sendRedirect("login.jsp");
}else{
chain.doFilter(req, resp);
}
}
public void init(FilterConfig config) throws ServletException {
}
}
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_4_0.xsd"
version="4.0">
<filter>
<filter-name>SetEncodingFilter</filter-name>
<filter-class>com.msb.filter.SetEncodingFilter</filter-class>
</filter>
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.msb.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>SetEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LearningServlet1</servlet-name>
<servlet-class>com.msb.servlet.LearningServlet1</servlet-class>
</servlet>
<servlet>
<servlet-name>LearningServlet2</servlet-name>
<servlet-class>com.msb.servlet.LearningServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LearningServlet1</servlet-name>
<url-pattern>/serv1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LearningServlet2</servlet-name>
<url-pattern>/serv2.do</url-pattern>
</servlet-mapping>
</web-app>
登录 http://localhost:8080/learningfilter/serv2.do 则调到 login.jsp
再次登录
http://localhost:8080/learningfilter/serv2.do
响应正常
3. listener 监听器
监听器的作用:
监听一些共享对象属性值的变化 或者事件的发生前后 做出响应的响应 类似 触发器
这些共享对象有:
ServletContext 对象 全局唯一的tomcat启动时创建 停止时销毁
HttpSession对象
ServletRequest 对象
servlet
package com.msb.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* @Auther: jack.chen
* @Date: 2023/10/21 - 10 - 21 - 11:40
* @Description: ${PACKAGE_NAME}
* @version: 1.0
*/
public class ListenerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// request对象设置属性
request.setAttribute("learning", "listener");
//servletContext对象添加属性
ServletContext context = this.getServletContext();
context.setAttribute("servlet_key", "servlet_value");
// 设置session
HttpSession session = request.getSession();
session.setAttribute("sess_key", "sess_value");
response.getWriter().write("Learning Listener !");
}
}
listener
package com.msb.listener; /**
* @Auther: jack.chen
* @Date: 2023/10/21 - 10 - 21 - 11:45
* @Description: ${PACKAGE_NAME}
* @version: 1.0
*/
import javax.servlet.*;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class MyListener1 implements ServletRequestListener, ServletRequestAttributeListener,
ServletContextListener, ServletContextAttributeListener,
HttpSessionListener, HttpSessionAttributeListener
{
@Override
public void attributeAdded(ServletRequestAttributeEvent servletRequestAttributeEvent) {
// request对象 属性增加
// 将设置的属性打印
System.out.println(servletRequestAttributeEvent.getName());
System.out.println(servletRequestAttributeEvent.getValue());
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent servletRequestAttributeEvent) {
// request对象 属性移除
}
@Override
public void attributeReplaced(ServletRequestAttributeEvent servletRequestAttributeEvent) {
// request对象 属性重新设置
// 将设置的属性打印
System.out.println(servletRequestAttributeEvent.getName());
System.out.println(servletRequestAttributeEvent.getValue());
}
@Override
public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
// request对象 创建
}
@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
// request对象 销毁
}
@Override
public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
// servletContext 对象添加属性
}
@Override
public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
// servletContext 对象移除属性
}
@Override
public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
// servletContext 对象 替换属性
}
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
// servletContext 对象创建 tomcat启动时创建一次 全局共享
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
// servletContext 停止时销毁
}
@Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
// session 对象 添加属性
}
@Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
// session 对象 移除属性
}
@Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
// session 对象 修改属性
}
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
// session 对象被创建
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
// session 对象销毁
}
}
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_4_0.xsd"
version="4.0">
<listener>
<listener-class>com.msb.listener.MyListener1</listener-class>
</listener>
<servlet>
<servlet-name>ListenerServlet</servlet-name>
<servlet-class>com.msb.servlet.ListenerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListenerServlet</servlet-name>
<url-pattern>/serv1</url-pattern>
</servlet-mapping>
</web-app>
用listener实现在线人数的统计
不同的浏览器分别访问
page.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
当前在线人数:${applicationScope.count}
</body>
</html>
listener
package com.msb.listener; /**
* @Auther: jack.chen
* @Date: 2023/10/21 - 10 - 21 - 12:07
* @Description: ${PACKAGE_NAME}
* @version: 1.0
*/
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class CountListener implements ServletContextListener,
HttpSessionListener, HttpSessionAttributeListener {
// Public constructor is required by servlet spec
public CountListener() {
}
// -------------------------------------------------------
// ServletContextListener implementation
// -------------------------------------------------------
public void contextInitialized(ServletContextEvent sce) {
/* This method is called when the servlet context is
initialized(when the Web application is deployed).
You can initialize servlet context related data here.
*/
ServletContext servletContext = sce.getServletContext();
// 设置初始值
servletContext.setAttribute("count", 0);
}
public void contextDestroyed(ServletContextEvent sce) {
/* This method is invoked when the Servlet Context
(the Web application) is undeployed or
Application Server shuts down.
*/
}
// -------------------------------------------------------
// HttpSessionListener implementation
// -------------------------------------------------------
public void sessionCreated(HttpSessionEvent se) {
/* Session is created. */
ServletContext servletContext = se.getSession().getServletContext();
// 获取servletContext对象count属性
int count = (int)servletContext.getAttribute("count");
// +1之后设置回去
servletContext.setAttribute("count", ++count);
}
public void sessionDestroyed(HttpSessionEvent se) {
/* Session is destroyed. */
ServletContext servletContext = se.getSession().getServletContext();
// 获取servletContext对象count属性
int count = (int)servletContext.getAttribute("count");
// -1之后设置回去
servletContext.setAttribute("count", --count);
}
// -------------------------------------------------------
// HttpSessionAttributeListener implementation
// -------------------------------------------------------
public void attributeAdded(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute
is added to a session.
*/
}
public void attributeRemoved(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute
is removed from a session.
*/
}
public void attributeReplaced(HttpSessionBindingEvent sbe) {
/* This method is invoked when an attibute
is replaced in a session.
*/
}
}
标签:java,void,http,finter,javax,监听器,import,servlet,public
From: https://www.cnblogs.com/cavalier-chen/p/17778774.html