I try to make countdown clock, but I can not call a javascript function by <script type="text/javascript">...</script> inside <c:if>...</c:if>. Can you help me solve this problem or give some solution to make countdown in jsp file?
demo.jsp: countdonw() function not called
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Demo Page</title>
</head>
<body>
<form action="demo" method="POST">
Time: <input type="text" id="input-time" name="inputTime">
<input type="submit" value="Start">
</form>
<c:if test="${timeRemain!= null}">
<input type="hidden" id="time-remain" value="${timeRemain}">
<p>Time Remaining: <span id="display-time"></span></p> //this line work
<script type="text/javascript">
countDown(); //not call this function
</script>
</c:if>
</body>
<script type="text/javascript">
async function countDown() {
var timeRemain = document.getElementById("time-remain").value;
alert(timeRemain);
}
</script>
</html>
demo.java servlet just send timeRemain to jsp file.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
String inputTime = request.getParameter("inputTime");
request.setAttribute("timeRemain", Integer.parseInt(inputTime));
request.getRequestDispatcher("demo.jsp").forward(request, response);
}
Try This:
<script type="text/javascript"> //oustide <c:if> tag
var timeRemain = document.getElementById("time-remain").value;
if(timeRemain.length>0 && timeRemain !== "undefined")
{
countDown();
}
</script>
Note: Better option would be to AJAX over here
Refer: https://www.javatpoint.com/ajax-tutorial
Related
I can`t understand one thing when i send request to get object by name from db,
it always return me null. I surf all sites try to fix it with session and etc. Nothing to work.
Any ideas?
enter image description here
This is my Servlet class:
#WebServlet(value = "/display", name = "IndexServlet")
public class IndexServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if(!(request.getParameter("mysql")==null)) {
MySQLRepository sql = new MySQLRepository();
Headline object = sql.getByHeadline(request.getParameter("mysql"), DatabaseConnection.initDatabase());
request.setAttribute("id", object.getId());
request.setAttribute("headline", object.getHeadline());
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("out.jsp");
requestDispatcher.forward(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is index.jsp:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>MySQLSolrProject</title>
</head>
<!DOCTYPE html>
<body>
<form action="out.jsp" method="get">
<p>Headline:</p>
<label>
<input type="text" name="mysql">
</label>
<%--<br>
<p>Full text:</p>
<label>
<input type="text" name="solr">
</label>--%>
<br><br>
<input type="submit" value="Search" formmethod="get">
</form>
</body>
</html>
This is out.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Out</title>
</head>
<body>
<h2>Text is:</h2>
<table>
<tr><th>Id</th><th>Headline</th><th></th></tr>
<tr><td><%=session.getAttribute("id")%></td>
<td><%=session.getAttribute("headline")%></td>
</tr>
</table>
<p>Return to search</p>
</body>
</html>
the error was that Tomcat version 10.* didn't want to work with version 4 servlets
I downgraded Tomcat to version 9.* and it worked.
Here is a sample jsp page with a form.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="h.abc" %>
<%
abc p = new abc();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="abcd.jsp" method="POST">
<input type="hidden" name="<%=p.getName()%>+'Name'" value='y'>
<input type='text' name='<%=p.getName()%>' >
<input type='submit' value='submit'>
</form>
</body>
</html>
Here is the abc class in the 'h' package.Please pardon the naming.It's only for illustration purposes.
public class abc {
public String name="abc";
public abc()
{
}
public String getName()
{
return name;
}
}
And this is the abcd.jsp target page.Here i am trying to get the value of the input field.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="h.abc" %>
<%
abc p = new abc();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String s = p.getName();
out.println(request.getParameter(s+"Name"));
out.println(request.getParameter(s));
%>
</body>
</html>
I am unable comprehend why the input field is not returning 'y' as its value.rather it is returning null.
change the code in first jsp
<input type="hidden" name="<%=p.getName()%>Name" value='y'>
you need put your abc instance in HttpServletRequest'attributes by calling setAttribute("you_key", abcInstance) method. And then you can get abc instance in your jsp pages by calling req.getAttribute("your_key") or using el expression
It calls Servlet by click a href.
<li >privilegeManagement</li>
this code is include in the navigation.jsp which is included in the main.jsp.
then it's my servlet.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
ProviderDao pd = new ProviderDao();
List<ProviderArchives> list = pd.getArchives();
String str = "chenfeng";
req.setAttribute("list", list);
req.setAttribute("hu" , str);
getServletContext().getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
}
then it's my main.jsp.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#page import="java.util.*"%>
<%#page import="com.chenfeng.javabean.ProviderArchives"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>main</title>
</head>
<body>
<%# include file="navigation.jsp"%>
<div>
<%# include file="management.jsp"%>
</div>
<div>
<%
String k = (String)request.getAttribute("hu");
out.println(k);
%>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.provideID() }</td>
<td>${item.GID }</td>
<td>${item.Gname }</td>
<td>${item.PID }</td>
<td>${item.TEL }</td>
<td>${item.ADDR }</td>
<td>
Modify
Delete
</td>
</tr>
</c:forEach>
</div>
</body>
</html>
then when I run this on server,it shows like this
thank in advance for any help!
Actually,there is no reason for this code.But the eclipse run into problem.The real problem log output after I delete class file in build directory and build it again.
It's quite clear. You set attribute of Request Object while you're forwarding Servlet Context Object.
Instead of:
getServletContext().getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
Write:
req.getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
I am building a web page which will show the users lat/langs sent from the android app. I have managed to receive those lat/lngs and also inserted them in the DB as well using DAO and servlet classes. Now having little knowledge of the java script in a jsp. How can i pass those paramters into this jsp so that it can show them on the map?
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript">
</script>
<style>
<% int i= 0;%>
<c:forEach var="usinf" items="${LatLang}">
#map-canvas_<%=i%> {
height: 150px;
width: 250px;
margin: 0px;
padding: 0px
}
<% i= i+1;%>
</c:forEach>
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=set_to_true_or_false">
</script>
<script>
function initialize() {
<% i= 0;%>
<c:forEach var="usinf" items="${LatLang}">
var geocoder<%=i%>;
var mapsss<%=i%>;
var infowindow<%=i%> = new google.maps.InfoWindow();
var marker<%=i%>;
geocoder<%=i%> = new google.maps.Geocoder();
var latlng<%=i%> = new google.maps.LatLng(${usinf.pickuplat},${usinf.pickuplng});
geocoder<%=i%>.geocode({'latLng': latlng<%=i%>}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
mapsss<%=i%>.setZoom(11);
marker<%=i%> = new google.maps.Marker({
position: latlng<%=i%>,
map: mapsss<%=i%>
});
infowindow<%=i%>.setContent(results[1].formatted_address);
infowindow<%=i%>.open(mapsss<%=i%>, marker_<%=i%>);
}else {
alert('No results found');
}
}else {
alert('Geocoder failed due to: ' + status);
}
});
var mapOptions<%=i%> = {
zoom: 8,
center: latlng<%=i%>,
mapTypeId: 'roadmap'
}
mapsss<%=i%> = new google.maps.Map(document.getElementById('map-canvas_<%=i%>'), mapOptions<%=i%>);
<% i= i+1;%>
</c:forEach>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<title>Insert title here</title>
</head>
<body>
<body onload="initialize()">
<div id="map-canvas_" style="width:100%; height:100%"></div>
</body>
</body>
</html>
My servlet do post method.
protected void Process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Authenticate authplots = new Authenticate();
List<UserInfo> getTheLatlangs = authplots.GetAllLangs();
request.setAttribute("LatLang", getTheLatlangs);
RequestDispatcher view = request.getRequestDispatcher("Testmaps.html");
view.forward(request, response);
}
Using JSTL, I did it this way. Maybe it will help.
<script type="text/javascript">
var markers = [
<c:forEach var="row" items="${result.rows}">
['<c:out value="${row.aciklama}" />',
<c:out value="${row.KONUME}" />,
<c:out value="${row.KONUMB}" />,
<c:out value="${row.EVID}" />,
'<c:out value="${row.aptadi}" />',
'<c:out value="${row.mahalle}" />',
'<c:out value="${row.sokak}" />',
'<c:out value="${row.durumu}" />',
'<c:out value="${row.metrekare}" />',
'<c:out value="${row.fiyat}" />',
'<c:out value="${row.odasayisi}" />'],
</c:forEach> ];
</script>
You can look in github.
JSP Google MAPS
I'm trying to make a list of members of type Party, and linking their memberID to an update page which automatically gets the memberID of the one which was clicked.
I've already written code in the servlet to display a view of all of the members, with each of their IDs linked to a page called UpdateParty.jsp however what I want is for the ID clicked to be passed on with the request so that it can be used in the UpdateParty.jsp as a parameter so that the user does not have to enter it.
I'm using postgres for my SQL if anyone wants to know.
Servlet code which produces a list of all party members:
else if (request.getParameter("listallmembers") != null) {
try {
User sessionuser = (User) session.getAttribute("User");
String u = sessionuser.getUsername();
ArrayList<Party> p = new ArrayList<Party>();
ResultSet rs = this.findAllMembers(u);
while (rs.next()) {
Party party = new Party();
party.setMemberID(rs.getString("memberID"));
party.setPartyFirstname(rs.getString("partyFirstname"));
party.setPartySurname(rs.getString("partySurname"));
party.setUsername(rs.getString("username"));
p.add(party);
}
request.setAttribute("members", p);
request.getRequestDispatcher("ViewPartyMembers.jsp").forward(request, response);
} catch (Exception e) {
out.print(e);
e.printStackTrace(out);
}
Code for ViewPartyMembers.jsp:
<%#page import="HolidayExchange.Party"%>
<%#page import="HolidayExchange.User"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<%
List<Party> l = (List<Party>) request.getAttribute("members");
if(l!=null){
out.println("<table>");
out.println("<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>");
for(int i = 0; i < l.size();i++){
out.println("<tr><td>"+ l.get(i).getMemberID() +
"</td><td><a href='UpdateParty.jsp'>"+ l.get(i).getPartyFirstname() +
"</a></td><td>"+ l.get(i).getPartySurname() +
"</td><td>" + l.get(i).getUsername() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}else{
%>
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
<%
}
%>
</body>
</html>
Here's something a little more sane for you. It uses the JSTL Expression Language and tag library.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<c:if test="${!empty members}">
<table>
<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>
<c:forEach items="${members}" var="member">
<tr><td>${member.memberID}</td>
<c:url value="link" value="UpdateParty.jsp">
<c:param name="memberId" value="${member.memberID}"/>
</c:url>
<td>${member.partyFirstname}</td>
<td>${member.partySurname}</td>
<td>${member.username}</td>
</tr>
</c:forEach>
</table>
</c:if>
<c:if test="${empty members}">
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
</c:if>
</body>
</html>
If you want the ID to be available on the UpdateParty.jsp your link should look like:
<a href='UpdateParty.jsp?id=" + l.get(i).getMemberID() + "'>"+ l.get(i).getPartyFirstname()"</a>
So the id property will be available in the JSP as a request parameter.
Anyway, I recommend you not use scriptlet in your JSP and instead point directly to a JSP point to a Controler/Action