首页 > 技术文章 > jsp的appilication.getInitParameter()方法无法获取到值的问题

roobtyan 2018-03-25 08:01 原文

背景介绍

今天研究jsp的内置对象时发现,使用appilication.getInitParameter()从web.xml文件中获取值的时候,死活获取不到,折腾了将近一个小时,后来出现问题的原因却让我感到智商遭到了侮辱。。。。

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>driver</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>
    <!--数据库的url-->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/keyan</param-value>
    </context-param>
    <!--配置第二个参数:用户名-->
    <context-param>
        <param-name>usr</param-name>
        <param-value>root</param-value>
    </context-param>
    <!--配置第三个参数:密码-->
    <context-param>
        <param-name>passwd</param-name>
        <param-value>root</param-value>
    </context-param>
</web-app>

起初我以为是配置信息出现了错误,但是怎么看也不像是出了错误。

jsp文件信息

<%
    String driver = application.getInitParameter("driver");
    String url = application.getInitParameter("url");
    String usr = application.getInitParameter("usr");
    String passwd = application.getInitParameter("passwd");
    /*注册驱动*/
    //driver = "com.mysql.jdbc.Driver";
    Class.forName(driver);
    //开始链接
    Connection connection = DriverManager.getConnection(url,usr,passwd);
    //创建查询语句
    Statement statement = connection.createStatement();
    //sql语句
    String sql = "select * from e_person";
    //开始执行
    ResultSet set = statement.executeQuery(sql);
%>
<table border="1" bgcolor="blue" width="300px">
    <%
        while(set.next()){

    %>
    <tr>
        <td><%set.getString(1);%></td>
        <td><%set.getString(2);%></td>
    </tr>
    <%
        }
    %>

</table>

再看这里,也是没什么问题的。

最终解决的办法

首先,你要确定你上面两个文件都没有写错,其次,如果你用了JRebel,请重新启动tomcat,而不是使用热部署,我就是被这玩意坑的,太惨了。。。。
问题的原因应该是这样的,虽然JRebel可以在你更新了后台或者前端的文件信息时,能热部署到服务器上,但是貌似这货并没有将web.xml文件重新加载一遍,所以导致了这个问题。
当然了,如果你重启服务器还是出现这个问题,那么就是你的文件写错了。
Good luck for you!

结语

感谢您的阅读,欢迎指正博客中存在的问题,也可以跟我联系,一起进步,一起交流!

微信公众号:进击的程序狗
邮箱:roobtyan@outlook.com
个人博客:https://roobtyan.cn

推荐阅读