Java.Servlet.How to find out the type of HTTP method using JSP EL?

In JSP EL, you can’t directly call methods like request.getMethod() because EL is designed mainly for accessing attributes and properties, not for executing complex logic.

✅ However, you can still access the HTTP method indirectly using request scope attributes.

🔥 Practical Solution:

  1. Expose the HTTP method as a request attribute in your Servlet before forwarding to the JSP.

Example in Servlet:

request.setAttribute("httpMethod", request.getMethod());
request.getRequestDispatcher("/yourPage.jsp").forward(request, response);

Access it in the JSP using EL:

<p>HTTP Method: ${httpMethod}</p>

httpMethod will now output GET, POST, PUT, etc., depending on the client request.

🔵 Why can’t EL call request.getMethod() directly?

  • EL in standard JSP only allows property access (like user.name, order.id) or simple map lookup.
  • EL does not allow calling arbitrary methods like getMethod() for security and simplicity reasons.

If you write something like ${request.method}:

  • EL tries to find a “method” property inside the request object (it doesn’t exist).
  • Therefore it will just return null or an empty string.

📢 Summary:

StepAction
1In a servlet or JSP scriptlet, store the HTTP method in a request attribute
2In the JSP, access it via ${httpMethod} using EL

⚡ Alternative (less clean way):

If you have no servlet and want to get it inside pure JSP, you can (but it’s ugly) use a scriptlet:

<%
    request.setAttribute("httpMethod", request.getMethod());
%>

Then use ${httpMethod} in EL.

✅ But better practice is to set it from a servlet/controller and keep JSP clean!

🎯 Final Key Points:

MethodRecommended?Reason
Using Servlet to set attribute✅ BestClean, follows MVC
Using JSP scriptlet to set attribute⚠️ AcceptableBut not ideal in modern projects
Trying to call request.getMethod() directly in EL❌ Not possibleEL can’t call arbitrary methods
This entry was posted in Без рубрики. Bookmark the permalink.