HttpServletRequest HttpServletResponse common operations

一,HttpServletResponse 

   . Response.getWriter () write ( "<h1> response </ h1>"); character stream so as to write data

   . Response.getOutputStream () write ( "response"): in the data write mode byte stream

   response.setCharacterEncoding ( "utf-8"): setting response data utf-8, character stream

   response.setHeader ( "Content-Type", "text / html; charset = utf-8"): Settings page coding

   response.setContentType ( "text / html; charset = UTF-8"); "): distortion data in response to solve

Two, HttpServletRequest to obtain client information

   getRequestURL (): Gets the full path of the resource request

   getRequestURI (): access to resources partial path

   getQueryString (): method returns the parameter portion of the request line.

   getRemoteAddr (): Gets the requesting client's IP

   getRemotePort (): Gets the port requesting client

   getRemoteHost (): Gets the name of the requesting client

   getLocalAddr (): Returns the IP web server

   getLocalName (): Returns the web server host name

   getMethod (): returns the client request mode

Three, request to obtain header information

   request.getHeader (name); // Get the value of a single value corresponding to the request header name

   request.getHeaders ( "Accept-Encoding"); // Get a plurality of the same name request a set value corresponding to the value of the head, the flow returns enumerated type

   request.getHeaderNames (); // get all the value of the request header name, also returns data type of a data enumeration, the enumeration traversal out sequentially the elements, name value corresponding to the value acquired according Http request to obtain All information header

To do:

/ **
* Get header
* /
String headValue = request.getHeader ( "the Accept-Encoding"); // get a single value corresponding to the request header name value
System.out.println (headValue);


Enumeration e = request.getHeaders ( "Accept- Encoding"); // Get a plurality of the same name request a set value corresponding to the value of the head, the flow returns enumerated type
/ **
* traverses the data out
* /
the while (e.hasMoreElements ()) {
// iterate each element stored in the enumeration
String value = (String) e.nextElement ();
System.out.println (value); // outputs the value
}

/ **
* Get all request headers information
* /
the Enumeration request.getHeaderNames ER = (); // get all values name request header
the while (er.hasMoreElements ()) {
String name = (String) er.nextElement ();
String value = request.getHeader (name );
System.out.println (name + "=" + value);
}

Fourth, get the client request parameters

getParameter (name): Gets the parameter values specified name. This is one of the most commonly used method.
getParameterValues (String name): Gets all the values in the array specifies the name of the parameter. It applies to a case where a plurality of parameter values corresponding to the name. As pages in the form check box, the value of multiple-selection list submitted.
getParameterNames (): returns the names of all parameters Enumeration object request message contains. By traversing the Enumeration object, you can get all of the information request parameter name
getParameterMap (): returns an Object Request Map saved all parameter name and value of the message. Key Map object is a string type of parameter name, value is the value of this parameter is an array of type Object corresponding.

Fifth, the various paths to obtain

request.getRealPath () This method is no longer recommended for use, instead of the method is:

request.getSession().getServletContext().getRealPath()

.. Request.getSession () getServletContext () getRealPath ( "/"); get the full path of the Web project

Request .getContextPath (), returns the root directory for the project, on the Tomcat under ROOT is empty, the configuration is not local if the Application context, also returns empty, on the contrary arranged to return the value of the configuration

ps: Java way to read the configuration file

Mode 1: The ServletContext Read, Read The realpath configuration file, and then read out by the file stream.

Because it is a ServletContext read the file path, the configuration file can be placed in the WEB-INF of classes directory, you can be at the application level and WEB-INF directory.
Specific performance file storage location in the eclipse project is: can be placed src below, can also be placed below webroot web-info and so on.
Because the path is read by the stream reading a file, it can be read xml configuration file includes any and properties. Disadvantages: servlet can not be applied on the outside to read configuration information.

String realPath = getServletContext().getRealPath(path);

InputStreamReader reader =new InputStreamReader(new FileInputStream(realPath),"utf-8");

Option 2: ResourceBundle class to read configuration information

Advantages are: the resource may be loaded in a manner fully qualified class name, a direct read out, and the resource files can be read in a non-Web applications.
Disadvantages: only load classes below the class resource file, and can only be read .properties file.

/**
     * 获取指定.properties配置文件中所以的数据
     * @param propertyName
     *        调用方式:
     *            1.配置文件放在resource源包下,不用加后缀
     *              PropertiesUtil.getAllMessage("message");
     *            2.放在包里面的
     *              PropertiesUtil.getAllMessage("com.test.message");
     * @return
     */
    public static List<String> getAllMessage(String propertyName) { // 获得资源包 ResourceBundle rb = ResourceBundle.getBundle(propertyName.trim()); // 通过资源包拿到所有的key Enumeration<String> allKey = rb.getKeys(); // 遍历key 得到 value List<String> valList = new ArrayList<String>(); while (allKey.hasMoreElements()) { String key = allKey.nextElement(); String value = (String) rb.getString(key); valList.add(value); } return valList; }

Three ways: using the read configuration information ClassLoader manner

The advantage is: You can read the configuration resource information in a non-Web applications, you can read any file resource information.
Disadvantages: only load classes below the class resource file.

 /**获取的是classes路径下的文件
     * 优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息
     * 缺点:只能加载类classes下面的资源文件。
     * 如果要加上路径的话:com/test/servlet/jdbc_connection.properties
     */
    private static void use_classLoador(){ //获取文件流 InputStream is=TestJava.class.getClassLoader().getResourceAsStream("message.properties"); //获取文件的位置 String filePath=TestJava.class.getClassLoader().getResource("message.properties").getFile(); System.out.println(filePath); }

Method four: getResouceAsStream

XmlParserHandler.class.getResourceAsStream differs in that the classloader is used relative to the current class.

Method five: PropertiesLoaderUtils Tools

PropertiesLoaderUtils Spring offer allows you to directly load the properties file-based resources address the class path.
The biggest advantage is this: real-time load profiles, effective immediately after the changes without restarting.

   private static void springUtil(){ Properties props = new Properties(); while(true){ try { props=PropertiesLoaderUtils.loadAllProperties("message.properties"); for(Object key:props.keySet()){ System.out.print(key+":"); System.out.println(props.get(key)); } } catch (IOException e) { System.out.println(e.getMessage()); } try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }

reference:

https://www.jianshu.com/p/efdd1a526939

Guess you like

Origin www.cnblogs.com/kobe24vs23/p/11318279.html