carteruk
carteruk

Reputation: 139

Convert String to Integer JSP

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:

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.

Upvotes: 5

Views: 88039

Answers (5)

hvsp
hvsp

Reputation: 347

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.

Upvotes: 4

Abdulrehman
Abdulrehman

Reputation: 59

Best and easiest way to convert String into Integer:

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

Upvotes: 0

Megha Sharma
Megha Sharma

Reputation: 202

Try using this:

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

Its working for me.

Upvotes: 13

Joop Eggen
Joop Eggen

Reputation: 109547

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;.

Upvotes: 1

Jerome Anthony
Jerome Anthony

Reputation: 8021

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());
%>

Upvotes: 0

Related Questions