I'm a complete beginner to JSPs and servlets and I would appreciate it if you could help me on this small problem. I have an index.html file that has links to two JSP files: addItem.jsp (user can input item into their todDo list, and submit button links to servlet), and toDoList.jsp (shows the toDO list and redirects via a button to addItem.jsp)
The problem I am having is that when I view the toDoList.jsp before adding an item to the list, the list does not appear. However, I add an item on addItem.jsp, the list shows from the servlet, and now I can view the full list, including the item that was added on toDoList.jsp.
How can I change my code so that I don't have to add something to the list to view it?
toDoList.jsp :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="javax.servlet.http.HttpSession" %>
<%#page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>My ToDo List:</h1>
<% ArrayList<String> toDoList = new ArrayList<String>();%>
<% if(session.getAttribute("toDoList") != null) { // If the list exists in the session %>
<% toDoList = (ArrayList<String>) session.getAttribute("toDoList");%>
<% for(String toDoItem:toDoList) { %>
<% out.println(toDoItem); %><br>
<% } %>
<% } else {%>
<h3>Your list is empty!</h3>
<% } %>
<form action="addItem.jsp" method="post">
<fieldset>
<input type="submit" value="Add Item">
</fieldset>
</form>
</body>
addItem.jsp :
<!DOCTYPE html>
<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="Servlet1" method="post">
<fieldset>
<label>New ToDo Item:</label>
<input type="text" name="item"><br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
The main Servlet1 code:
#WebServlet(urlPatterns = {"/Servlet1"})
public class Servlet1 extends HttpServlet {
ArrayList<String> toDoList = new ArrayList<String>();
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String item = request.getParameter("item");
toDoList.add(item);
HttpSession session = request.getSession();
boolean is_toDoList_Initilized = false;
if(session.getAttribute("toDoList") == null) {
is_toDoList_Initilized = false;
session.setAttribute("toDoList", toDoList);
} else is_toDoList_Initilized = true;
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Servlet1</title>");
out.println("</head>");
out.println("<body>");
for(String toDoItem:toDoList) {
out.println(toDoItem + "<br>");
}
out.println(is_toDoList_Initilized);
out.println("</body>");
out.println("</html>");
}
}
I think you just need to call that servlet before redirecting your toDoList.jsp from your index page.
Flow will be like
flow 1: index.jsp > servlet1 > toDoList
flow 2: index.jsp > addItem.jsp > servlet1 > toDoList
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 )
There is my jsp page in which a href links are there.
So i have to redirect it to that particular web page when i click to that link.
The links are fetched from my database.
Below is my jsp page
<%# page import="java.sql.*" %>
<%ResultSet rs=null; %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
Your Searched Results Are :
</title>
<link href="Desktop/style.css" rel="stylesheet" type="text/css" />
</head>
<body bgcolor="8B4513">
<%
Connection conn=null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection
("jdbc:mysql://localhost:3306/tendermysql","root","root");
Statement stmt=conn.createStatement();
rs=stmt.executeQuery("select * from Record");
%>
<form>
<center>
<h1> Welcome to Ezest Tender Optimzed Search</h1>
<%
while(rs.next())
{
%>
<a href= "<%rs.getString(2); %>"
onclick = "window.location.href=this.form.rs.getString(2)
[this.form.rs.getString(2)]" > <% out.println(rs.getString(2)); %>
</a>
<br />
<% } %>
<% }
catch(Exception e)
{
out.println("Wrong Input" +e);
}
%>
<br>
</center>
</form>
</body>
</html>
I tried it but the page is not redirecting...
Porblem here is that your ResultSet is forward only so you cannot use this line rs.getString(2) to get same record more than once inside loop. Use a temp variable to repeat the value. Also there is no need to give onclick attribute when href is given the same link.
String str;
while(rs.next()){
str = rs.getString(2);%>
<%=str%><%
}
Sample code with href and onclick:
<a href='http://stackoverflow.com/' onclick='return confirm("Visit page?")'>Stackoverflow</a>
P.S. Make sure to close db connection
I am trying to display a blob image in a jsp page by (using this) but i am getting an error:
javax.servlet.ServletException: java.sql.SQLException: Column '2' not found.
My table is:
create table upload_image
(
iImageID int AUTO_INCREMENT primary key,
bImage longblob
);
Code: uploadimage.jsp
<%# page language="java" errorPage="" %>
<html>
<head>
<title>Image insert into database</title>
</head>
<body>
<form name="frm" action="saveImage.jsp" enctype="multipart/form-data" method="post">
<input type="file" name="uProperty" /> <br>
<input type="submit" name="goUpload" value="Upload" />
</form>
</body>
</html>
saveImage.jsp
<%# page import="java.sql.*" %>
<%# page import="org.apache.commons.fileupload.*"%>
<%# page import="org.apache.commons.io.output.*"%>
<%# page import="org.apache.commons.fileupload.servlet.*"%>
<%# page import="org.apache.commons.fileupload.disk.*"%>
<%# page import="java.io.*"%>
<%# page import="java.util.*"%>
<%
Connection conn=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/online","root", "12345");
PreparedStatement psImageInsertDatabase=null;
byte[] b=null;
try{
String sqlImageInsertDatabase="insert into upload_image (bImage) values(?)";
psImageInsertDatabase=conn.prepareStatement(sqlImageInsertDatabase);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
List items = sfu.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
b = item.get();
}
}
psImageInsertDatabase.setBytes(1,b);
psImageInsertDatabase.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
response.sendRedirect("addimage.jsp");
}
%>
get.jsp
<%# page import ="java.sql.*" %>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/online","root", "12345");
Statement st = con.createStatement();
ResultSet i = st.executeQuery("select * from upload_image");
%>
<%
while(i.next( )){
%>
<img src="imageServlet?id=<%=i.getString("2")%>" />
<% }%>
After executing the get.jsp (after executing uploadimage.jsp) I am getting "Column '2' not found." Please help me to display the image in the jsp page
Its throwing an error cause it is finding a column named as 2 since you have put 2 in double quotes.Also I feel it should be 1 and not 2(but you know better)
This is the answer below
<img src="imageServlet?id=<%=i.getString(1)%>" />//with no quotes as you can see
or
<img src="imageServlet?id=<%=i.getString("iImageID")%>" />
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 am trying to do a JSP program where there is a number and a button. Upon clicking the button, the number above increments. I need to use sessions in this program.
This is the code I did:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Welcome </title>
</head>
<body>
<%
// check if there already is a "Counter" attrib in session
AddCount addCount = null;
int test = 0;
String s;
try {
s = session.getAttribute("Counter").toString();
} catch (NullPointerException e){
s = null;
}
if (s == null){
// if Counter doesn't exist create a new one
addCount = new AddCount();
session.setAttribute("Counter", addCount);
} else {
// else if it already exists, increment it
addCount = (AddCount) session.getAttribute("Counter");
test = addCount.getCounter();
addCount.setCounter(test);
addCount.addCounter(); // increment counter
session.setAttribute("Counter", addCount);
}
%>
<%! public void displayNum(){ %>
<p> Count: <%= test %> </p>
<%! } %>
<input TYPE="button" ONCLICK="displayNum()" value="Add 1" />
</body>
</html>
The result is that every time I run the program, the number increments.. however I do not want this to happen.. I want the number to increment upon clicking the button :/ What am I doing wrong?
Thanks for any help. Would be very much appreciated!
A schematic JSP, as it could have been done.
Here I assume that the page is named "counter.jsp" and that the AddCount class resides in a package "mypkg".
JSP encodings can be set in the HTML header lines, before the first HTML browser text.
For ISO-8859-1 you may actually use encoding Windows-1252, with extra chars, like special comma-like quotes. Even MacOS browsers will accept these.
Here I check whether the button was clicked, as whether the form parameter "somefield" is present. (There are other possibilities.)
session="true" is crucial here.
<%#page contentType="text/html; charset=Windows-1252"
pageEncoding="Windows-1252"
session="true"
import="java.util.Map, java.util.HashMap, mypkg.AddCount" %>
<%
// Check if there already is a "Counter" attrib in session
AddCount addCount = (AddCount)session.getAttribute("Counter");
if (addCount == null) {
// If Counter doesn't exist create a new one
addCount = new AddCount();
session.setAttribute("Counter", addCount);
}
// Inspect GET/POST parameters:
String somefield = request.getParameter("somefield");
if (field != null) {
// Form was submitted:
addCount.addCounter(); // increment counter
}
int count = addCount.getCounter();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome - counter.jsp</title>
</head>
<body>
<p> Count: <%= count %></p>
<form action="counter.jsp" method="post">
<input type="hidden" name="somefield" value="x" />
<input type="submit" value="Add 1" />
</form>
</body>
</html>