This question already has answers here:
Calling a servlet from JSP file on page load
(4 answers)
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 1 year ago.
I am trying to send data from the InformationServlet servlet to the information.jsp file it redirects to.
The InformationServlet is the following:
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
#WebServlet(name = "Information", value = "/Information")
public class InformationServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
RequestDispatcher dispatcher = request.getRequestDispatcher("administration.jsp");
dispatcher.forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
request.setAttribute("myemail",email);
request.getRequestDispatcher("information.jsp").forward(request, response); // forward the email to the .jsp
}
}
and the information.jsp is:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.sql.SQLException"%>
<%-- Database information --%>
<%
String id = request.getParameter("userid");
String driver = "com.mysql.cj.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "employees";
String userid = "root";
String password = "password";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
%>
<html>
<head>
<title>information</title>
</head>
<body>
<% String member_email = (String)request.getAttribute("myemail");
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement = connection.prepareStatement("Select surname, name, email, phone, CV from member left join resume on memberEmail = email where email = ?");
statement.setString(1, member_email);
resultSet = statement.executeQuery();
resultSet.next();
%>
<div id="table">
<a action="Information" method="post" class="table-row">
<span class="table-cell" name="surname"> <%=resultSet.getString("surname") %> </span>
<span class="table-cell" name="firstname"> <%=resultSet.getString("name") %> </span>
<span class="table-cell" name="email"> <%=resultSet.getString("email") %> </span>
<span class="table-cell" name="phone"> <%=resultSet.getString("phone") %> </span>
<span class="table-cell" name="cv"> <%=resultSet.getString("cv") %> </span>
</div>
<%
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
Basically the .jsp file retrieves some information from the database "employees" depending on the "myemail" parameter passed from the servlet. I've searched it up a lot online and from what I found this is the correct way of establishing a communication between the two file types, yet the member_email variable in the scriplet of the "information.jsp" file is null somehow. This is my first attempt of building a web application, so the usage of servlets/jsps is rather new to me, so maybe I have an obvious mistake.
Also in case it is needed, the "administration.jsp" the "InformationServlet" listens from is the following:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%-- Database information --%>
<%
String id = request.getParameter("userid");
String driver = "com.mysql.cj.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "employees";
String userid = "root";
String password = "password";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<html>
<head>
<title>Administration Page</title>
<link rel="stylesheet" href="css_files/initial.css">
</head>
<body>
<h1>Administration Page</h1>
<%
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select surname, name, email from member";
resultSet = statement.executeQuery(sql);
//each row will be filled with looping throw the table in the database
while(resultSet.next()){
%>
<div id="table">
<form method="post" action="information.jsp" class="table-row">
<span class="table-cell" name="surname"> <%=resultSet.getString("surname") %> </span>
<span class="table-cell" name="firstname"> <%=resultSet.getString("name") %> </span>
<span class="table-cell" name="email"> <%=resultSet.getString("email") %> </span>
<button type="submit">Navigate to user information</button>
</form>
</div>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
which is working as intended.
Related
Problem with insert data into Derby database
I use jsp and servlet, but I have try so many time but still can not insert data into database, it only shows
List of students with score:
and nothing else, it should insert user input into database, database connection is set, id data type is number , marks is int, name is varchar. No error in program I also add javaDB Driver to Libraries, I just do not understand what is wrong.
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>Student Score</title>
</head>
<body>
<h1>Welcome to Student Score Application</h1>
<form method="post" action="Result.jsp">
<input type="submit" value="View Data">
</form>
<br>
<form method="post" action="servletAdd">
ID:<input type="text" name="ID"><br>
Name:<input type="text" name="name"><br>
Marks:<input type="text" name="marks"><br>
<input type="submit" value="Add">
<input type="reset" value="Clear">
</form>
</body>
</html>
Result.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Result</title>
</head>
<body>
<h1>List of students with score:</h1>
<%#page import="java.sql.*"%>
<%
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/abc","abc","abc");
Statement stmt = con.createStatement();
String sql = "SELECT * FROM ABC";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String id = rs.getString("id");
String name = rs.getString("name");
int marks = rs.getInt("marks");
out.println("ID: "+ id);
out.println("Name: "+name);
out.println("Marks: "+marks);
%><br>
<%
}
//STEP 6:
rs.close();
stmt.close();
con.close();
%>
</body>
</html>
servletAdd.java
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
public class servletAdd extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String JDBC_DRIVER = "org.apache.derby.jdbc.ClientDriver";
String DB_URL = "jdbc:derby://localhost:1527/abc";
String USER ="abc";
String PASS ="abc";
Connection conn = null;
Statement stmt = null;
String id = request.getParameter("ID");
String name = request.getParameter("name");
int marks = Integer.parseInt(request.getParameter("marks"));
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/abc",USER,PASS);
stmt = conn.createStatement();
String sql = "INSERT into ABC values"+"("+ "'"+ id +"'"+ ","+ name + ","+ "'"+ marks+"'"+")";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
response.setContentType("text/html;charset=UTF-8");
response.sendRedirect(request.getContextPath()+"/Result.jsp");
}
}
I want to upload an image file in my project directory folder named Images and store the image name in a database.
The file name has been saved in the database and my image retrieved by the browser properly, but when I check my directory folder named Images it is empty.
My questions is: Where is my file stored and why can't I see the image file in my folder?
This is my Index.jsp file
<%--
Document : index
Created on : Mar 15, 2018, 7:30:15 PM
Author : Lenovo
--%>
<%#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 name="form1" method="post" enctype="multipart/form-data" action="insertimage.jsp">
<p>
<input type="file" name="ImageFile" id="ImageFile" />
</p>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</body>
</html>
This is my insertimage.jsp file
<%# page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%# page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%# page import="org.apache.commons.fileupload.*"%>
<%# page import="java.util.*, java.io.*" %>
<%# page import="java.util.Iterator"%>
<%# page import="java.util.List"%>
<%# page import="java.io.File"%>
<%# page contentType="text/html;charset=UTF-8" %>
<%# include file="getcon.jsp"%> <!-- to connect a database-->
<%
try
{
String ImageFile="";
String itemName = "";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart)
{
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
e.getMessage();
}
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
String name = item.getFieldName();
String value = item.getString();
if(name.equals("ImageFile"))
{
ImageFile=value;
}
}
else
{
try
{
itemName = item.getName();
File savedFile = new File(config.getServletContext().getRealPath("/") + "Images\\" + itemName);
out.println("File Uploaded.." + itemName);
item.write(savedFile);
}
catch (Exception e)
{
out.println("Error" + e.getMessage());
}
}
}
try
{
st.executeUpdate("insert into test(image) values ('" + itemName + "')");
}
catch(Exception el)
{
out.println("Inserting error" + el.getMessage());
}
}
}
catch (Exception e)
{
out.println(e.getMessage());
}
%>
This is my retrieveimage.jsp file
<%# include file="getcon.jsp"%>
<html>
<head>
<title>View Image Page</title>
</head>
<body>
<table width="100%" border="0">
<!-- main content -->
<%
ResultSet rs=null;
try
{
rs = st.executeQuery("select image from test");
while(rs.next())
{
%>
<table width="70%" height="160" border="1" align="center">
<tr>
<!-- Mention Directory where your images has been saved-->
<td><img src="Images/<%=rs.getString("image") %>" width="115" height="128" /></td>
</tr>
</table>
<%
}
}
catch(Exception e)
{
out.print("" + e.getMessage());
}
%>
</table>
</body>
</html>
This is my connection file
<%#page import="java.sql.*" %>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample", "root", "root");
Statement st = con.createStatement();
%>
The following has more chance of working.
File savedFile = new File(config.getServletContext().getRealPath("/Images/" + itemName));
savedFile.getParentFile().mkdirs();
...
Not sure whether the server is also Windows; on other systems path names are case-sensitive (Images with capital i).
You could provide a fixed itemName for testing.
The img tag might need to be:
<img src="/Images/ ...
I have this code to show the images but it not works. doesnt display the image just a little white square, i've been looking for an answer and i cant find , somebody to help me, please.
Show.jsp
<%# page import="java.sql.*" %>
<%# page import='java.io.InputStream' %>
<%# page import='java.io.OutputStream' %>
<%
String login = "root";
String password = "";
String url = "jdbc:mysql://localhost/dbimagenes";
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
int nBytes=0;
%>
<html><style type="text/css">
<!--
body {
background-color: #F5f5f5;
}
-->
</style><body>
<h1>Imagen desde MySQL</h1>
<table>
<tr><td>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection(url, login, password);
statement = conn.createStatement();
rs = statement.executeQuery("SELECT imagen FROM t_imagenes where id='2'");
try{
if(rs.next()){
response.setContentType("image/jpeg");
InputStream is = rs.getBinaryStream(1);
OutputStream aux= response.getOutputStream();
out.println("jajaja");
byte [] buffer = new byte[4096];
for (;;) {
nBytes = is.read(buffer);
if (nBytes == -1)
break;
aux.write(buffer, 0, nBytes);
}
is.close();
aux.flush();
aux.close();
}else{
throw new SQLException("image not found");
}
rs.close();
} catch (SQLException e) { out.println("Imagen no encontrada");}
out.println("no se muestra");
%>
</td></tr></table>
<p> Imagen</p>
PRINCIPAL
</body></html>
My way to save the images into mysql is of this way:
Insert.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#include file="conexion.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Insertar</h1>
<%
String nombre=request.getParameter("txtnombre");
String marca=request.getParameter("txtmarca");
String imagen=request.getParameter("txtimagen");
if(nombre!=null && marca!=null && imagen!=null){
String qry ="insert into t_imagenes(nombre,marca,imagen) values('"+nombre+"','"+marca+"','"+imagen+"')";
sql.executeUpdate(qry);
out.print("Datos Registrados "
+ "<a href='index.jsp'>REGRESAR</a>");
}else{
%>
<form name="frmimagenes" method="post" action="insertar.jsp">
nombre: <input type="text" name="txtnombre"/><br/>
marca: <input type="text" name="txtmarca"/><br/>
imagen: <input type="file" name="txtimagen" value="" size="50" /><br/>
<input type="submit" value="Guardar">
</form>
<%}//else%>
</body>
</html>
you need to use image tag img to display the image in html (i have not test the following code, please adjust it if it has any error)
<%# page import="java.sql.*" %>
<%# page import='java.io.InputStream' %>
<%# page import='java.io.OutputStream' %>
<%# page import='java.io.ByteArrayOutputStream' %>
<%# page import='org.apache.commons.codec.binary.Base64' %>
<%
String login = "root";
String password = "";
String url = "jdbc:mysql://localhost/dbimagenes";
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
int nBytes=0;
%>
<html><style type="text/css">
<!--
body {
background-color: #F5f5f5;
}
-->
</style><body>
<h1>Imagen desde MySQL</h1>
<table>
<tr><td>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, login, password);
statement = conn.createStatement();
rs = statement.executeQuery("SELECT imagen FROM t_imagenes where id='2'");
String url = "data:image/jpeg;base64,";
try{
if(rs.next()){
InputStream is = rs.getBinaryStream(1);
OutputStream aux = new ByteArrayOutputStream();
out.println("jajaja");
byte [] buffer = new byte[4096];
for (;;) {
nBytes = is.read(buffer);
if (nBytes == -1)
break;
aux.write(buffer, 0, nBytes);
}
is.close();
aux.flush();
url += new String(Base64.encodeBase64(aux.toByteArray()));
aux.close();
}else{
throw new SQLException("image not found");
}
rs.close();
} catch (SQLException e) { out.println("Imagen no encontrada");}
out.println("no se muestra");
%>
<img src="<%=url%>" />
</td></tr></table>
<p> Imagen</p>
PRINCIPAL
</body></html>
I wanted to pass the value retrieved on a java class to a page.I am using DAO classes.
I have retrieved the values from the database and stored them on String variables.Now I want to set them to the text boxes in my view.jsp page.I am new to this area,can anyone help me out??
View.jsp is as
<%# 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="process.jsp">
Enter Name <br/> <br> <input type="text" name="uname" onclick="this.value=''"/><br/><br/>
<input type="submit" value="view details"/><br/><br/>
Email id: <br/> <input type="text" name="email" id="email" > <br/><br/>
password: <br/> <input type="text" name="passw" id="passw"><br/><br/>
</form>
</body>
</html>
and My Activity ViewDAO.java is as
public static void view(user u) {
Connection con=ConnectionProvider.getCon();
String uname=u.getUname();
try {
PreparedStatement ps=con.prepareStatement("select email,pass from S1.USER432 where name='"+uname+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String pass = rs.getString("PASS");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks...
If you are using a front controller[spring mvc] then you can pass the data by doing,
model.addAttribute("variable_name ", data);
and in the jsp you can access it by doing this ${variable_name};
You need to call the DAO method from your servlet like below:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// call DAO method to get the email and password
HashMap<String,String> map=ViewDAO.getDetails();
//from the map you will get the email and password.then you need to set them in the attributes and get them in your jsp
request.setAttribute("email", map.get("email"));
request.setAttribute("password", map.get("password"));
}
your DAO method should be like the below:
public static HashMap<String,String> getDetails(user u) {
Connection con=ConnectionProvider.getCon();
String uname=u.getUname();
Map<String,String> map=new HashMap<>();
try {
PreparedStatement ps=con.prepareStatement("select email,pass from S1.USER432 where name='"+uname+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String pass = rs.getString("PASS");
}
map.put("email",email);
map.put("password",pass);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
}
Hope this will help you.
if you are using simple jsp and servelt, then make one ViewController.java.
You can two methods one for handling GET and other for POST
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String email = request.getParameter("email");
String password = request.getParameter("password");
request.setAttribute("email", email);
request.setAttribute("password", password);
request.getRequestDispatcher("view.jsp").forward(request, response);
}
catch(Exception e){
}
View.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="process.jsp">
Enter Name <br/> <br> <input type="text" name="uname" onclick="this.value=''"/><br/><br/>
<input type="submit" value="view details"/><br/><br/>
Email id: <br/> <input type="text" name="email" id="email" value="<%=email%>" > <br/><br/>
password: <br/> <input type="text" name="passw" id="passw" value="<%=password%>"><br/><br/>
</form>
</body>
</html>
The Servlet decides which page must be loaded. So whatever you get from the DAO must go to the Servlet and through that, to the jsp. You can use a bean class to send values from DAO to Servlet.
Like this,
public class Details{
private String email;
private String password;
public void setEmail(String email){
this.email = email;
}
public void setPassword(String password){
this.password= password;
}
public String getEmail(){
return this.email;
}
public String getPassword(){
return this.password;
}
}
And you can make the following changes in DAO after getting the query results in the String. Add these
Details d = new Details();
d.setEmail(email);
d.setPassword(pass);
return d;
You can pass this object d to the servlet and retrieve the values using the getter methods of the bean. Also, the DAO must be called from the Servlet.
And now on the Servlet side.
On the Servlet you can put your code in the get or post method depending on your need. It may be like
public class ExampleServlet extends HttpServlet{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email"); //got from the jsp where "email" is the name attribute of the input field
Details d = new Details();
d = ViewDao.view(user_object); //the bean sent by DAO. "user_object" is parameter that your DAO method is taking in your code
if(d.getEmail()!=null){ //just an example
// your code that redirects desired page
}
}
}
Based on d returned by the DAO you may redirect to any page you want.
Something like that
Observe this import
dao.UserDao,bean.*,
dao is the package
UserDao is the class
bean is the method you want or is could an attribute from dao
remember that
jsp
<body>
<%#page import="dao.UserDao,bean.*,java.util.*"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Users List</h1>
<%
List<User> list=UserDao.getAllRecords();
request.setAttribute("list",list);
%>
<div class="table-responsive">
<table class="table">
<thread class="bg-info">
<th>Id</th><th>Name</th><th>Password</th><th>Edit</th><th>Delete</th>
</thread>
<c:forEach items="${list}" var="u">
<tr>
<td>${u.getId()}</td><td>${u.getUsername()}</td><td>${u.getPassword()}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</div>
<br/>Add New User
<br>
<br>
<form action="index.jsp">
<button type="submit">IndexUsers</button>
</form>
</body>
Bean or model
package bean;
// classe para as tables
public class User {
private int id;
private String username,password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
dao
public class UserDao {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql_database","root","14570");
}catch(Exception e){System.out.println(e);}
return con;
}
public static int save(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"insert into login(username,password) values(?,?)");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int update(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"update login set username=?,password=? where id=?");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
ps.setInt(3,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("delete from login where id=?");
ps.setInt(1,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static List<User> getAllRecords(){
List<User> list=new ArrayList<User>();
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from login");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
list.add(u);
}
}catch(Exception e){System.out.println(e);}
return list;
}
public static User getRecordById(int id){
User u=null;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from login where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
}
}catch(Exception e){System.out.println(e);}
return u;
}
}
Another Example this import import="dao.*"% makes available any methods from package dao, Bellow you see how to get the result of the method countid() in the dao.
<%#page import="dao.*"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<% int id = 0; %>
<%
DaoEvento daoEvento = new DaoEvento();
id = daoEvento.countId();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<body>
<br><br>
<form action="add_event_servletnew" method="POST">
<div class="form-group">
<td>
<font color='green' face = "Arial" size = "4">
<%= request.getParameter("message") %>
</font>
view
<td>
</div>
<div class="form-group">
<label>id</label>
<input type="text" name="id" value="<%= id%>" readonly="readonly" class="form-control"/>
</div>
<div class="form-group">
<label>Title</label>
<input type="text" name="title" value="" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<input type="date" name="start" value="" class="form-control"/>
</div>
<div class="form-group">
<label>End</label>
<input type="date" name="end" value="" class="form-control" />
</div>
<div class="form-group">
<td><input type="submit" value="submit" class="btn btn-success btn-block"/></td>
</div>
</form>
</body>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
<script src="jquery.mask.min.js"> </script>
</html>
Hello i'm trying to create a page to update a row in my database table i'm using DAO/Servlet with JSP page
DAO code:
public static AnimalUpdateBean updateAnimal(AnimalUpdateBean bean) {
//preparing some objects for connection
PreparedStatement up = null;
Statement stmt = null;
String id = bean.getAnimalId();
String aname = bean.getAnimalName();
String dob = bean.getAnimalDob();
String gender = bean.getAnimalGender();
String breedid = bean.getAnimalBreed();
String remark = bean.getAnimalRemark();
try
{
//connect to DB
currentCon = dbConnection.getConnection();
up = currentCon.prepareStatement("update animal set aname = '"+aname+"' , gender = '"+gender+"', specie_id = '"
+breedid+"' , remark = '"+remark+"' where animal_id = '"+id+"'");
up.executeUpdate();
if (up.executeUpdate()>=1){
stmt=currentCon.createStatement();
rs = stmt.executeQuery("select aname , dob, gender, specie_id , remark from animal where animal_id = '"+id+"'");
}
System.out.println("done");
}
catch (Exception ex)
{
System.out.println("Log In failed: An Exception has occurred! " + ex);
}
//some exception handling
finally
{
if (rs != null) {try {rs.close();} catch (Exception e) {} rs = null;}
if (stmt != null) {try {stmt.close();} catch (Exception e) {}stmt = null;}
if (currentCon != null) {try {currentCon.close();} catch (Exception e) {}currentCon = null;}
}
return bean;
}
}
UpdateAnimal.jsp code:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="java.util.ArrayList" %>
<%#page import="content.*"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%# page session="true"%>
<%#page import="java.io.*"%>
<%#page import="java.net.*"%>
<%#page import="javax.servlet.*"%>
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256" %>
<!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=windows-1256">
<title>Update Animal</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Zoo keeper</th></tr>
</table>
<h1>Update Animal</h1>
<form action="Relay" >
<fieldset>
Animal new name: <input type= "text" name = "aname"><br>
Animal new DOB: <input type= "text" name = "dob"><br>
<br>
Animal new gender:
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
Animal new Breed: <input type= "text" name = "breedid" ><br>
Animal new remarks: <textarea name = "remark" rows="4" cols="20">
</textarea> <br /> <br/>
<input type="submit" value="submit">
<input type="hidden" name="animal_id" value="<%= request.getParameter("animal_id") %>">
<input type="hidden" name="command" value="UpdateAnimalServlet" >
</fieldset>
</form>
</body></html>
the record being updated come from a select page to view the records when the user click on the name he will be redirected to update page CheckAnimal.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="java.util.ArrayList" %>
<%#page import="content.*"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%# page session="true"%>
<%#page import="java.io.*"%>
<%#page import="java.net.*"%>
<%#page import="javax.servlet.*"%>
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256" %>
<!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=windows-1256">
<title>Animal list</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Zoo keeper</th></tr>
</table>
<h1>Animal list</h1>
Click on animal name to update it!
<center>
<table width="100 % " id='table1' border="1" cellspacing="2" cellpadding="2">
<tr class="tab-highlighted-2">
<td class="tab-highlighted-2" width="15">
<div align="left">Name</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Age</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Gender</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Status</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Breed</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Pen #</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Zoo</div>
</td>
<td class="tab-highlighted-2" width="20">
<div align="left">Remarks</div>
</td>
</tr>
<c:forEach items="${beans}" var="view">
<tr>
<td>${view.animalName}</td>
<td>${view.animalDob}</td>
<td>${view.animalGender}</td>
<td>${view.animalSource}</td>
<td>${view.animalBreed}</td>
<td>${view.sectionId}</td>
<td>${view.zooId}</td>
<td>${view.animalRemark}</td>
</tr>
</c:forEach>
</table>
</center>
</body></html>
AnimalUpdateBean.java code:
package content;
public class AnimalUpdateBean {
private String animalId;
private String animalName;
private String animalDob;
private String animalGender;
private String animalBreed;
private String animalRemark;
public String getAnimalId() {return animalId;}
public String getAnimalName() {return animalName;}
public String getAnimalDob() {return animalDob;}
public String getAnimalGender() {return animalGender;}
public String getAnimalBreed() {return animalBreed;}
public String getAnimalRemark() {return animalRemark;}
public void setAnimalId(String animalId) {this.animalId = animalId;}
public void setAnimalName(String animalName) {this.animalName = animalName;}
public void setAnimalDob(String animalDob) {this.animalDob = animalDob;}
public void setAnimalGender(String animalGender) {this.animalGender = animalGender;}
public void setAnimalBreed(String animalBreed) {this.animalBreed = animalBreed;}
public void setAnimalRemark(String animalRemark) {this.animalRemark = animalRemark;}
}
the servlet responsible to start the update is UpdateAnimalServlet:
package content;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginServlet
*/
public class UpdateAnimalServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
AnimalUpdateBean animal = new AnimalUpdateBean();
animal.setAnimalId(request.getParameter("animal_id"));
animal.setAnimalName(request.getParameter("aname"));
// animal.setAnimalDob(request.getParameter("dob"));
animal.setAnimalGender(request.getParameter("gender"));
animal.setAnimalBreed(request.getParameter("breedid"));
animal.setAnimalRemark(request.getParameter("remark"));
String test = request.getParameter("animal_id");
System.out.println(test);
System.out.println(animal);
animal = DAO.updateAnimal(animal);
response.sendRedirect("/oosd/member.jsp");
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
I'm using a Relay servlet that calls AnimalUpdateServlet for execution:
package content;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class Relay extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
String command = request.getParameter("command");
if (command.equals("LoginServlet")){
RequestDispatcher rd =request.getRequestDispatcher("/"+command);
rd.forward(request, response);
//for testing
System.out.println("Request forwarded to " + command + " servlet");
} else if (command.equals("UpdateAnimalServlet")){
RequestDispatcher rd =request.getRequestDispatcher("/"+command);
rd.forward(request, response);
//for testing
System.out.println("Request forwarded to " + command + " servlet");
}
else
System.out.println("=> command='" + command + "'");
String url = "/oosd/" + command;
String encodedUrl = response.encodeRedirectURL(url);
System.out.println(" url=" + url);
System.out.println(" encodedUrl=" + encodedUrl);
response.sendRedirect(encodedUrl);
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
and last thing is the web.xml page:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>content.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>UpdateAnimalServlet</servlet-name>
<servlet-class>content.UpdateAnimalServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>SelectAnimalServlet</servlet-name>
<servlet-class>content.SelectAnimalServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Relay</servlet-name>
<servlet-class>content.Relay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SelectAnimalServlet</servlet-name>
<url-pattern>/SelectAnimalServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UpdateAnimalServlet</servlet-name>
<url-pattern>/UpdateAnimalServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Relay</servlet-name>
<url-pattern>/Relay</url-pattern>
</servlet-mapping>
</web-app>
I keep getting these errors:
Log In failed: An Exception has occurred! java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
I have checked the data entry and all correct name text, gender text, specie_id number, remark text i even put the dob on hold until this work i'm using access database and here is the connection code:
package content;
import java.sql.*;
public class dbConnection {
static Connection con;
static String url;
public static Connection getConnection()
{
try
{
String url = "jdbc:odbc:oosd";
// assuming "DataSource" is your DataSource name
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
try
{
con = DriverManager.getConnection(url,"","");
// assuming your SQL Server's username is "username"
// and password is "password"
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
return con;
}
}
Any idea where is my mistake here ?
as specie_id is a number and that's what the thrown exception is stating "Data type mismatch in criteria expression." and because of this exception sendRedirect error is occuring as because of the SQLException data has been already written to the response.
your query should be something like
"update animal set aname = '"+aname+"' , gender = '"+gender+"', specie_id = "
+Integer.parseInt(breedid)+" , remark = '"+remark+"' where animal_id = '"+id+"'"
same would be required if animal_id is also a number.
The sendRedirect error happens when you've already written data to the response (like with a forward, or to the JSP writer directly) then try to redirect.
The SQL error is likely due to you using a string IDs in the SQL (surrounded by single-quotes) whereas the IDs in the DB are most likely defined as an integer.
Also, after you update the animal, you perform a query, but do nothing with the results.