Tag Archives: filter

[Solved] JAVA Web Error: startup failed due to previous errors

1. Error prompt:

WARNING [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more Filters failed to start. Full details will be found in the appropriate container log file
WARNING [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [/filter] startup failed due to previous errors

File directory structure:

After testing, we found that there is a problem with the configuration in the web.xml file, and the parameter names configured are not the same as those obtained in the filter, resulting in a startup error

2. Solution

Correct the configured parameters and republish them

[Solved] Java.lang.IllegalStateException: getReader() has already been called for this request

For the project, it is necessary to obtain the data in the request body in the interceptor for data verification, because the @ requestbody annotation is used in the self-defined controller, resulting in an error in the project. The content of the error is: Java. Lang. IllegalStateException: getreader() has already been called for this request

After consulting the data, it is found that the getReader and getinputstream in the request are obtained by stream. After reading once, they can’t be used again. The solution is:

Step 1: define a filter in which a self-defined request is passed in. The self-defined request inherits the wrapper class httpservletrequestwrapper and rewrites the getinputstream and getReader methods
the filter code is as follows:

package com.chinastock.filter;

import com.chinastock.util.CustomHttpServletRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author zhoule
 * @description: handle request
 */
public class IMTAFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if(servletRequest instanceof HttpServletRequest) {
            requestWrapper = new CustomHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        }
        if(requestWrapper == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }
}

The custom request code is as follows:

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author zhoule
 * @description: Custom request wrapper for processing messages in the request body
 */
public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private byte[] body;

    public CustomHttpServletRequestWrapper(HttpServletRequest request) throws IOException
    {
        super(request);

        BufferedReader reader = request.getReader();
        try (StringWriter writer = new StringWriter()) {
            int read;
            char[] buf = new char[1024 * 8];
            while ((read = reader.read(buf)) != -1) {
                writer.write(buf, 0, read);
            }
            this.body = writer.getBuffer().toString().getBytes();
        }
    }

    public String getBody(){
        return new String(body, StandardCharsets.UTF_8);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException
    {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream()
        {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            public int read() throws IOException
            {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException
    {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}

The second step is to write the interceptor of the project. Some codes of the interceptor are as follows:

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        CustomHttpServletRequestWrapper wrapper = (CustomHttpServletRequestWrapper) request;
        String body = wrapper.getBody();
        System.out.println(body);
        return true;
    }

Register global time filter in main.js in Vue

In main.js, define a global time filter through: Vue. Filter().
the first parameter is the name of the filter, such as: dataform,
the second parameter is the processing function of the time filter: function(), which needs to specify a formal parameter: originval, which is to process the time data
to get the originval time, first update the date and pass the originval to you, that is, to get a date object of the time according to the local time

Get four digit year through getfullyear()

Get the month through getmonth(). The month starts from 1, so make it + 1
if the month is less than two digits, fill in 0 in the front by calling. Padstart (2, ‘0’). The first parameter represents the total length of the number of digits, and the second parameter is a string. If the number of digits is less than two, which string should be filled in

Get the current date through: getdate()

Get the current hour through: gethours()

Get the current minutes through: getminutes()

Get the current seconds by: getseconds()

Let the obtained date, time, minute and second be spliced into a complete date string
return ${y} - ${m} - ${D} - ${HH}: ${mm}: ${SS}

//Format time filter
vue.filter (‘dataform ‘, function (originval) {
const DT = new date (originval)

const y = dt.getFullYear()
const m = (dt.getMonth() + 1 + ‘’).padStart(2, ‘0’)
const d = (dt.getDate() + ‘’).padStart(2, ‘0’)

const hh = (dt.getHours() + ‘’).padStart(2, ‘0’)
const mm = (dt.getMinutes() + ‘’).padStart(2, ‘0’)
const ss = (dt.getSeconds() + ‘’).padStart(2, ‘0’)

return ${y}-${m}-${d} ${hh}:${mm}:${ss}

Basic use of filter

The Filter Filter
It is one of the three main components of JavaWeb. Three components are: Servlet program, Listener, Filter Filter. Filter Filter is the JavaEE specification. It’s also the interface. The Filter Filter is used to intercept requests and Filter responses. Common application scenarios for intercepting requests are:
Permission checking diary operation transaction management requirements: Under your web project, there is an admin directory. All resources in the admin directory (HTML pages, JPG images, JSP files, and so on) must be logged in by the user before they can be accessed.

import com.wz.userManager.pojo.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "UserCenterFilter",urlPatterns = {"/pages/*"})
public class UserCenterFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp= (HttpServletResponse)servletResponse;
        HttpSession session = req.getSession();
        User username = (User) session.getAttribute("user");
        if(username==null){
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}

Wireshark filtering HTTP packets

Wireshark Filter: Protocol = “HTTP” displays filtered HTTP packets

    List item

Using the filter
built into the wireshark tool, directly click “filter “, open the “display filter” dialog box, select “HTTP”, and then click “Expression” to use the filter condition expressions identified by the tool.