I am developing a college project and i will try to explain my problem using a small example.
Below there are 3 jsp pages (index.jsp , test.jsp , logged.jsp) and i want that if the user try to access logged.jsp directly by entering url http://localhost:8080/sessionTest/logged.jsp then he will be redirected to index.jsp.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action ="test.jsp" method="post">
enter user id :<input type="text" name="user">
Enter password:<input type="password" name="pass">
<input type="submit" value="submit">
</form>
</body>
</html>
test.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String user= request.getParameter("user");
String pass= request.getParameter("pass");
if(user.equals("snow")&& pass.equals("123"))
{
session.setAttribute("user", user);
RequestDispatcher r = request.getRequestDispatcher("logged.jsp");
r.forward(request, response);
}
else {
out.println("wrong pass or id");
}
%>
</body>
</html>
logged.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<% session = request.getSession(false);
if(session==null)
{
response.sendRedirect("index.jsp");
}
else{
out.println("welcome its old session");
}
%>
</body>
</html>
please , help me with some code and explain how it works
Try this one may be it helps you :
<%
HttpSession session = request.getSession();
if(null!=session.getAttribute("username")){
out.write("username is "+session.getAttribute("username").toString());
}
else{
response.sendRedirect("/index.jsp");
}
%>
Related
Below is my index.html and action.jsp code
When I am submitting the values from index.html to action.jsp instead of getting the output of out.println in action.jsp I am getting the complete action.jsp as my output.
Advise what is the issue and how to rectify it also advise if the directory structure is correct i.e.; all files are placed where they are usually supposed to be placed or not
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="action.jsp" method="post">
Name <input type="text" name = "name"> <br>
Password <input type="password" name="password"> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
// Below is action.jsp
<%#page import="p1.NewHibernateUtil"%>
<%#page import="org.hibernate.Transaction"%>
<%#page import="p1.User"%>
<%#page import="org.hibernate.Session"%>
<%#page import="org.hibernate.SessionFactory"%>
<%#page import="org.hibernate.cfg.Configuration"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
out.println("In scriplet tag");
Configuration cfg = new Configuration();
out.println("Configuration object created");
cfg.configure("hibernate.cfg.xml");
out.println("Configured");
// SessionFactory sf = NewHibernateUtil.getSessionFactory();
// out.println("SessionFactory created");
// Session ses = sf.openSession();
// Transaction t = ses.beginTransaction();
// String n = request.getParameter("name");
// String p = request.getParameter("password");
//
// out.println("Welcome " + n);
// User u1 = new User(n, p);
// ses.save(u1);
// t.commit();
// ses.close();
// out.println("Data inserted successfully");
%>
</body>
</html>
As per my assumption you are running the given example without using web server. You will require web server to run given code.
Consider using web server (ex. Tomcat http://tomcat.apache.org/tomcat-8.0-doc/index.html )
I am trying to insert image in mysql database & retrive it and displayimg it another jsp page but while retriving its not displaying image in browser instead it started download can you help me in this. . , and my code is . .,
Addimage.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>
<form action="AddImg.jsp" method="post">
Image<input type="file" name="file" value="upload" /><br>
<input type="submit" value="Add"/>
</form>
</body>
</html>`
and AddImg.jsp
<%#page import="java.sql.*" %>
<%#page import="java.io.*" %>
<%
Connection con;
PreparedStatement stmt;
ResultSet rs;
byte[] b=null;
//int f;
%>
<%# 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">
<%
String filenm=request.getParameter("file");
String f="C:/visualverify02/limitedimages/"+filenm;
File file=new File(f);
FileInputStream fin =new FileInputStream(file);
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/imgdb","root","password");
stmt=con.prepareStatement("insert into img values(?)");
//String str="insert into img values ('"+file2+"')";
stmt.setBinaryStream(1,(InputStream) fin, (int) (file.length()));
int count=stmt.executeUpdate();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
if(count>0)
{
out.println("img inserted");
rs = stmt.executeQuery("SELECT * FROM img ");
int i = 1;
if(rs.next()) {
Blob len1 = rs.getBlob("imgfile");
//int len = (int)len1.length();
b = len1.getBytes(1,(int)len1.length());
}else{out.println("Img not selected");}
response.setContentType("image/jpg");
OutputStream o=response.getOutputStream();
%>
<table>
<tr><td><%o.write(b); %></td></tr>
<%
o.flush();
o.close();
}
else{
out.println("Not inserted");
}
%>
</table>
</body>
</html>
First of all I think it's bad practice to have scriptlets in your jsp. I would suggest use at least a http servlet as a controller that deals with storing the image.
Secondly, the way the code is written you are not writing an image to a html page, but to a file, that will trigger downloading that file. To do what you want to archive your contenttype should be "text/html" and the output should be a html with an image tag like described in how to show byte data in an img tag
I have the following JSP page:
<%#page import="com.myPath.JSPHelper"%>
<%#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=utf-8">
<meta name="keywords" content="${jspHelper.getKeywordsMetatag()}">
</head>
<body>
<%
JSPHelper jspHelper = new JSPHelper();
jspHelper.loadData(request.getAttribute("id").toString()); // load data from database
%>
<script type="text/javascript">
<%=jspHelper.getScriptContent()%>
</script>
</body>
</html>
What I'm trying to do is to fill in the contents of the keywords meta tag using a function getKeywordsMetatag() that is defined in a companion class `JSPHelper.java'.
But this is not working, I get the following error:
The function getKeywordsMetatag must be used with a prefix when a default namespace is not specified
I'm new to JSP so I've tried many things without success.
What am I doing wrong here?
What really bothers me is that the function getScriptContent() perfectly works, dumping javascript code in the html page. Why does getScriptContent() work but not getKeywordsMetatag()?
Thanks!
I would move the declaration of jspHelper up above its first use. I would also drop the ${} syntax but that might not be necessary.
<%#page import="com.myPath.JSPHelper"%>
<%#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">
<%
JSPHelper jspHelper = new JSPHelper();
%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="<%=jspHelper.getKeywordsMetatag()%>">
</head>
<body>
<%
jspHelper.loadData(request.getAttribute("id").toString()); // load data from database
%>
<script type="text/javascript">
<%=jspHelper.getScriptContent()%>
</script>
</body>
</html>
Hi I want to do a JSP program where there is a number displayed and a button. When the user clicks this button the number above it increments. I want to include sessions in this program.
What I have done is this:
This is the form in html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Form</title>
</head>
<body>
<%! public void displayNum(){ %>
Number: <%=session.getAttribute("Counter") %>
<%! } %>
<FORM METHOD=POST ACTION="getcount.jsp">
<button TYPE="button" ONCLICK= "displayNum()">Add 1</button>
</FORM>
</body>
</html>
and this is myJSP file:
<%
AddCount addCount = new AddCount();
addCount.setCounter(addCount.addCounter(addCount.getCounter()));
int counter = addCount.getCounter();
session.setAttribute("Counter", counter);
%>
where AddCount is a java class with a variable counter, setter and getter and a function to increase the counter - addCount(num); all I'm getting when running the file is a button without any text in it :/
I've been trying over and over again. Can someone help me please?
Thankss!
You are adding java code in html, which is not possible.
Second thing even if you are having a static int counter in AddCount it wont work as many user s may use this page and expect only one increment for their each click.
So what you should do is write a jsp file like this index.jsp
<%Integer counter = (Integer)request.getSession().getAttribute("counter")
if(counter==null) {counter=0;}
counter ++;
request.getSession().setAttribute("counter",counter);
%>
<div>counter=<%=counter%></div><br>
+1
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Form</title>
</head>
<body>
function displayNum()
{
<%
AddCount addCount = new AddCount();
addCount.setCounter(addCount.addCounter(addCount.getCounter()));
int counter = addCount.getCounter();
session.setAttribute("Counter", counter);
%>
document.getElementById("demo").innerHTML="<%=session.getAttribute("Counter")%>";
}
<p id="demo"> {number will be displayed here} </p>
<button TYPE="button" ONCLICK= "displayNum()">Add 1</button>
</body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="jquery.js"></script>
<title>My Form</title>
</head>
<body>
<script>
$(document).ready(function() {
$("button").click(function() {
$("#div1").load("increament.jsp");
});
});
</script>
<div id="div1"> {number will be displayed here} </div>
<button>Add 1</button>
</body>
</html>
and increament.jsp file :
<%
int count;
if (session.getAttribute("Counter") == null) {
count = 1;
} else {
count = (Integer) session.getAttribute("Counter");
count++;
}
session.setAttribute("Counter", count);
out.println(session.getAttribute("Counter"));
%>
I want to redircet to another page by meta refresh, but only after all resources were loaded. Any ideas how to archive that?
SOLUTION:
I combined both ways, the meta refresh and the jQuery way.
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="pos" uri="/WEB-INF/tld/pos.tld" %>
<%# taglib prefix="template" tagdir="/WEB-INF/tags" %>
<%# page pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="description" content="" />
<meta http-equiv="Refresh" content="1; url=${callback}/" />
<script type="text/javascript" src="/JS/pos_js/jquery-latest.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
window.location = '${callback}';
});
</script>
</body>
</html>
With this way, for me, it is possible to redirect if the document in fully loaded and if JS is deactivated the meta refresh will throw the user to the callback page.
Only real way of doing it is:
<meta http-equiv="Refresh" content="1500; url=http://www.example.com/" />
That will wait 1.5 seconds for the page to load... not ideal, but without JS you'll be lucky!
edit: What about an iFramed option?
You could do this via jQuery using the $(document).load() function.
$(document).load(function() {
window.location = 'http://new.url.com';
});