J2EE-----关于Servlet的代码知识整理

2018-09-04  本文已影响0人  不过意局bugyj

工具intellij,墙裂推荐。作为一个jetbrains的铁忠粉,能用上的我几乎都下载了,而且学生认证很简单,次日就可用认证完成。

创建web项目

  1. 首先用intellij先新建一个project:
  1. 再src中新建一个servlet,代码:
package util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "MySer")
public class MySer extends HttpServlet {
    protected 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 GET method");
        out.println("  </BODY>");out.println("</HTML>");out.flush();out.close();
    }

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}

  1. 在../web/WEB-INFO/web.xml中对Servlet进行注册:
<?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_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>MySer</servlet-name>
        <servlet-class>util.MySer</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>MySer</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

servlet-name即Servlet的名字,servlet-class可以写 包名.类名格式,没有包就可以不写,url-pattern在浏览器中访问时作为访问Servlet的地址后缀,可写多个。

比如这里的是/hello,那么访问时就是http://localhost:8080/项目名/hello,即可访问到Servlet。

  1. index.jsp文件中对servlet提交请求即可,代码:
<body>
    <form action="/hello" method="post">
       <input type="submit" value="提交">
    </form>
  </body>
登录

通过ServletConfig获取Servlet的初始化参数

如果给Servlet配置了初始化函数的话,tomcat会在创建一个Servlet对象时将初始化参数封装进一个ServletConfig里并通过Servlet中的init()方法传进去

实例
  1. 在web.xml中Servlet中加上
<servlet>
        <servlet-name>MySer</servlet-name>
        <servlet-class>util.MySer</servlet-class>
        <init-param>
            <param-name>name</param-name>
            <param-value>hsw</param-value>
        </init-param>
        <init-param>
            <param-name>id</param-name>
            <param-value>987654321</param-value>
        </init-param>
        <init-param>
            <param-name>password</param-name>
            <param-value>123456789</param-value>
        </init-param>
    </servlet>

  1. 就可以在Servlet获取即可:
public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("UTF-8");
        PrintWriter out = response.getWriter();

        Enumeration<String> names = config.getInitParameterNames();

        while (names.hasMoreElements()) {
            String name = names.nextElement();
            out.println(name + ": " + config.getInitParameter(name));
        }

    }

ServletContext对象

web容器启动时会给每个web程序创建一个ServletContext对象,其代表的即是当前的web应用。

web在ServletConfig中维护了ServletContext对象,可以通过ServletConfig.getServletContext()获取该对象,也能用this.getServletContext()。

因为一个web应用中所有Servlet共享一个ServletContext,所以ServletCopntext可以通过ServletContext实现通信。

创建一个新的Servlet MySer2,doPost代码携程这个样子

public class MySer2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String name = (String) context.getAttribute("name");
        PrintWriter printWriter = response.getWriter();
        printWriter.println("this is Servlet2");
        printWriter.println("name" + " :" + name  + "from MySer2");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}

把MySer里未用到的doGet函数作为设定一个属性的方法!

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext context = config.getServletContext();
        context.setAttribute("name", "何少文");

        response.setContentType("UTF-8");
        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.println("this is Servlet1");
        out.println("   <form action=\"/hello2\" method=\"post\">");
        out.println("   <input type=\"submit\" value=\"提交\">");
        out.println("   </form>");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

web代码添加

<servlet>
        <servlet-name>MySer2</servlet-name>
        <servlet-class>util.MySer2</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>MySer2</servlet-name>
        <url-pattern>/hello2</url-pattern>
    </servlet-mapping>

运行下程序:

image.png

显示index.jap的内容!

点提交,将注册表接入MyServlet,然后就有了MySer中输出的xml代码。

点击此处的submit

image.png

就显示了MySer2的内容,这里从ServletConfig获取到了MySer中添加的name属性。

获取WEB应用的初始化参数:

在web.xml中web-app中添加

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" >
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/test</param-value>
    </context-param>
</web-app>

然后再Servlet中直接ServletContext.getInitParameter(String name)即可!类似于ServletConfig.getInitParameter(String name);不多赘述。

用ServletContext进行请求转发

上课时老师曾拿请假作为例子,拿假条去财务部没用,然后财务部直接吧假条转到学工处理。

这里即某个Servlet处理不了的问题,运用ServletContext请求转发将其转到其他的Servlet处理。看代码。

新建两个类,MySer3,MySer4:

public class MySer4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("这是MySer4!");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
public class MySer3 extends HttpServlet {

    ServletConfig config = null;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ServletContext context = config.getServletContext();
        RequestDispatcher dispatcher = context.getRequestDispatcher("/hello4");//这里还是和表单form中action填的是一样的!并不是类名
        dispatcher.forward(request, response);

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

运行:

点击提交:


利用ServletContext获取读取资源文件

根据资源文件的位置的不同,读取的方式也有不同。可以大致的分为两类:

  1. 在Servlet的context域中读取。2.在非Servlet中读取文件,需要使用类加载器加载!

可以看到下面的java项目的目录结构可以看出,class有两个输出位置,根据以往java的项目文件格式,可以知道production文件夹下是java的class输出位置 。而针对web程序,工程目录下的src目录被发布到服务器时会映射到/WEB-INF/classes,所以这里可以忽视peoduction的存在,只用WEB-INFO的目录就行(production没试过)

创建几个properties文件

.properties的格式差不多这样


新建MySer5:

public class MySer5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        getPro(response);
        response.getWriter().println("<hr/>");
        getPro2(response);
        response.getWriter().println("<hr/>");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private void getPro(HttpServletResponse response) throws IOException {
        //InputStream input = new FileInputStream(new File("/WEB-INF/classes/util/pro.properties"));//这样没用,一定要用下面的语句!
        InputStream input = this.getServletContext().getResourceAsStream("/WEB-INF/classes/util/pro.properties");
        Properties pro = new Properties();
        pro.load(input);
        String name = pro.getProperty("name");
        String admin = pro.getProperty("admin");
        String password = pro.getProperty("password");
        PrintWriter out = response.getWriter();
        out.println("information come from pro1: ");
        out.println("name : " + name + ", admin :" + admin + ", password :" + password);
    }

    private void getPro2(HttpServletResponse response) throws IOException {
//这样根本没用:InputStream input = new FileInputStream(new File("/out/artifacts/firstServlet_war_exploded/pro2.properties"));
        InputStream input = this.getServletContext().getResourceAsStream("/pro2.properties");
        Properties pro = new Properties();
        pro.load(input);
        String name = pro.getProperty("name");
        String admin = pro.getProperty("admin");
        String password = pro.getProperty("password");
        PrintWriter out = response.getWriter();
        out.println("information come from pro2\n");
        out.println("name : " + name + ", admin :" + admin + ", password :" + password);
    }
}
image.gif

在web中写下Servlet信息。修改表单中的url为/hello5:

运行结果:


目录结构中可以看出web目录下和映射文件夹里面的内容大致相似。

所以根据以上代码即可推导出所有在ServletContext域中的所有配置文件的路径。

然后就是非Servlet域外的文件!这需要类装载器来读取。

不多说,自己看点击打开链接

作为一个初学者,带着做笔记的想法写完了这篇博客,所以一定会漏洞百出,欢迎大家纠错!


美丽的十元
上一篇下一篇

猜你喜欢

热点阅读