Servlet 示例

引入jar包:

  servlet-api.jar

 

ParameterServlet.java

package com.mousewheel.springmvc;

import java.io.IOException;

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

public class ParameterServlet extends HttpServlet {

    private String name = "";
    private Integer age = 0;

    @Override
    public void init() throws ServletException {
        super.init();
        ServletContext context = getServletContext();
        name = context.getInitParameter("name");
        age = Integer.valueOf(context.getInitParameter("age"));

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletOutputStream out = resp.getOutputStream();
        resp.setContentType("text/html");
        out.println("<html><head><title>Basic Servlet</title></head>");
        out.println("<body>Name is  <b>" + name);
        out.println("</b><br>Age is  <b>" + age + "</b>");
        out.println("</body></html>");
    }
}

 

web.xml

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Servlet Demo</display-name>
    <context-param>
        <param-name>name</param-name>
        <param-value>mousewheel</param-value>
    </context-param>
    <context-param>
        <param-name>age</param-name>
        <param-value>10</param-value>
    </context-param>
    <servlet>
        <servlet-name>ParameterServlet</servlet-name>
        <servlet-class>com.mousewheel.springmvc.ParameterServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ParameterServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

 

运行结果

 

posted @ 2017-09-17 21:32  鼠标滚轮  阅读(121)  评论(0编辑  收藏  举报