Trying to display the current date on a page in JSP but getting odd error codes. Any idea what I am doing wrong?
<% Date today = new Date(); %>
<%!
public String displayDate(Date date){
return date.toString();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome!</title>
</head>
<body>
<h1><center>Today's Date is: <%displayDate(<%=today%>);%></center></h1>
This
<%displayDate(<%=today%>);%>
should be something like
<%= displayDate(today); %>
Also, I'd recommend you migrate away from scriptlets.
Related
I am trying to dynamically generate a list of dates without duplicates in JSP to display in a selector tag.
In my servlet class:
query = " SELECT * FROM visits";
prepStatement = connection.prepareStatement(query);
results = prepStatement.executeQuery();
Set<Date> vdates = new HashSet<>();
while(results.next()){
vdates.add(results.getDate("date"));
}
Date[] dates = vdates.toArray(new Date[vdates.size()]);
out.println(vdates);
request.setAttribute("dates", dates);
RequestDispatcher dispatcher = request.getRequestDispatcher("/js/selectorJSP.jsp");
dispatcher.forward(request, response);
In my selectorJSP file:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Selector Page</title>
<script src="js/jquery-2.1.4.min.js"></script>
<script>
</script>
</head>
<body>
<h1>Hello World!</h1>
<select>
<option value="AllRecords">${dates[0]}</option>
</select>
<input type="button" onclick="" value="Download">
</body>
</html>
The result is that it just shows an empty field, I am trying to show one to make sure it works and make a loop to show all available dates in selector but not available.
This is my current JSP code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<jsp:useBean id="user" class= "uts.wsd.User" scope="session" ></jsp:useBean>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String password = request.getParameter("password");
String gender = request.getParameter("gender");
String color = request.getParameter("favcol");
user.setName(name);
user.setEmail(email);
user.setPassword(password);
user.setGender(gender);
user.setFavouriteColour(color);
%>
<body style="background: <%= color %>;">
<% if (request.getParameter("tos") == null ) {%>
<p>
Sorry, you must agree to the Terms of Service.</p>
<p>Click <a href="register.jsp" > here </a> to go back.
</p>
<%} else { %>
<jsp:forward page="index.jsp" />
<% } %>
</html>
Here I use jsp:forward page="index.jsp" to redirect to index.jsp page. Then, if I want to use response.sendRedirect("index.jsp")? How can I proceed?
I tried this:
<% if (request.getParameter("tos") == null ) {%>
<p>
Sorry, you must agree to the Terms of Service.</p>
<p>Click <a href="register.jsp" > here </a> to go back.
</p>
<%} else { %>
<response.sendRedirect("index.jsp")>
<% } %>
</html>
But it failed. Please help! Thank you!!
response.sendRedirect() is Java code not a tag, so you should not close the scriptlet tags before typing it, and it is not to be preceded by < and closed with >...its just Java code:
<%
}
else
{
response.sendRedirect("index.jsp");
return; //this is to redirect immediately so it doesn't
//run any code below this point before redirecting
}
%>
I have a JSP that includes other JSPs using code like this:
<jsp:include page="include.jsp" />
I simply want to be able catch the exception and show the end user an error message if include.jsp is missing. How can I detect or catch the missing resource condition?
I think JSP has implicits objetcs, one of them is Exception.
Example of tutorialspoint:
<%# page errorPage="ShowError.jsp" %>
<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
// Throw an exception to invoke the error page
int x = 1;
if (x == 1) {
throw new FileNotFoundException("Error, one file is missing!!!");
}
%>
</body>
And only you have handle the exception in the error page:
<%# page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>
In your original JSP
<%# page errorPage="errorPage.jsp" %>
<html>
<head>
<title>JSP exception handling</title>
</head>
<body>
<jsp:include page="include.jsp" />
</body>
</html>
Then, in your errorPage.jsp
<%# page isErrorPage="true" %>
<html>
<head>
<title>Display the Exception Message</title>
</head>
<body>
<h2>errorPage.jsp</h2>
<i>An exception has occurred. Please fix the errors. Below is the error message:</i>
<b><%= exception %></b>
</body>
</html>
Credits: Examples extracted from this tutorial: http://beginnersbook.com/2013/11/jsp-exception-handling/
You should use java.io.File to check whether the file is missing.
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%#page import="java.io.*"%>
<%#page import="java.io.File.*"%>
<%
String filename = "kpisrc/getNowTime2.jsp";
File f = new File(filename);
if(f.exists()){
%>
<jsp:include page="<%=filename%>" ></jsp:include>
<%
}else{
out.print(filename + " not found.");
}
%>
Or another way to check file exists
if(null == application.getResource(filename))
by using try/catch?
<%
try {
%>
<jsp:include page="<%=filename%>" ></jsp:include>
<%
} catch(Exception e) {
%>
the file, <%=filename%>, is missing.
<%
}
%>
I am trying to get data from mysql and set the all data in xml format but I am unable to do this task. My code is:
abc.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>Insert title here</title>
</head>
<body>
<%
try
{
Connection connection=DBCreation.getConnection();
Stirng query="select latitude,longitude,time from jam_info";
Statement stmt=connection.createStatement();
ResultSet rs=stmt.executeQuery(query);
%></body>
</html>
<%# page contentType="text/xml" %>
<markers>
<marker>
<latitude></latitude>
<longitude></longitude>
<time>100</time>
</marker>
</markers>
I think this is wrong. Please guide me.
You can do something like this getXXX method will depend upon the type of the column holding the value.
<%# page language="java" contentType="text/xml; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
Connection connection=DBCreation.getConnection();
Stirng query="select latitude,longitude,time from jam_info";
Statement stmt=connection.createStatement();
ResultSet rs=stmt.executeQuery(query);
response.setContentType("text/xml");
out.println("<markers>");
while(rs.next()) {
out.println("<marker>");
out.println("<latitude>" + rs.getXXX("latitude") + "</latitude>");
out.println("<longitude>" + rs.getXXX("longitude") + "</longitude>");
out.println("<time>" + rs.getXXX("time") + "</time>");
out.println("</marker>");
}
out.println("</markers>");
%>
Hope this helps.
I am using the sendRedirect() method. But it doesn't. Please have a look at the following code:-
<%#page import="utility.ConnectionClass,java.sql.* "%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>processadmin</title>
</head>
<body>
<%
Connection con=null;
ConnectionClass obj=new ConnectionClass();
con=obj.createConnection(con);
String user=request.getParameter("user");
String pass=request.getParameter("pass");
String sql="select * from admin where username='"+user+"'";
Statement stat=con.createStatement();
ResultSet rs=stat.executeQuery(sql);
rs.next();
if((rs.getString(1)==user)&&(rs.getString(2)==pass))
response.sendRedirect("processadmin.jsp");
else
out.println("Not working");
%>
</body>
</html>
And when I run this I get the output :- Not Working
Compare String using equals() method . == compares String references , not actual contents of the String.
if(user.equals(rs.getString(1)) && pass.equals(rs.getString(2)))
Note:- Please don't use scriptlets in JSP . It is a bad practice. Read this.