Web学习笔记 - 第013天

Servlet初始化属性

方法

注解

@WebServlet(urlPatterns="/hello", loadOnStartup=1,
        initParams={
                @WebInitParam(name="username", value="kygo"),
                @WebInitParam(name="age", value="20")
        })

web.xml配置

  
    HelloServlet
    com.kygo.servlets.HelloServlet
    
      username
      admin
    
    
      password
      123456
    
  
拿到初始化的属性
    private ServletConfig config;

    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(config.getInitParameter("username"));
        System.out.println(config.getInitParameter("password"));
    }

过滤器

例子

例子1:编码

/**
 * 处理请求和响应编码的过滤器
 * @author kygo
 *
 */
/*@WebFilter(
    urlPatterns="/*",
    initParams={@WebInitParam(name="encoding", value="utf-8")}
)*/
public class CharacterEncodingFilter implements Filter {
    private String defaultEncoding = null;
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        if (defaultEncoding != null) {
            req.setCharacterEncoding(defaultEncoding);
            resp.setCharacterEncoding(defaultEncoding);
        }
        chain.doFilter(req, resp);
    }
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        defaultEncoding = filterConfig.getInitParameter("encoding");
    }

}

web.xml配置

 
    characterEncodingFilter
    com.kygo.filters.CharacterEncodingFilter
    
        encoding
        utf-8
    
  
  
  
    characterEncodingFilter
    /*
  

例子2:处理聊天的脏话

public class MalContentFilter implements Filter {

    private static class MalContentAutoHandler extends HttpServletRequestWrapper {
        private ServletRequest request;
        
        public MalContentAutoHandler(HttpServletRequest request) {
            super(request);
            this.request = request;
        }
        
        @Override
        public String getParameter(String name) {
            String originValue = request.getParameter(name);
            if (name.equals("message")) {
                return originValue.replaceAll("fuck|shit|[日操干]", "*");
            } else {
                return originValue;
            }
        }
        
    }
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        MalContentAutoHandler a = new MalContentAutoHandler((HttpServletRequest) req);
        chain.doFilter(a, resp);
    }

}

web.xml配置

 
    malContentFilter
    com.kygo.filters.MalContentFilter
  
  
  
    malContentFilter
    *.do
  
字符串倒转
    public static String reverse(String str) {
/*      StringBuilder sb = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            char ch = str.charAt(i);
            sb.append(ch);
        }
        return sb.toString(); */
/*      return new StringBuilder(str).reverse().toString(); */      
        
        assert str != null;
        if (str.length() > 1) {
            return reverse(str.substring(1)) + str.charAt(0);
        }
        return str;
    }

自定义jsp标签

例子:显示时间
定义一个显示时间的类

package com.kygo.tags;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class ShowTimeTag extends SimpleTagSupport {
    private String format;
    
    public void setFormat(String format) {
        this.format = format;
    }
    
    @Override
    public void doTag() throws JspException, IOException {
        JspWriter writer = getJspContext().getOut();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        writer.write(LocalDateTime.now().format(formatter));
    }
}

在WEB-INF目录下创建mytags.tld文件




    0.1
    2.0
    http://www.kygo.com/core
    
    
        showTime
        com.kygo.tags.ShowTimeTag
        empty
        
            format
            true
        
    


jsp页面

<%@ page pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="k" uri="http://www.kygo.com/core" %>


    
        
        
    
    
        
    

例子2:字符串倒转方法标签
myfunctions类

package com.kygo.functions;

public class MyFunctions {
    
    private MyFunctions() {
        throw new AssertionError();
    }
    
    public static String reverse(String str) {
/*      StringBuilder sb = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            char ch = str.charAt(i);
            sb.append(ch);
        }
        return sb.toString(); */
/*      return new StringBuilder(str).reverse().toString(); */      
        
        assert str != null;
        if (str.length() > 1) {
            return reverse(str.substring(1)) + str.charAt(0);
        }
        return str;
    }
    
    public static void main(String[] args) {
        System.out.println(reverse("abcdefghigk"));
    }
}

mytags.tld




    
    
        reverse
        com.kygo.functions.MyFunctions
        
            java.lang.Sting reverse(java.lang.String)
        
    
    

你可能感兴趣的:(Web学习笔记 - 第013天)