Servlet初始化属性
方法
注解
@WebServlet(urlPatterns="/hello", loadOnStartup=1,
initParams={
@WebInitParam(name="username", value="kygo"),
@WebInitParam(name="age", value="20")
})
web.xml配置
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.kygo.servlets.HelloServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123456</param-value>
</init-param>
</servlet>
拿到初始化的属性
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配置
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>com.kygo.filters.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
例子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配置
<filter>
<filter-name>malContentFilter</filter-name>
<filter-class>com.kygo.filters.MalContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>malContentFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
字符串倒转
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文件
<?xml version="1.0" encoding="utf-8"?>
<taglib>
<tlib-version>0.1</tlib-version>
<jsp-version>2.0</jsp-version>
<uri>http://www.kygo.com/core</uri>
<tag>
<name>showTime</name>
<tag-class>com.kygo.tags.ShowTimeTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>format</name>
<required>true</required>
</attribute>
</tag>
</taglib>
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" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<k:showTime format="yyyy-MM-dd hh:mm:ss"/>
</body>
</html>
例子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
<?xml version="1.0" encoding="utf-8"?>
<taglib>
<function>
<name>reverse</name>
<function-class>com.kygo.functions.MyFunctions</function-class>
<function-signature>
java.lang.Sting reverse(java.lang.String)
</function-signature>
</function>
</taglib>