问题
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.
回答1:
Try using this:
<%int no = Integer.parseInt(request.getParameter("numberMax"));%>
Its working for me.
回答2:
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.
回答3:
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 &.
回答4:
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());
%>
回答5:
Best and easiest way to convert String into Integer:
String val="67";
int value=Integer.valueOf(val);
来源:https://stackoverflow.com/questions/27219898/convert-string-to-integer-jsp