Servlet的配置

今天接触了Servlet,Servlet 是一个 Java程序,是在服务器上运行以处理客户端请求并做出响应的程序Servlet是早期最初始的一个版本,慢慢形成JSP.介绍一下Servlet的配置。

案例:web项目WebRoot/WEB-INF/web.xml下

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

  <!-- 注册servlet -->
  <servlet>
      <servlet-name>HelloServlet</servlet-name>
      <servlet-class>servlet.HelloServlet</servlet-class>
      <!-- 初始化参数:由当前servlet管理 -->
      <init-param>
          <param-name>name</param-name>
          <param-value>小明</param-value>
      </init-param>
  </servlet>

  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>query</servlet-name>
    <servlet-class>servlet.query</servlet-class>
  </servlet>
    <servlet-mapping>
    <servlet-name>query</servlet-name>
    <url-pattern>/servlet/query</url-pattern>
  </servlet-mapping>

  <!-- 映射servlet -->
  <servlet-mapping>
      <servlet-name>HelloServlet</servlet-name>
      <url-pattern>/HelloServlet</url-pattern>
  </servlet-mapping>

  <!-- 上下文参数:由web容器管理 -->
  <context-param>
      <param-name>name</param-name>
      <param-value>admin</param-value>
  </context-param>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

JAVA代码:

package servlet;

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

import javax.faces.application.Application;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.corba.se.impl.interceptors.PINoOpHandlerImpl;

public class HelloServlet extends HttpServlet {

    /**
     * servlet生命周期
     *  1\实例化servlet(web容器实现)
     *    使用功能
     *    1、初始化工作;此方法只执行一次;在第一次访问sersvlet的时候执行(执行init()方法体现)
     *    2、真正处理客户端请求(执行service()方法)
     *    输出响应信息
     *    3、关闭web容器;只执行一次;在web容器关闭的售后执行销毁servlet(执行destory()方法)
     */

    /* (non-Javadoc)
     * 重写父类初始化方法
     * @see javax.servlet.GenericServlet#init()
     */
    @Override
    public void init() throws ServletException {
        // TODO Auto-generated method stub
        System.out.println("servlet第一个执行的方法!!!");

        //得到servlet初始化
        System.out.println("初始化参数:"+this.getServletConfig().getInitParameter("name"));

        //获取上下文参数
        System.out.println("上下文参数:"+this.getServletContext().getInitParameter("name"));
    }

    /* (non-Javadoc)
     * 以GET提交方式提交的请求调用该方法
     * 默认不指定提交方式的时候执行该方法
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub

    }

    /* (non-Javadoc)
     * 以POST提交方式提交的请求调用该方法
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        /**
         * 处理客户端的请求
         */
        System.out.println("执行service方法处理请求");

        //接收参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(username.equals("admin") && password.equals("123456")){
            //相当于jsp页面的session
            HttpSession session = request.getSession();

            Application app = (Application) getServletContext();

            request.setAttribute("username", username);
            //跳转到成功页面
            request.getRequestDispatcher("/success.jsp").forward(request, response);
        }

        /**
         * 响应客户端请求
         */
        //告诉客户端怎么解释返回的内容
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print("<HTML>");
        out.print("<head><title>HelloServlet</title></head>");
        out.print("<body>HelloServlet第一个servlet诞生了!!!</body>");
        out.print("</HTML>");
        out.close();
    }

    /* (non-Javadoc)
     * servlet(销毁方法)
     * @see javax.servlet.GenericServlet#destroy()
     */
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        System.out.println("销毁servlet!!!");
    }

}
package servlet;

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

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

public class query extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public query() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out
                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the GET method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out
                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

JSP代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>登录</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
    <form action="HelloServlet" method="post">
        username:<input type="text" name="username" /><br/>
        password:<input type="password" name="password" /><br/>
        <input type="submit" />
    </form>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP ‘success.jsp‘ starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
       ${username } 登录成功<br>
  </body>
</html>
时间: 2024-10-16 04:34:17

Servlet的配置的相关文章

Servlet开发技术,创建,以及Servlet的配置,web.xml的配置

直接上图,不废话!!! 第一:首先在Eclipse的包资源管理器中,单机鼠标右键,在弹出的快捷键菜单中选择“新建”/Servlet命令,在弹出的对话框中输入新建的Servlet所在的包和类名,然后单击下一步, 我选择默认,Next 依旧默认,Next 注意事项,在创建web的工程的时候需要注意的是如下图,选择上web.xml这个按钮,因为Servlet需要配置一下web.xml这个文件,web.xml在web-inf这个文件下面 上图第二个箭头前面有个方括号,勾选上就可以自动创建好web.xml

Servlet获取配置信息(ServletConfig)和ServletContext

ServletConfig ServletConfig:当Servlet容器初始化Servlet时,Servlet容器会给Servlet的init方法传入一个ServletConfig.ServletConfig封装可以通过@WebServlet或者部署描述符传给Servlet的配置信息.这样传入的每条信息就叫做一条初始参数,要在Servlet容器传给Servlet的init方法的ServletConfig中调用getInitParameter方法.getInitParameter的方法签名如下

[Java.Web][Servlet]读取配置

private ServletConfig config; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String value = config.getInitParameter("data"); OutputStream out = response.getOutputStream(); out.w

servlet过滤器配置白名单、黑名单

1.web.xml配置 1 <filter> 2 <description>过滤是否登陆</description> 3 <filter-name>encodingFilter</filter-name> 4 <filter-class>com.stxx.manager.filter.EncodingFilter</filter-class> 5 <init-param> 6 <description&g

JavaWeb核心编程之(三)Servlet Context 配置

ServletContextServlet引擎为每个Web应用程序都创建一个对应的ServletContext对象, ServletContext对象被包含在ServletConfig对象中, 调用ServletConfig.getServletContext方法可以返回ServletContext对象的引用.由于一个WEB应用程序中的所有Servlet都共享同一个ServletCOntext对象, 所以ServletContext对象被称之为application对象(Web应用程序对象).功

关于servlet的配置

当我们使用eclipse新建一个Servlet时,我们到web.xml中配置后有时会出现服务器无法启动的情况 下面我们来看: eg: servlet: ** * Servlet implementation class LogoServlet */@WebServlet("/LogoServlet")//重点在这里public class LogoServlet extends HttpServlet { private static final long serialVersionU

web.xml中servlet的配置

<servlet>元素是配置Servlet所用的元素. <servlet-mapping>元素在Servlet和URL样式之间定义一个映射,即servlet类提供一个url,在地址栏输入对应的映射路径就可以访问你的servlet. 下面给出一段配置代码: <servlet> <servlet-name>ServletName</servlet-name> <servlet-class>xxxpackage.xxxServlet<

JSP/Servlet环境配置

下载安装JDK并配置环境变量 这里我下载安装的是jdk-7u51-windows-i586,如果你没有请到Oracle官网下载: [我的电脑]-[高级系统设置]-[环境变量]-系统变量中的Path添加Java bin目录: 命令窗口测试配置环境变量正确与否. 下载服务器 我学习使用的是Web容器apache-tomcat-7.0.50-windows-x86,如果没有请到Apache下载. 配置服务器 确定SDK安装目录,即JAVA_HOME环境变量,这一步应该在第一步中已经配置: 指定端口,默

Servlet初始配置 监听器和过滤器

ServletContext:application范围内的参数 此所设定的参 来源: http://note.sdo.com/my 数,在JSP网页中可以使用下列方法来取得: ${initParam.param0}, <%=application.getInitParameter("param0") %><br/> 若在Servlet可以使用下列方法来获得: String param_name=getServletContext().getInitParame