@WebServlet 用法 @WebFilter 用法以及解决中文乱码

简介: @WebServlet 用法 @WebFilter 用法以及解决中文乱码

servlet路径错误

今天idea写了个servlet

默认生成的

@WebServlet(name=“getParameter”)

然后在访问的时候无法访问,


servlet路径配置方法

@WebServlet方法,推荐


修改为

@WebServlet("/getParameter")

可以通过

http://localhost:8080/servlet2_war_exploded/getParameter?x1=lmkservlet

进行访问

源代码

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/getParameter")
public class getParameter extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String x1=request.getParameter("x1");
            PrintWriter out1=response.getWriter();
            out1.print("<html><body><p> 请求参数x1的值为"+x1+"</p></body></html>");
    }
}

web-xml 配置路径方法,老方法

或者也可以再 web-iml 中进行配置

<?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">
    <servlet>
        <servlet-name>Hello</servlet-name>
        <servlet-class>Hello</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Hello</servlet-name>
        <url-pattern>/Hello</url-pattern>
    </servlet-mapping>
</web-app>

解决servlet 中文乱码的方法

方法一直接设定 字符集这样的好处就是简单,

但是当几十个servlet都采用这种方式,每次设定都很麻烦

当servlet很多是,我推荐 方法二 全局过滤器 Filter

    //设置请求字符集
    request.setCharacterEncoding("utf-8");
    //设置响应头字符集,告诉浏览器是什么字符集
        response.setContentType("text/html;charset=utf-8");
        //设置响应字符集
        response.setCharacterEncoding("utf-8");


完整代码

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/getParameter")
public class getParameter extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String x1=request.getParameter("x1");
            PrintWriter out1=response.getWriter();
            out1.print("<html><body><p> 请求参数x1的值为"+x1+"</p></body></html>");
    }
}


方法二 设定全局过滤器

Filter的执行顺序与在web.xml配置文件中的配置顺序一致,一般把Filter配置在所有的Servlet之前。

过于过滤器的几点常识

过滤器只会被初始化一次

所以过滤器常驻内存

所以只有很必要的操作才需要使用过滤器20200310181428334.png

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
//指定路径匹配 以及过滤器名称,  /* 就是全局所有请求都匹配
@WebFilter(filterName = "setCharacterCoding" ,urlPatterns = "/*")
public class setCharacterCoding implements Filter {
    public void destroy() {
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        String codingmode="utf-8";
        req.setCharacterEncoding(codingmode);
        resp.setContentType("text/html;charset="+codingmode);
        resp.setCharacterEncoding(codingmode);
        chain.doFilter(req, resp);
    }
    public void init(FilterConfig config) throws ServletException {
    }
}

启用全局过滤器之后

配置初始化参数

@WebServlet

参数设置用法

@WebServlet(urlPatterns = “/getinit”, initParams = {@WebInitParam(name = “姓名”, value = “lmk”),

@WebInitParam(name = “classname”, value = “init初始化参数”, description = “基本信息”)}

)

参数获取


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String innner = this.getInitParameter(“姓名”) + “
”;
package two;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/getinit", initParams = {@WebInitParam(name = "姓名", value = "lmk"),
        @WebInitParam(name = "classname", value = "init初始化参数", description = "基本信息")}
)
public class getInitPara extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String innner = this.getInitParameter("姓名") + "<br>";
        innner += this.getInitParameter("classname");
        PrintWriter out1 = response.getWriter();
        out1.print(innner);
        out1.close();
    }
}

context 上下文初始化参数

首先在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">
    <!-- 配置上下文参数,所有的Servlet中都可以使用 -->
    <context-param>
        <param-name>sx1</param-name>
        <param-value>上下文介绍</param-value>
    </context-param>
    </web-app>

上下文参数调用

String innner = this.getServletContext().getInitParameter(“sx1”) ;


servlet 初始化参数以及上下文参数的区别

局部初始化参数只能当前servlet获取

上下文初始化参数可以,在整个web 应用中获取

会话跟踪

由于http的无连接性

必须应用程序自己唯一表示用户

cookie使用

cookie 最多保存20个值

大小不超4kb


位于 javax.servlet.http.Cookie

Cookie(String name, String value)


setCookie servlet

创建了 Cookie 之后,

在 respose 中 setCookies

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String id1=UUID.randomUUID().toString();
        Cookie c1=new Cookie("id",id1);
        response.addCookie(c1);

getCookie servlet

在 request 中getCookies

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Cookie[] cs=request.getCookies();
            for(Cookie c1:cs){
                if (c1.getName().equals("id")){
                    PrintWriter out1= response.getWriter();
                    out1.print("获取的cookie id 值是"+c1.getValue());
                    out1.close();
                }
            }
    }


cookie 的生命周期

当cookie不设置生命周期时,cookie默认是 会话cookie

当设置了cookie的生命周期,以后,cookie,就成了持久cookie,



相关文章
mailto用法详解
mailto用法详解
529 0
mailto用法详解
|
存储 SQL Oracle
DatabaseMetaData的用法(转)
DatabaseMetaData的用法(转)
595 0
|
Web App开发 JavaScript 前端开发
FastClick用法
FastClick用法 为什么要使用FastClick 移动设备上的浏览器默认会在用户点击屏幕大约延迟300毫秒后才会触发点击事件,这是为了检查用户是否在做双击。
2666 0
|
Java
Systrace的用法小结
通过SysTrace可以帮助我们分析性能问题,包含方法的耗时时长、CPU的使用情况、ANR、布局情况等;相比性能工具TraceView,主要用来分析每个方法的执行时间,对于冷启动而言,想抓trace只能通过代码的方式,这样会导致整个应用比较卡顿,测试出的方法时间,不是真正的执行时间,只能看下时间长短的相对占比。
3499 0
|
Web App开发
$0和$#的用法
$0的作用就是取脚本的名称,也包括路径 $#的作用是命令行脚本传参个数
823 0