init-param和context-param 中擷取資料的一個問題,擷取contextparam

來源:互聯網
上載者:User

init-param和context-param 中擷取資料的一個問題,擷取contextparam

init-param  中的資料是要在制定的 servlet 下才能取的到資料的

其中擷取 init-param  的可以用 這樣的一個方式去擷取

ServletConfig config = getServletConfig();String name = config.getServletName("name")

 

或者在init方法中擷取

public void init(ServletConfig config) throws ServletException {     config.getInitParameter("name");     super.init(config);}

這兩種擷取額方式都要在web.xml  中配置對應的一個訪問路徑

貼上web.xml中的配置

<servlet>     <servlet-name>test</servlet-name>     <servlet-class>com.chen.servlet.MainServlet</servlet-class>     <init-param>         <param-name>username</param-name>         <param-value>admin</param-value>     </init-param></servlet> <servlet-mapping>        <servlet-name>test</servlet-name>        <url-pattern>/test</url-pattern> </servlet-mapping>

若要擷取到 <init-param> 標籤中的   init-param  值在訪問的時候就必須要同/test 這樣的對應路徑去訪問

程式員最不喜歡做的事情應該就是寫同樣的東西,還要寫上好多份了吧,於是就有人用註解的方式去寫發現取不到 <init-param>  標籤內的值

<context-param> 中的資料

    <context-param>        <param-name>user</param-name>        <param-value>user</param-value>    </context-param>

貼上servlet 的代碼

@WebServlet("/te")public class MainServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         ServletConfig config = getServletConfig();        config.getInitParameterNames();  //擷取 init-param 中的所有資料          String user = getInitParameter("user");  //擷取指定的一個資料
getServletContext().getInitParameter("user") //擷取 <context-param> 中的資料 }}

 

這邊會犯的一個錯誤就是用註解的方式訪問的時候回去擷取 <init-param> 標籤中的資料 ,其中的 getServletConfig() 是可以擷取到許多有項目的基本資料的。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.