response.sendRedirect in JSP - java

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
}
%>

Related

JSP Syntax error when trying to embed a a-href

I have this JSP code for my web app:
I am getting a syntax error at "Delete" in the success clause. Can anyone help me to pinpoint the problem? Thank you, appreciate it!
<%# 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>atozknowledge.com demo loginjsp</title>
</head>
<body>
<%# page import="java.sql.*"%>
<%# page import="javax.sql.*"%>
<%
String userid=request.getParameter("usr");
session.putValue("userid",userid);
String pwd=request.getParameter("pwd");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tomcat","root","root");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from users where userid='"+userid+"'");
if(rs.next())
{
if(rs.getString(2).equals(pwd))
{
out.println("welcome"+userid);
Delete
}
else
{
out.println("Invalid password try again");
}
}
else
%>
Home
</body>
</html>
Delete isn't valid Java code. If you want to get out of the Java scriptlet, use %> to do so (then <% to go back into it):
%>Delete<%
Your tag is inserted inside a Java Part of code. Juste move your tag or close your scriptlet
if(rs.getString(2).equals(pwd))
{
out.println("welcome"+userid);
%>
Delete
<%
}
else
{
out.println("Invalid password try again");
}

How to pass input From JSP to other JSP

First JSP, currencyConversion.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Currency Conversion</title>
<style>
label{ display: inline-block;
width: 140px;
text-align: left;
padding-top:10px;}
</style>
</head>
<body>
<h1>Use JSP Declaration tag, JSP Scriplet and JSP Expression
in application</h1>
<font style="color:plum; font-family:verdana;"><b>
Currency Conversion</b></font>
<form id="currency" action="processCurrency.jsp" method="get">
<label for="amount">Amount (in RM)</label>
<input name="amount" id="amount"></br>
<label for = "currency">Convert to</label>
<select name="currency" id = "currency"><br/>
<option value = "1">USD</option>
<option value = "2">Pound Sterling</option>
<option value = "3">Euro</option>
</select>
<br />
<br />
<input type = "submit" id = "btnSubmit" value="Submit"/>
<input type = "reset" id = "btnReset" value = "Reset"/>
</form>
</body>
</html>
Second JSP, processCurrency.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Currency process</title>
</head>
<body>
<%
String currency=request.getParameter("currency");
int amount=request.getParameter("amount");
%>
<%!
final double USD=3.92;
final double STG=5.96;
final double EURO=4.47;
double calculateRate(String currency, int amount)
{
double currencyChange=0.00f;
if(currency.equals("1"))
currencyChange=(double)(amount*USD);
if(currency.equals("2"))
currencyChange=(double)(amount*STG);
if(currency.equals("3"))
currencyChange=(double)(amount*EURO);
return currencyChange;
}
%>
</body>
</html>
I have try using JSP:param, but it wont let me pass the amount as it state that different datatype.
<%int amount=request.getParameter("amount");%>
How to pass the currency and amount from the currencyConversion.jsp into double calculateRate(String currency, int amount) in the processCurrency.jsp?
What you get is a String value, convert it to int.
int amount = Integer.valueOf(request.getParameter("amount"));
<%
String currency=request.getParameter("currency");
double amount=Double.valueOf(request.getParameter("amount"));
out.println("MYR "+amount+" to");
final double USD=3.92;
final double STG=5.96;
final double EURO=4.47;
double currencyChange=0.00f;
if(currency.equals("1")){
currencyChange=(double)(amount*USD);
out.println("USD "+currencyChange);}
else if(currency.equals("2")){
currencyChange=(double)(amount*STG);
out.println("Sterling Pound "+currencyChange);}
else if(currency.equals("3")){
currencyChange=(double)(amount*EURO);
out.println("EURO "+currencyChange);}
%>

How to catch missing JSP file Exception

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.
<%
}
%>

validating jstl sql datasource using javascript

