I am trying to show the data of the user that I intend to update.
In my structure I enter a dni that is extracted when consulting a list, to then show the user's data in particular in another form. When this form is sent, the data will be permanently updated.
The problem I have is that I do not know how to show the user's data that I have previously searched for.
P.E: I am looking for a user called Jhon Doe with DNI 11111111E, in the second form I will have a new form with name and surname Jhon Doe, now I write in those fields of the form Mike Doe and press submmit.
The problem: I don, t know how to show the old name in my form (i don, t know hot to show Jhon Doe).
Here is my code, now i am stuck in that part, the update itseld is ok, but the name is not showed)
I have add my jsp web page to see how they works, but anyway my problem is about the way i manage to show the date from the user who will be updated.
My first jsp page here(V2formModificarUsuario1.jsp)
<%#page import="java.util.List"%>
<%#page import="Entidades.Usuario"%>
<%#page import="DAO.DAOUsuario"%>
<%#page import="Conexion.DBConnection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario" />
<jsp:setProperty name="usuario" property="*"/>
<%
String message = "";
List<Usuario> usuarios = null;
DAOUsuario dao = new DAOUsuario();
try {
//usuarios = dao.selectUsuario("si","nombre");
usuarios = dao.selectAllUsuarios();
} catch (Exception ex) {
message = ex.toString();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>V2formListarUsuariosAltaNombre</title>
<link href="../css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - LISTADOS USUARIOS</h1>
<div id="menu">
<div id="opciones">
<h2>Menu inicial</h2>
<h2>Atras</h2>
</div>
<form id="formulario" action="V2formModificarUsuario2(en obras).jsp" method="POST">
<label for="DNI">Intruduzca DNI del usuario</label><br>
DNI: <input type="text" name="DNI" required="">
<input type="submit" value="buscar">
</form>
<form>
<%if (!message.isEmpty()) {%>
<input name="status_initial" type="text" style="width:400px" value="<%=message%>"/>
<%} else { %>
<br/><br/>
<table border="1">
<tr>
<th>DNI</th>
<th>nombre</th>
<th>apellidos</th>
<th>de alta</th>
</tr>
<%for (int i = 0; i < usuarios.size(); i++) {%>
<tr>
<td><%=usuarios.get(i).getDNI()%></td>
<td><%=usuarios.get(i).getNombre()%></td>
<td><%=usuarios.get(i).getApellidos()%></td>
<td><%=usuarios.get(i).getDeAlta()%></td>
</tr>
<%}%>
</table>
<%}%>
</form>
</div>
</div>
</body>
My second jsp page here(V2formModificarUsuario2.jsp)
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%#page import="Entidades.Usuario"%>
<%#page import="DAO.DAOUsuario"%>
<%#page import="Conexion.DBConnection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario"></jsp:useBean>
<jsp:setProperty name="usuario" property="*"/>
<%
String message = "";
// String nameToChange = "";
String surnameToChange = "";
try {
if ((usuario.getDNI() != null) && (!usuario.getDNI().isEmpty())) {
DAOUsuario dao = new DAOUsuario();
// nameToChange=dao.selectByDNI(request.getParameter("DNI")).getNombre(); comentado por ahora
surnameToChange=dao.selectByDNI(request.getParameter("DNI")).getApellidos();
Usuario usuarios = dao.selectByDNI(usuario.getDNI());
if (usuarios != null) {
if ((usuario.getNombre() != null) && (!usuario.getNombre().isEmpty())
&& (usuario.getApellidos() != null) && (!usuario.getApellidos().isEmpty())) {
dao.update(usuario.getDNI(), usuario.getNombre(), usuario.getApellidos());
message = "User correctly updated.";
} else {
if (request.getParameter("updating") == "1") {
message = "Los campos name, surname and deAlta are required .";
}
}
} else {
message = "user do not exists.";
}
} else {
message = "DNI must not be null.";
}
} catch (Exception ex) {
message = ex.getMessage();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSPformModificarUsuario2(en obras)</title>
<link href="css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - USUARIO</h1>
<div id="menu">
<div id="opciones">
<h2>Inicio</h2>
</div>
<form method="POST" action="V2formModificarUsuario2(en obras).jsp">
<input name="updating" type="hidden" value="1"/>
<%if (!message.isEmpty()) {%>
<input name="message" type="text" style="width:400px" value="<%=message%>"/>
<%} else { %>
<br/><br/>
DNI:
<input name="DNI" type="text" style="width:200px" value="<jsp:getProperty property="DNI" name="usuario"/>" readonly=""/>
<br/><br/>
nombre:
<input name="nombre" type="text" style="width:200px" placeholder="<%=apellidoActualizar%>" value="<jsp:getProperty property="nombre" name="usuario"/>"/>
<br/><br/>
apellidos:
<input name="apellidos" type="text" style="width:200px" value="<jsp:getProperty property="apellidos" name="usuario"/>"/>
<br/><br/>
<input type="submit" value="Actualizar"/>
<%}%>
</form>
</div>
</div>
</body>
And finally, My DAO here.
public Usuario update(String DNI, String nombre, String apellidos) throws Exception {
if ((DNI == null) || (DNI.isEmpty())) {
throw new Exception("DNI must not be null");
}
if ((nombre == null) || (nombre.isEmpty())) {
throw new Exception("name must not be null");
}
if ((apellidos == null) || (apellidos.isEmpty())) {
throw new Exception("surname must not be null");
}
Usuario usuario = selectByDNI(DNI);
if (usuario == null) {
throw new Exception("user do not exist");
}
try (Connection connection = DBConnection.get()) {
if (connection == null) {
throw new Exception("Connection is null");
}
String query = "UPDATE usuario SET nombre=?, apellidos=? WHERE DNI=?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, nombre);
statement.setString(2, apellidos);
statement.setString(3, DNI);
statement.execute();
} catch (Exception ex) {
throw ex;
} finally {
DBConnection.close();
}
usuario = selectByDNI(DNI);
return usuario;
}
public Usuario selectByDNI(String DNI) throws Exception {
if ((DNI == null) || (DNI.isEmpty())) {
return null;
}
Usuario usuario = null;
try (Connection connection = DBConnection.get()) {
if (connection == null) {
throw new Exception("Connection is null");
}
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM usuario WHERE DNI = '" + DNI + "'");
if (rs.next()) {
usuario = new Usuario(rs.getString("DNI"), rs.getString("nombre"),
rs.getString("apellidos"), rs.getString("deAlta"));
}
} catch (Exception ex) {
throw ex;
} finally {
DBConnection.close();
}
return usuario;
}
I have resolved, the response was qualified as repeated, but i am not agree, my solution is different:
I have created 3 forms, the first one search the DNI, the second one create an user object and fill the camps in a form(with a placeholder and a value for each one), and the last one is where i have made the updating for the user.
The code here.
the second form in a jsp page
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%#page import="Entidades.Usuario"%>
<%#page import="DAO.DAOUsuario"%>
<%#page import="Conexion.DBConnection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario"></jsp:useBean>
<jsp:setProperty name="usuario" property="*"/>
<%
String message = "";
String nombreActualizar = "";
String apellidoActualizar = "";
try {
if ((usuario.getDNI() != null) && (!usuario.getDNI().isEmpty())) {
DAOUsuario dao = new DAOUsuario();
nombreActualizar = dao.selectByDNI(request.getParameter("DNI")).getNombre();
apellidoActualizar = dao.selectByDNI(request.getParameter("DNI")).getApellidos();
} else {
message = "El DNI de actualización no puede ser nulo.";
}
} catch (Exception ex) {
message = ex.getMessage();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSPformModificarUsuario2(en obras)</title>
<link href="../css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - USUARIO</h1>
<div id="menu">
<div id="opciones">
<h2>Menu inicial</h2>
<h2>Atras</h2>
</div>
<form method="POST" action="V2formModificarUsuario3(en obras).jsp">
<input name="updating" type="hidden" value="1"/>
<%if (!message.isEmpty()) {%>
<input name="message" type="text" style="width:400px" value="<%=message%>"/>
<%} else {%>
<br/><br/>
DNI:
<input name="DNI" type="text" style="width:200px" value="<jsp:getProperty property="DNI" name="usuario"/>" readonly=""/>
<br/><br/>
nombre:
<!-- <input name="nombre" type="text" style="width:200px" value="<<!--jsp:getProperty property="nombre" name="usuario"/>"/>-->
<input name="nombre" type="text" style="width:400px" placeholder="<%=nombreActualizar%>" value="<%=nombreActualizar%>"/>
<br/><br/>
apellidos:
<!--<input name="apellidos" type="text" style="width:200px" value="<<!--jsp:getProperty property="apellidos" name="usuario"/>"/>-->
<input name="apellidos" type="text" style="width:400px" placeholder="<%=apellidoActualizar%>" value="<%=apellidoActualizar%>"/>
<br/><br/>
<input type="submit" value="Actualizar"/>
<%}%>
</form>
</div>
</div>
</body>
The third form in a new one jsp page
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%#page import="Entidades.Usuario"%>
<%#page import="DAO.DAOUsuario"%>
<%#page import="Conexion.DBConnection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario"></jsp:useBean>
<jsp:setProperty name="usuario" property="*"/>
<%
String message = "";
DAOUsuario dao = new DAOUsuario();
String DNIActualizado="";
String nombreActualizado ="";
String apellidoActualizado = "";
if (
((request.getParameter("DNI") == null) || (request.getParameter("DNI").isEmpty()))
|| ((request.getParameter("nombre") == null) || (request.getParameter("nombre").isEmpty()))
|| ((request.getParameter("apellidos") == null) ||(request.getParameter("apellidos").isEmpty()))
) {
message = "Ningún campo del formulario debe estar vacio.";
}else{
DNIActualizado=request.getParameter("DNI");
nombreActualizado=request.getParameter("nombre");
apellidoActualizado=request.getParameter("apellidos");
usuario=dao.update(DNIActualizado, nombreActualizado, apellidoActualizado);
message = "usuario con DNI "+request.getParameter("DNI")+" actualizado";
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSPformModificarUsuario3(en obras)</title>
<link href="../css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - USUARIO</h1>
<div id="menu">
<div id="opciones">
<h2>Menu inicial</h2>
<h2>Atras</h2>
</div>
<form method="POST" action="V2formModificarUsuario3(en obras).jsp">
<input name="updating" type="hidden" value="1"/>
<%if (!message.isEmpty()) {%>
<input name="message" type="text" style="width:400px" value="<%=message%>"/>
<%} else {%>
<br/><br/>
DNI:
<input name="DNI" type="text" style="width:200px" value="<jsp:getProperty property="DNI" name="usuario"/>" readonly=""/>
<%}%>
</form>
</div>
</div>
</body>
Related
I have trouble with CSS in JSP pages.
CSS files are not loaded in any page.
I have this JSP page which is a registration form for a student.
I have a page works correctly but that page has no information from my database.
The rest of pages include some lines and some data from the database.
I really don't know where the problem is so I need your help :(
Student form :
<%#page import="java.util.List"%>
<%#page import="tables.Optionn"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="${pageContext.request.contextPath}">
<link href="Style/bootstrap.css" rel="stylesheet" type="text/css">
<link href="Style/font-awesome.css" rel="stylesheet" />
<link href="Style/style.css" rel="stylesheet">
<link href="Style/style-responsive.css" rel="stylesheet">
<% List<Optionn> option = (List<Optionn>) request.getAttribute("option_list");%>
<title>Etudiant</title>
</head>
<body>
<div class="container" id="registration_form">
<form method="post" class="form-login" action="//localhost:8086/GestionPfe/reg_etudiant">
<h2 class="form-login-heading" >ajouter un Etudiant!</h2>
<div class="login-wrap">
Option: <br> <select name="opt" class="form-control">
<%for (Optionn tempop : option) {%>
<option value=<%=tempop.getIdOption()%> > <%=tempop.getNomOption()%></option>
<%}%>
</select><br>
Nom: <br> <input name="nom_etudiant" type="text" class="form-control">
<br>
Prenomt: <br> <input name="prenom_etudiant" type="text" class="form-control">
<br>
Niveau: <br> <input name="niveau_etudiant" type="text" class="form-control">
<br>
Date De Naissance: <br><input name="date_naissance_etudiant" type="date" class="form-control">
<br>
Numero D'inscription: <br> <input name="num_inscription_etudiant" type="text" class="form-control">
<br>
Adresse: <br> <input name="adresse_etudiant" type="text" class="form-control">
<br>
Email: <br><input name="email_etudiant" type="email" class="form-control">
<br>
Mot De Pass: <br><input name="mot_de_pass_etudiant" type="password" class="form-control">
<br>
Telephone: <br><input name="telephone_etudiant" type="text" class="form-control">
<br>
<button type="submit" class="btn btn-theme btn-block"><i class="fa fa-lock"></i> SIGN IN</button>
</div>
</form>
</div>
</body>
</html>
Student Servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String op= request.getParameter("opt");
String nom_etudiant= request.getParameter("nom_etudiant");
String prenom_etudiant= request.getParameter("prenom_etudiant");
String niveau_etudiant= request.getParameter("niveau_etudiant");
String num_inscription_etudiant= request.getParameter("num_inscription_etudiant");
String date_naissance_etudiant= request.getParameter("date_naissance_etudiant");
String adresse_etudiant = request.getParameter("adresse_etudiant");
String email_etudiant = request.getParameter("email_etudiant");
String mot_de_pass_etudiant = request.getParameter("mot_de_pass_etudiant");
String telephone_etudiant = request.getParameter("telephone_etudiant");
try {
int idop=Integer.parseInt(op);
int tel=Integer.parseInt(telephone_etudiant);
SimpleDateFormat simpledate=new SimpleDateFormat("yyy-MM-dd");
Date birthdayDate = simpledate.parse(date_naissance_etudiant);
Optionn opt = new Optionn();
opt = (Optionn) session.get(Optionn.class,idop);
Etudiant etudiant=new Etudiant(opt,nom_etudiant,prenom_etudiant,niveau_etudiant, mot_de_pass_etudiant,num_inscription_etudiant,birthdayDate,adresse_etudiant,email_etudiant,tel);
session.save(etudiant);
session.getTransaction().commit();
session.close();
response.sendRedirect("Jsp/home.jsp");
} catch (ParseException ex) {
Logger.getLogger(reg_agent.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Add ".." to all your path,
<link href="../Style/style.css" rel="stylesheet">
Try this :
try {
int idop=Integer.parseInt(op);
int tel=Integer.parseInt(telephone_etudiant);
SimpleDateFormat simpledate=new SimpleDateFormat("yyy-MM-dd");
Date birthdayDate = simpledate.parse(date_naissance_etudiant);
Optionn opt = new Optionn();
opt = (Optionn) session.get(Optionn.class,idop);
Etudiant etudiant=new Etudiant(opt,nom_etudiant,prenom_etudiant,niveau_etudiant, mot_de_pass_etudiant,num_inscription_etudiant,birthdayDate,adresse_etudiant,email_etudiant,tel);
session.save(etudiant);
session.getTransaction().commit();
session.close();
RequestDispatcher dispatcher = request.getRequestDispatcher("Jsp/home.jsp");
dispatcher.forward(request, response);
} catch (ParseException ex) {
Logger.getLogger(reg_agent.class.getName()).log(Level.SEVERE, null, ex);
}
I am new to jsp. I am trying to insert data into the table through a jsp page. My code is running fine all the values are correctly passing to the statement. But, after the last value it should move to the executeUpdate command but it moved to the return command instead which returns 0 and data does not inserted into the database. My code is here.
RegisterDao.java
package RegBean;
import java.sql.*;
/**
*
* #author syedahmed
*/
public class RegisterDao {
public static int register(user u){
int status = 0;
try{
Connection con = ConnectionProvider.getCon();
PreparedStatement ps = con.prepareStatement("insert into register(uname,ulogin,upass,Gender,ucontact,Email) values(?,?,?,?,'',?)");
ps.setString(1,u.getUname());
ps.setString(2,u.getUlogin());
ps.setString(3,u.getUpass());
ps.setString(4,u.getGender());
ps.setString(5,u.getUcontact());
ps.setString(6,u.getEmail());
status=ps.executeUpdate();
}catch(Exception e){}
return status;
}
}
process.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import = "RegBean.RegisterDao"%>
<jsp:useBean id="obj" class="RegBean.user"/>
<jsp:setProperty property="*" name="obj"/>
<%
int status = RegisterDao.register(obj);
if(status>0)
out.print("You are successfully Logged in");
else
out.print("unsuccessful");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<form action="process.jsp">
<input type="text" name="uname" value="Name..." onclick="this.value=''"/><br/>
<input type="text" name="ulogin" value="Login ID..." onclick="this.value=''"/><br/>
<input type="password" name="upass" value="Password..." onclick="this.value=''"/><br/>
<input type="radio" name="gender" value="Male"> Male<br>
<input type="radio" name="gender" value="Female"> Female<br>
<input type="radio" name="gender" value="Other"> Other<br>
<input type="text" name="ucontact" value="Contact#..." onclick="this.value=''"/><br/>
<input type="email" name="email" value="email..." onclick="this.value= ''"/><br/>
<input type="submit" value="register"/>
</form>
</html>
It's mean that you code executed in the try section failed. Display the stacktrace in the catch section to see errors.
try{
...
}catch(Exception e){
e.printStackTrace()
}
problem has been resolved.. there was a mistake in the query..
"insert into register(uname,ulogin,upass,Gender,ucontact,Email) values(?,?,?,?,'',?)" ..
I know it is a simple task but don't able to find out what is the problem.
I made one login.jsp which is starting page.
LoginAction.jsp which will validate the user
I think there is some problem with ReqestDispatcher.
I am trying to find out solution from past 2 days and I am exhausted please help me.
All the table names and their field names are correct.
This is LoginAction.jsp
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="DataBase.DBCONNEction"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.Connection"%>
<%#page import="javax.servlet.RequestDispatcher"%>
<%#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 uname = request.getParameter("name");
String pass = request.getParameter("pass");
String unam, upass;
Connection con = null;
PreparedStatement prst = null;
Statement stm = null;
DBCONNEction DBC = null;
con = DBC.getConnection();
stm = con.createStatement();
RequestDispatcher rd = request.getRequestDispatcher("/welcome.jsp");
ResultSet rs = stm.executeQuery("select password from details where username = '" + uname + "'");
if (rs.next()) {
if (rs.getString("password").equals(pass)) { //If valid password
session.setAttribute("User", uname);
}else {
request.setAttribute("Error", "Invalid password.");
rd = request.getRequestDispatcher("/login.jsp");
}
}
else {
request.setAttribute("Error", "Invalid user name.");
rd = request.getRequestDispatcher("/login.jsp");
}
rd.forward(request, response);
%>
</body>
</html>
This is login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Knowledge Repository System</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="header">
<h1>Knowledge Repository System JSP</h1>
<form id="search" action="loginAction.jsp" method="POST">
<label>Username <input type="text" name="name" id="s-user" style="width:90%;" required></label>
<label>Password<input type="password" name="pass" id="s-pass" style="width:90%;" required></label>
<input type="submit" class="submit" value="Submit">
</form>
</div>
Admin Panel
<div class="nav">
<h2 style="font-size: 36px"><strong>Sign Up</strong></h2>
<form action="details" method="POST">
<signup>
<p><input type="text" name="name" required placeholder="Username"></p>
<p><input type="password" name="pass" required placeholder="password"></p>
<p><input type="text" name="email" required placeholder="xyz#abc.com"></p>
<p><input type="submit" value="Sign Up" align="center"></p>
</signup>
</form>
</div>
</body>
</html>
This is DBCONNEction.java
package DataBase;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBCONNEction {
private static String URL = "jdbc:mysql://localhost:3306/repository";
private static String DRIVER = "com.mysql.jdbc.Driver";
private static String pass = "myserver";
private static String user = "root";
static Connection con = null;
static {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
return con;
}
}
I am using org.apache.commons.*, org.apache.commons.disk.*, org.apache.commons.fileupload.servlet.* packages for file uploading in JSP program and there was no need of Struts and it was working great, data easily worked with this, but when I added Struts 2 core libraries into my web project using MyEclipse 8.5 it is not working and have no fields found. May be the program is with upload.parseRequest.
Frankly, I am unable to understand the problem, so I share my program too
AddCategory.jsp:
<html>
<head>
<meta http-equiv="refresh" content="30">
</head>
<script type="text/javascript">
function blank() {
if (document.cate.cat.value == "Enter New Category") {
alert(" Category must not be blanked !!!");
document.cate.cat.focus();
return false;
}
else if (!document.getElementById("file1").value) {
alert("No file selected");
return false;
}
else {
return true;
}
}
</script>
<form name="cate" action="CategoryAdded.jsp" method="post" enctype="multipart/form-data" onsubmit="return blank()">
<table width="100%" border="0">
<tr>
<th colspan="2" scope="col">
<div align="center">Create New Category</div>
</th>
</tr>
<tr>
<td width="50%">
<div align="right">Enter New Category:</div>
</td>
<td width="50%">
<input name="cat" type="text" id="cat" value="Enter New Category"
onFocus="if(this.value== 'Enter New Category'){ this.value='' ; this.style.background='white';}"
onBlur="if(this.value==''){this.value='Enter New Category'; this.style.background='lightyellow'}">
</td>
</tr>
<tr>
<td width="50%">
<div align="right">Upload photo:</div>
</td>
<td width="50%"><input name="file1" type="file" id="file1"></td>
</tr>
<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="Add Category">
</div>
</td>
</tr>
</table>
</form>
</html>
CategoryAdded.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%#page import="java.io.*" %>
<%# page language="java" errorPage="" %>
<%# page import="java.sql.*" %>
<%# page import="org.apache.commons.io.*" %>
<%#page import="java.util.Iterator,java.util.List" %>
<%#page import="org.apache.commons.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.*" %>
<%# page import="java.util.*" %>
<%#page import="org.apache.commons.fileupload.FileItemFactory" %>
<%#page import="org.apache.commons.fileupload.FileItem" %>
<%#page import="org.apache.commons.fileupload.FileUploadException" %>
<%#page import="p1.DBInfo" %>
<%#page import="p1.Identy" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<%
String pname = "";
Identy id = new Identy();
String cod = id.code();
boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
if (!isMultipartContent) {
System.out.println("No multipart found");
return;
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
System.out.println("No fields found");
return;
}
DBInfo obj = new DBInfo();
Connection cn = obj.getConn();
PreparedStatement ps = cn.prepareStatement("insert into category values(?,?,?)");
while (it.hasNext()) {
FileItem fileItem = it.next();
if (fileItem.getFieldName().equals("cat")) {
pname = fileItem.getString();
System.out.println("category name is " + pname);
}
boolean isFormField = fileItem.isFormField();
if (!isFormField) {
String s = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\") + 1);
fileItem.write(new File("D:\\Practice\\ShoppingCart\\WebRoot\\images\\" + s));
System.out.println(s);
fileItem.getOutputStream().close();
ps.setString(3, "D:\\Practice\\ShoppingCart\\WebRoot\\images\\" + s);
}
}
ps.setString(1, pname);
ps.setString(2, pname + cod);
int i = ps.executeUpdate();
if (i == 1) {
%>
<head>
<script type="text/javascript">
function myFunction() {
var r = confirm("New Category Added Successfully!!!\nIf you Want to Add more New Category then Press Ok!!!");
if (r == true) {
window.location = "AddCategory.jsp";
}
else {
window.location = "Tryy.jsp";
}
}
</script>
</head>
<body onload="myFunction()">
</body>
<%
}
cn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</html>
The best thing is to rewrite the JSPs to remove scriptlets and move business logic to the action classes.
You could also use Struts2 <s:if> and <s:else> tags to render content conditionally.
The commons-fileUpload is the default implementation for uploading files in Struts2, to use it correctly you could run an example Struts2 project like struts-2-upload-multiple-files-example.
Objective: If I type an email id, in the html form it has to send the request to jsp where it does the logic and has to print(in the html form) whether the email is available or not. I have the following code. Please do help me which part I am doing wrong.
CreateAccount.html
<!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">
<script type="text/javascript" src="emailStore.js"></script>
</head>
<body onload="process()">
<form name="login">
<table align="center">
<tr>
<td>Email*</td>
<td><input type="text" name="userinput" id="userinput"/></td>
<td><div id = "underInput"></div></td>
</tr>
<tr>
<td>Password*</td>
<td><input type="password" name="pswrd" /></td>
</tr>
<tr>
<td>Repeat Password*</td>
<td><input type="password" name="pswrd1" /></td>
</tr>
<tr>
<td>First Name*</td>
<td><input type="text" name="userid" /></td>
</tr>
<tr>
<td>Last Name*</td>
<td><input type="text" name="userid" /></td>
</tr>
<tr>
<td>Phone Number</td>
<td><input type="text" name="userid" /></td>
</tr>
</table>
<div style="text-align: center">
<input type="submit" value="Create Account"/>
</div>
</form>
</body>
</html>
The ajax part in a javascript file. emailStore.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequest()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new ActiveXObject();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert("can't create that object");
}
else
{
return xmlHttp;
}
}
function process()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
email = encodeURIComponent(document.getElementById("userinput").value);
xmlHttp.open("GET", "emailStore.jsp?email=" + email, true);
xml.onreadystatechange = handle.ServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = '<span style = "color:blue">' + message + '</span>';
setTimeout('process()',1000);
}
else
{
alert('Something went Wrong');
}
}
}
And the logic part in a jsp file- emailStore.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList"%>
<!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>
<%
String email = request.getParameter("userinput");
ArrayList<String> emails = new ArrayList<String>();
emails.add("something#gmail.com");
if (emails.contains(email)) {
out.println("Email already taken!");
} else {
out.println("Email available");
}
%>
</body>
</html>
I would advise you of the following:
Use library JQuery;
Use Servlet instead of the JSP;
Keep a list in the session;
Do not use a tabular layout. Instead, use div- layers, and cascading style sheets.
Here is a simple example, front- end part is ..
<head>
...
<script>
$(document).ready(function() {
$('#submit').click(function(event) {
var input=$('#userinput').val();
$.get('ActionServlet',{userinput:input},function(responseText) {
$('#underInput').text(responseText);
});
});
});
</script>
...
</head>
<body>
...
<form id="form1">
...
Email
<input type="text" id="userinput"/>
<input type="button" id="submit" value="Submit"/>
<br/>
<div id="underInput">
</div>
...
</form>
...
</body>
</html>
..and server side -
...
public class ActionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ActionServlet() {
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String answer = "Something went Wrong";
String userinput = request.getParameter("userinput").toString();
HttpSession httpSession = request.getSession(true);
if(httpSession.isNew()) {
httpSession.setAttribute("sessionVar", new ArrayList<String>());
}
List<String> arrayList = (ArrayList<String>)httpSession.getAttribute("sessionVar");
if(userinput != null && !userinput.equals("")) {
if(arrayList.contains(userinput)) {
answer = "Email already taken!";
} else {
arrayList.add(userinput);
answer = "Email available";
}
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(answer);
}
...