Convert String to Integer JSP

86.5k views Asked by At

I am a beginner using JSP. I want to display a list of incrementing integers using a maximum range of the users choice.

Entering: 6 should display the following:

  • number 1
  • number 2
  • number 3
  • number 4
  • number 5
  • number 6

input.jsp

<body>
<input type="number" name="numberMax" required>
<input type="submit" value="submit">
</body>

jspResult.jsp

<body>
<% 
int numberMax = request.getParameter("numberMax");  // Cannot convert from String to int
%>
for (int i = 1; i <= numberMax; i++) 
{ %>
<ul>
<li><%= i %></li>
</ul>
<% } %>
</body>

How can I convert the input to an integer in order for the jsp scriptlet to print.

5

There are 5 answers

1
Megha Sharma On BEST ANSWER

Try using this:

<%int no = Integer.parseInt(request.getParameter("numberMax"));%>

Its working for me.

0
Jerome Anthony On

Try using `Integer.parseInt()' to convert string to integer.

<% 
 String paramNumMax = request.getParameter("numberMax");  // Cannot convert from String to int
 int numberMax = Integer.parseInt(paramNumMax.trim());
%>
0
Joop Eggen On

You can use JSTL tags. The conversion from String to int then is done in the Expression Language.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
    <head>
       <meta charset="UTF-8">
    </head>
<body>
    <p>There are ${param.numberMax} numbers.</p>
    <ul>
    <c:forEach begin="1" end="${param.numberMax}" varStatus="no">
        <li><c:out value="number ${no.count}"/></li>
    </c:forEach>
    </ul>
</body>

The request parameters one gets as param.numberMax inside ${...}. The varStatus object contains properties like first or last time in loop and such. Here the <c:out > tag is not needed, it can escape XML entities like turning a & into correct &amp;.

0
hvsp On

In case someone else lands here and is not allowed to use scripting elements for some reason. You could use

<fmt:parseNumber var="intValue" value="${integerAsString}" integerOnly="true"/>

to set a new JSP variable.

0
Abdulrehman On

Best and easiest way to convert String into Integer:

String val="67";
int value=Integer.valueOf(val);