I am trying to retrieve data from SQL query executed and validate the result with input I am making within form. I keep getting no return, in other words, it just returns empty value. Could you please help me with this matter or if this not the correct solution then how can I retrieve this value to perform validation.
My validation should match the inputed user with database user.
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<!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=US-ASCII">
<title>Insert title here</title>
<script>
function validateForm() {
var x = document.forms["input"]["user"].value;
var y = document.forms["input"]["pwd"].value;
if (x == null || x == "" && y==null || y=="" ) {
alert("Username and Password must be filled out");
return false;
}
}
function validateUser() {
var x = document.forms["input"]["user"].value;
var variableFromServer = "${names.FIRST_NAME}";
document.write('<p>'+variableFromServer+'</p>');
if (x != variableFromServer) {
alert("Username is not right"+variableFromServer);
return false;
}
}
</script>
</head>
<body>
<sql:setDataSource var="db" driver="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:********" user="******" password="******"/>
Connected
<sql:query dataSource="${db}" var="query_select">
Select * from User_Details
</sql:query>
<c:forEach var="names" items="${query_select.rows}" >
inside loop : <p>${names.FIRST_NAME}</p>
</c:forEach>
<form action= "/BilalWebtier/login.jsp" name="input" action="demo_form_action.asp" method="post" onsubmit="return validateForm() & validateUser();">
Username: <input type="text" name="user">
Password: <input type="password" name="pwd">
<input type="submit" value="Login">
<br/>
<br/>
</form>
<button type="button">Password Reset</button>
</body>
</html>
You should change it to the click event
<form action= "/BilalWebtier/login.jsp" name="input" action="demo_form_action.jsp" method="post" >
Username: <input type="text" name="user">
Password: <input type="password" name="pwd">
<input type="submit" value="Login" onclick="return validateForm() && validateUser();">
<br/>
<br/>
</form>

Passing values from servlet to google maps

I want to pass the google initialize function a latitude and a longitude, the question is that with different users might have different starting points, which means, different locations.
what i have right now is :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# 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=ISO-8859-1">
<title>Reminiscence Therapy</title>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<link rel=stylesheet
href="http://jquery.malsup.com/cycle2/demo/demo-slideshow.css">
<link rel=stylesheet href="http://fonts.googleapis.com/css?family=Acme">
<link rel=stylesheet href="http://jquery.malsup.com/cycle2/site.css">
<script>
var map;
function initialize(lat, lng) {
var mapProp = {
center : new google.maps.LatLng(lat, lng),
zoom : 18,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
google.maps.event.addDomListener(window, 'load', function() {
var lat = 51.45644, lng = -0.120850;
initialize(lat, lng);
});
</script>
</head>
<body>
<h2>My day in map</h2>
<div style='float: left'>
<form name='form1' action='FriendsListServlet' method='get'>
<input type='submit' name='btnsalvar' value='Photos of the day'>
</form>
</div>
<div>
<form name='form2' action='MapServlet' method='get'>
<input type='submit' name='btnsalvar' value='My day in map'>
</form>
</div>
<br />
<div id="googleMap"></div>
<div id="myWorkContent" class="myWorkContent">
<!-- Your images over here -->
<c:forEach items="${photosName}" var="photo">
<img src='images/<c:out value="${photo}" />' style="height: 80px;" />
</c:forEach>
</div>
<script src="http://www.google-analytics.com/urchin.js"></script>
<script>
_uacct = "UA-850242-2";
urchinTracker();
</script>
</body>
</html>
the problem is that the function
google.maps.event.addDomListener(window, 'load', function() {
is calling the initialize function with the values
var lat = 51.45644, lng = -0.120850;
but that is not what i want. I have a servlet that is behind this page. What that servlet does is calculating the starting point and i want the map to use as its center the point the servlet computes. How can that be done?
Change your jsp code to
var lat = <%= request.getAttribute("lat") %>, lng = <%= request.getAttribute("lng") %>;
In your servlet, before forwarding to the jsp, you need to add
request.setAttribute("lat",<Value which you calculated>);
request.setAttribute("lng",<Value which you calculated>);
Or, you may like to read the lat , lng from request.getParameter if you are using redirect to the page instead of forwarding.

Categories

Resources