[英]Show the current date using JSP and Servlets
我正在嘗試做有關Web編程(JSP和Servlet)的作業,但看不到代碼中的錯誤。
我的index.jsp是:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Data (sem JavaBeans)</title>
</head>
<body>
<a href="Data">Atualizar data</a>
<br/>
<%
if (request.getAttribute("dia") != null)
{
int dia = (Integer) request.getAttribute("dia");
int mes = (Integer) request.getAttribute("mes");
int ano = (Integer) request.getAttribute("ano");
int hora = (Integer) request.getAttribute("hora");
int minuto = (Integer) request.getAttribute("minuto");
String sDia = String.format("%2d",Integer.toString(dia));
String sMes = String.format("%2d",Integer.toString(mes));
String sAno = String.format("%4d",Integer.toString(ano));
String sHora = String.format("%2d",Integer.toString(hora));
String sMinuto = String.format("%2d",Integer.toString(minuto));
out.print("A hora atual é: " + sDia + "/" + sMes + "/" + sAno + " - " + sHora + ":" + sMinuto);
}
%>
</body>
</html>
而我的servlet是:
package br.com.gabriel;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Data
*/
@WebServlet("/Data")
public class Data extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Data() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@SuppressWarnings("deprecation")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Date d = new Date();
int dia = d.getDate();
int mes = d.getMonth() + 1;
int ano = d.getYear() + 1900;
int hora = d.getHours();
int minuto = d.getMinutes();
request.setAttribute("dia", dia);
request.setAttribute("mes", mes);
request.setAttribute("ano", ano);
request.setAttribute("hora", hora);
request.setAttribute("minuto", minuto);
request.getRequestDispatcher("index.jsp").forward(request, response);
};
}
我得到的錯誤是:
java.util.IllegalFormatConversionException: d != java.lang.String
但是我看不出這里哪里錯了...
提前致謝! 加布里埃爾
在像
String sDia = String.format("%2d",Integer.toString(dia));
擺脫Integer.toString(..)
調用。 d
模式用於
%2d
期望一個整數值,但是您將其傳遞給String
。
簡單地做
String sDia = String.format("%2d", dia);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.