Java web learning day 17 - Servlet

Day17

Example: Statistics of the number of visits

Create a variable of type int and save it in the ServletContext domain, so that all servlets can access it

Thought:

Initially there is no attribute in ServletCOntext to save the amount of visits

On the first access, create a variable, set the value to 1, and save it in the ServletContext

When accessed later, fetched from it, the value is incremented by 1.

//Steps: Get it first, and make a judgment based on the obtained value. If it is empty, it is the first access, and it will be created directly. If it is not empty, add 1 and then store it.

ServletContext context = this.getServletContext();

       Integer count = (Integer)context.getAttribute("count");

       if(count==null){

           context.setAttribute("count", 1);

       }

       else {

           count+=1;

           context.setAttribute("count", count);

       }

        PrintWriter pw = response .getWriter ();

        pw.print(count);

    }

Get resources on the classpath: For a javaweb project, the classpath is /WEN-INF/CLASS

and /WEB-INF/lib every jar package!

// get ClassLoader

       ClassLoader loader = this.getClass().getClassLoader();

       // call the method

        InputStream  input = loader.getResourceAsStream("index.jap");

        // Read the input stream content and convert it to a string

        String s  = IOUtils.toString(input);

        System.out.println(s);

Response

Type is HttpServletResponse

 

setError(int sc)--à send error status code, such as 404 500

setError(int sc,String info) send error status code and add error message

setStatus(int sc)-à send the correct status code

 

response header

The response header is a key-value pair that can have multiple values ​​of one name

setHeader(String name, String value) is used for single-value response headers,

For example: response .setHeader( "sss" , "SSS" );
addHeader(Stringname , String value), multi-valued response header (less used)

setIntHeader(Stringname , String value)

Response headers of type int for a single value

setDataHerder(Stringname , long value)

Response headers of type milliseconds for a single value

 

Response headers are automatically refreshed

PrintWriter writer = response.getWriter();

       writer.print("huangying");

       response.setHeader("Refresh","5;URL=/java10_1/Cservlet");

refresh time, jump address

keywords

                              

 

Disable browser caching

Three sentences:

response.setHeader("Cache-Control", "no-cache");

response.setHeader("pargam", "no-cache");

response.setDateHeader("expires", -1);

 

response has two streams

ServletOutputStream: used to send byte data to the client

ServletOutputSteam out = response.getOutputStream();

Print Writer: used to send character data to the client! Need to set encoding

PrintWriter writer = response.getWriter();

cannot be used at the same time

 

Read an image into a byte array

String path = " image absolute path " ;

       FileInputStream in = new FileInputStream(path);

       byte[] bytes = IOUtils.toString(path);

       response.getOutputStream().write(bytes);

 

Request uri: project name + servlet path

redirect

response.sendRedirect("http://www.baidu.com");

 

request

Encapsulates all client request data

Get common information:

Get client IP

 String request.getRemoteAddr();

Get request method:

   Request.getMethod(); The return value is get or post deflation to call the do method

Get request headers:

String getHeader(String name); for single-value headers

Int getIntHeader(String name); applies to request headers of type int

Long getDateHeader(String name); applies to request headers of single-value millisecond type

Enumeration<String>getHeader(String name), suitable for multi-value request headers

// get client IP

       String ip = request.getRemoteAddr();

       System.out.println(ip);

       // get request method

        String mothod = request.getMethod();

        System.out.println(mothod);

        // Get client segment information

        String user = request.getHeader("User-Agent");

       System.out.println(user);

Get request URL:

String getScheme (); Get the protocol name

        String getServerName(); Get the server name

        String getServlerPort (); Get the server port number

        String getContextPath (); Get the project address

        String getServletPath (); Get the servlet address

        String getQueryString (); get parameters

        String getRequestURI (); get uri

        String getRequestURL(); Get the request URL

 

Use referer request header to prevent anti-leech

If it is a local request, it will run to Baidu normally, otherwise it will go to index.jsp

String str = request.getHeader("Referer");

       System.out.println(str);

       if(!str.contains("localhost")||str==null){

           response.sendRedirect("index.jsp");

       }

       else{

           response.sendRedirect("http://www.baidu.com");

       }

    }

request request parameters

getparameter(parameter name); returns the value of the parameter

String[] name =request.getparamentValue(parameter name); if a parameter corresponds to multiple values, such as a check box

Enumeration names =request.getParamentNames(); returns all parameter names, which is an array

Map<String,String[]> map =request.getParamentMap();, get all request parameters, in the encapsulated map

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324651544&siteId=291194637