编写Servlet,并设置系统初始化参数,部署运行输出显示“系统的初始化参数是:This is System’s parameter”

package net.work2;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Test2
 */
public class Test2 extends HttpServlet {
    private static final long serialVersionUID = 1L;
     String Param = null;

    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        this.Param = config.getInitParameter("ref");
    }

    /**
     * @see Servlet#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("系统的初始化参数是:"+this.Param);
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

以上是servlet的写法,下面还需要配置web.xml文件搭配使用

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
 id="WebApp_ID" version="2.5">
  <display-name>HomeWork</display-name>

<servlet>
    <description></description>
    <display-name>Test2</display-name>
    <servlet-name>Test2</servlet-name>
    <servlet-class>net.work2.Test2</servlet-class>
    <init-param>
      <param-name>ref</param-name>
      <param-value>"This is System's parameter”"</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>Test2</servlet-name>
    <url-pattern>/Test2</url-pattern>
  </servlet-mapping>

  其中要注意的是

 this.Param = config.getInitParameter("ref");这段代码中“ref”是对应xml文件中的初始化参数名<param-name>ref</param-name>,还有如果中文输出来是一串问号的话,一定要添加这一句话
response.setContentType("text/html;charset=utf-8");
结束

 

posted @ 2020-02-09 21:16  技术白菜  阅读(448)  评论(0编辑  收藏  举报