简体   繁体   中英

@WebInitParam value is null in JSP

I have a simple servlet using annotations, all I want to do is to set initial values using servlet initialization parameters.

SimpleServlet.java

@WebServlet(
        description = "A simple servlet", 
        urlPatterns = { 
                "/SimpleServlet"
        }, loadOnStartup=1, initParams = {
                @WebInitParam(name="maximum", value="1000")
        })
public class SimpleServlet extends HttpServlet {

@Override
    public void init(ServletConfig config) {
        System.out.println(config.getInitParameter("maximum"));
    }
}

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

index.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%
   out.print(config.getInitParameter("maximum"));
%>

web.xml

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

The init method prints 1000 which is correct. But the index.jsp prints null. Can you tell me what's wrong in this code?

The @WebInitParam will init a param for this servlet. So when you access to this servlet you have the param value but when you directly access to your jsp the value is null . So you should access your jsp page through your servlet by hitting the url /SimpleServlet . This will help you:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM