SPRINGMVC filter get and print parameters

Source: Internet
Author: User

---restore content starts---

Today the leader arranges to give me a live, in the Web. XML add an interceptor, the log prints out the parameters of the request and response, and after an afternoon, now make a note again.

Before we go into the code, we need to sort out the logic of the entire HTTP request.

A complete HTTP request process begins when the connection to the TCP three handshake is successful, and the client begins sending an HTTP request to the server in the specified format, after the server receives the request, resolves the HTTP request, processes the business logic, and returns an HTTP response to the client. The HTTP response content also has a standard format. No matter what the client or the server, as long as the HTTP protocol standards to achieve, then it must be universal. The HTTP request format consists of four main parts: the request line, the request header, the blank line, the message body , each part contains one row

  

In the process of seeing spring MVC receiving parameters and responding: Sending a request, delegating a request to the processor, the processor calling the Clerk object, returning the view model, returning the view to the controller, the controller in the call view, returning to the controller, returning to the foreground

  

Now we're on the code: first we define the personal filter class

  

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.util.Enumeration;
Import Java.util.HashMap;
Import Java.util.Map;

Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import Javax.servlet.ServletContext;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;

public class Urlfilter implements Filter {

static Logger Logger = Loggerfactory.getlogger (Urlfilter.class);

ServletContext context;

public void Destroy () {
}

public void DoFilter (ServletRequest request, servletresponse response, Filterchain filter) throws IOException, servletexception {
HttpServletRequest r = (httpservletrequest) request;
String path = r.getquerystring ();
if (path = = null) {
map<string, string> map = new hashmap<string, string> ();
Enumeration headernames = ((httpservletrequest) request). Getheadernames ();
while (Headernames.hasmoreelements ()) {//loops through the parameters in the header and puts the traversed parameters into the map
String key = (string) headernames.nextelement ();
String value = ((httpservletrequest) request). GetHeader (key);
Map.put (key, value);
}
System.out.println (Map.tostring ());
Path = Map.tostring ();
}
String URL = R.getrequesturi ();
Requestwrapper requestwrapper = null;
String Repalceurl = Url.replaceall ("/", "" ");
if (null! = Repalceurl) {
Repalceurl = Repalceurl.trim ();
} else {
Return
}
Logger.info ("\ n-----------------URL:" + URL + "& queryString:" + path);

Responsewrapper responsewrapper = new Responsewrapper ((httpservletresponse) response);

if (Request instanceof HttpServletRequest) {
Requestwrapper = new Requestwrapper ((httpservletrequest) request);
try {
Map map = Request.getparametermap ();
Logger.info ("Map:" + map);
BufferedReader BufferedReader = Requestwrapper.getreader ();
String Line;
StringBuilder sb = new StringBuilder ();
while (line = Bufferedreader.readline ()) = null) {
Sb.append (line);
}
Logger.info ("Request.getreader:" + sb.tostring ());
} catch (Exception e) {
Todo:handle exception
Logger.error ("P2ps doFilter:", e);
}

}
if (null = = Requestwrapper) {
Filter.dofilter (request, response);
} else {
Filter.dofilter (Requestwrapper, Responsewrapper);
}

string result = new String (Responsewrapper.getresponsedata ());

Response.setcontentlength (-1);//resolution may be in the process of running the page only part of the output
Response.setcharacterencoding ("UTF-8");
PrintWriter out = Response.getwriter ();
Out.write (result);
Out.flush ();
Out.close ();
Logger.info ("\ n return Data:" + result);
Logger.info ("\ n----------------End URL:" + URL + "Httpstatus:" + ((httpservletresponse) response). GetStatus () + "");
}

public void init (Filterconfig filterconfig) throws Servletexception {
context = Filterconfig.getservletcontext ();
}

}

Then define a processing class to receive the request

