HelloServlet类继承HttpServlet利用HttpServletResponse对象

HelloServlet类继承HttpServlet利用HttpServletResponse对象

HelloServlet类的doGet()方法先得到username请求参数,对其进行中文字符编码转换,然后判断username是否为空,如果为空就返回403响应状态代码,否则就通过HttpServletResponse对象的getWriter()方法得到一个PrinterWriter对象,然后通过PrintWriter对象来输出HTML文档

HelloServlet.java

package com.demo.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/* Created by 谭雪娇 on 2017/4/5.
 */
public class HelloServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException,IOException{
        //获得sername的请求参数
        String username=request.getParameter("username");
        /*字符编码转换
        * HTTP请求的默认字符编码为ISO-8859-1,如果请求中包含中文需要把它转换为GB2312中文编码。*/
        if(username!=null){
            username=new String(username.getBytes("ISO-8859-1"),"UTF-8");
            if(username==null){
                response.sendError(response.SC_FORBIDDEN);
                return;
            }
            //设置HTTP响应的正文的MIME类型及字符编码
            response.setContentType("text/html;charset=UTF-8");
            /*输出HTML文档*/
            PrintWriter out=response.getWriter();
            out.println("HelloServlet");
            out.println("");
            out.println("你好:"+username);
            out.println("");
            System.out.println("before close():"+response.isCommitted());
            out.close();
            System.out.println("before close():"+response.isCommitted());
        }
    }
}

 

web.xml

xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>/WEB-INF/applicationContext.xmlparam-value>
    context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
        <servlet>
        <servlet-name>dispatcherservlet-name>
        <servlet-class>com.demo.servlet.RequestInfoServletservlet-class>

    servlet>
    <servlet-mapping>
        <servlet-name>dispatcherservlet-name>
        <url-pattern>/infourl-pattern>
    servlet-mapping>
    <servlet>
        <servlet-name>dispatcher1servlet-name>
        <servlet-class>com.demo.servlet.HelloServletservlet-class>
    servlet>
   <servlet-mapping>
       <servlet-name>dispatcher1servlet-name>
       <url-pattern>/hellourl-pattern>
   servlet-mapping>
web-app>

 

运行结果

Tomcat所在控制台结果

 

 

浏览器结果:

 

 

转载于:https://www.cnblogs.com/sinceForever/p/8454376.html

你可能感兴趣的:(java,web.xml)