ImportCom.demo.utils.StreamUtil;ImportJava.io.BufferedReader;ImportJava.io.ByteArrayInputStream;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJavax.servlet.ReadListener;ImportJavax.servlet.ServletInputStream;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletRequestWrapper;/*** Copy the value in BufferedReader in Request * * @date September 1, 2016 morning 10:53:06*/ Public classRequestwrapperextendsHttpservletrequestwrapper {Private Final byte[] body; /*** This must be added, copy the value in the BufferedReader in Request * *@paramRequest *@throwsIOException*/     PublicRequestwrapper (HttpServletRequest request)throwsIOException {Super(Request); //BODY = streamutil.readbytes (Request.getreader (), "UTF-8");BODY =Streamutil.getbytebystream (Request.getinputstream ()); } @Override PublicBufferedReader Getreader ()throwsIOException {return NewBufferedReader (NewInputStreamReader (getInputStream ())); } @Override PublicServletInputStream getInputStream ()throwsIOException {FinalBytearrayinputstream Bais =NewBytearrayinputstream (body); return NewServletInputStream () { Public Booleanisfinished () {return false; }             Public BooleanIsReady () {return false; }             Public voidSetreadlistener (Readlistener readlistener) {} @Override Public intRead ()throwsIOException {returnBais.read ();    }        }; }}
ImportJava.io.ByteArrayOutputStream;ImportJava.io.CharArrayWriter;Importjava.io.IOException;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;Importjava.io.UnsupportedEncodingException;ImportJavax.servlet.ServletOutputStream;ImportJavax.servlet.WriteListener;ImportJavax.servlet.http.HttpServletResponse;ImportJavax.servlet.http.HttpServletResponseWrapper; Public classResponsewrapperextendsHttpservletresponsewrapper {PrivateBytearrayoutputstream buffer =NULL;//output to byte array    PrivateServletoutputstream out =NULL; PrivatePrintWriter writer =NULL;  PublicResponsewrapper (HttpServletResponse resp)throwsIOException {Super(RESP); Buffer=NewBytearrayoutputstream ();//a stream that truly stores dataout =Newwapperedoutputstream (buffer); Writer=NewPrintWriter (NewOutputStreamWriter (Buffer, This. getcharacterencoding ())); }    /**overloaded Parent class Get OutputStream method*/@Override PublicServletoutputstream Getoutputstream ()throwsIOException {returnOut ; }    /**overloaded Parent method to get writer*/@Override PublicPrintWriter getwriter ()throwsunsupportedencodingexception {returnwriter; }    /**overloaded Parent class get Flushbuffer method*/@Override Public voidFlushbuffer ()throwsIOException {if(Out! =NULL) {Out.flush (); }        if(Writer! =NULL) {Writer.flush (); }} @Override Public voidReset () {buffer.reset (); }    /**force output of out and writer into buffer of wapperedresponse, otherwise the data will not be taken .*/     Public byte[] Getresponsedata ()throwsIOException {flushbuffer (); returnBuffer.tobytearray (); }    /**inner class, wrapping the Servletoutputstream*/    Private classWapperedoutputstreamextendsServletoutputstream {PrivateBytearrayoutputstream BOS =NULL;  PublicWapperedoutputstream (Bytearrayoutputstream Stream)throwsIOException {BOS=stream; } @Override Public voidWriteintbthrowsIOException {bos.write (b); } @Override Public voidWritebyte[] b)throwsIOException {bos.write (b,0, b.length); }         Public BooleanIsReady () {return false; }         Public voidSetwritelistener (Writelistener writelistener) {}}}

Add the custom filter class you just wrote in Web. xml

    <Filter>        <Filter-name>Urlfilter</Filter-name>        <Filter-class>Com.demo.demo2.UrlFilter</Filter-class><!--Note that this path is replaced by the path to your own project -    </Filter>    <filter-mapping>        <Filter-name>Urlfilter</Filter-name>        <Url-pattern>/*</Url-pattern>    </filter-mapping>

It is OK to write a Contrller test call.

Write bad please haihan, the wrong place please leave a message, I promptly corrected

Here is my reference to the article path: http://www.voidcn.com/blog/wuhenzhangxing/article/p-6299832.html

http://blog.jobbole.com/106632/

              

---restore content ends---

SPRINGMVC filter get and print parameters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.