code is not reading executeUpdate() - java

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(?,?,?,?,'',?)" ..

Related

Error 404 : css page can't load in JSP

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);
}

How to get values from array in jsp

I want to show the data from an array using JSP.
I have three files:
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>
<h1>Hello World! </h1>
<form name="Input Name Form" action="response.jsp"/>
<p> Enter your name:</p>
<input type="text" name="name"/>
<input type="submit" value="ok" />
</form>
</body>
</html>
response.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>
<h1>Hello World!</h1> <br>
<jsp:useBean id="aaa" scope="page" class="A.a" />
<jsp:setProperty name="aaa" property="name" value="<%= request.getParameter("name")%>" />
<jsp:getProperty name="aaa" property="name" />
</body>
</html>
a.java:
public class a {
public a ()
{}
private String name;
ArrayList() array_list = new ArrayList();
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
//some magic to fill array_list with values
}
}
My question is:
What statement should I use in jsp to get values from array_list in a.java?
I know that there is statement
<c:forEach> </c:forEach>
but I am not sure how to use it.
<c:forEach items="${dataDetail}" var="data" varStatus="item">
<c:out value="${data.id}"/>
</c:forEach>
Here "dataDetail" is name of the key where you have set your list in controller.
(session or request ).setAttribute("dataDetail",---List of Data of type Class Data---);
Above code is similar to
for(Data data : dataDetail){
System.out.println(data.getId());
}
A similar question has been asked here: Iterate ArrayList in JSP
Long story short:
<c:forEach items="${aaa.array_list}" var="item">
${item}
</c:forEach>
use JSTL.
Try this out:
Have this at top of your JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
And code for displaying data
<c:forEach begin="0" end="${fn:length(array_list) - 1}" var="index">
<tr>
<td><c:out value="${array_list[index]}"/></td>
</tr>
</c:forEach>

problems writing code to database html

Im trying to write information to a database just using jsp pages but I keep running into this error;
information storage was unsuccessful java.sql.SQLException: Must specify port after ':' in connection string
This is the code that I have;
<%#page import="java.sql.*" %>
<%#page import="java.util.Date" %>
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Player Register</title>
<link rel='stylesheet' href= 'styles.css'>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2 align="center"> Register</h2>
<form class="my_form" action="playerDisplay.jsp" method="POST">
<fieldset>
<legend>Please Enter Your Details</legend>
<h1 class="h1a">New Player</h1>
<p>
<label class="labela" for="login">Name:</label>
<input type="text" name="Name" id="Name" value="Name"required>
</p>
<p>
<label class="labela" for="login">Surname:</label>
<input type="text" name="Surname" id="Surname" value="Surname"required>
</p>
<p>
<label class="labela" for="login">PPS Number:</label>
<input type="text" name="PPS_Number" id="PPS_Number" value="PPS_Number"required>
</p>
<p>
<label class="labela" for="login">Grade:</label>
<input type="text" name="Grade" id="Grade" value="Grade"required>
</p>
<p>
<label class="labela" for="login">Email:</label>
<input type="text" name="Email" id="Email" value="Email"required>
</p>
<p>
<label class="labela" for="password">Password:</label>
<input type="password" name="password" id="Password" value="123456"required>
</p>
<p>
<input type="checkbox" name="mailingList" value="yes">Yes, add me to your mailing list<br>
</p>
<div style="text-align: center">
<input type="submit" name="submit">
<input type="reset" name="reset">
</div>
</fieldset>
</form>
</body>
</html>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="CSS/styles.css" rel="stylesheet" type="text/css"/>
<script src="js/libs/jquery/jquery.js"></script>
<style>
table, td, th {
border: 1px solid black;
}
td {
padding: 15px;
}
#optionalFieldset {
display: none;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Your Space</title>
<link rel='stylesheet' href= 'styles.css'>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
$(document).ready(function () {
$("#optionalCheck").click(function () {
$("#optionalFieldset").slideToggle("slow");
});
});
</script>
</head>
<body>
<fieldset>
<legend>Your Info</legend>
<%
String Name=request.getParameter("Name");
String Surname=request.getParameter("Surname");
String PPS_Number=request.getParameter("PPS_Number");
String Grade=request.getParameter("Grade");
String Email=request.getParameter("Email");
String Password=request.getParameter("Password");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn=DriverManager.getConnection("jdbc:mysql://http://danu6.it.nuigalway.ie:3306/mydb1899/players", "mydb1899a", "mydb1899a");
PreparedStatement ps = conn.prepareStatement("INSERT INTO players(Name,Surname,PPS_Number,Grade,Email,Password) VALUES(?,?,?,?,?,?)");
ps.setString(1,Name);
ps.setString(2,Surname);
ps.setString(3,PPS_Number);
ps.setString(4,Grade);
ps.setString(5,Email);
ps.setString(6,Password);
ps.executeUpdate();
out.println("Your information was successfully stored in our database");
conn.close();
ps.close();
}
catch(Exception e) {
out.println("information storage was unsuccessful " + e);
}
%>
</fieldset>
Home
</body>
</html>
Is there any way that I can do it this way and if so is there a solution to the error I have?
I think you do not want the http:// in there, for a proper URL you would want either MySQL:// -OR- http:// not both.
I am guessing your proper string is going to be :
jdbc:mysql://danu6.it.nuigalway.ie:3306/mydb1899/players
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
That is the format for connection URLs. Does yours work with that?

problems taking the value of the select option jsp

I need to take the value of the select option to send it to another page to be processed, but can not capture the value.
any ideas?
the select is loaded from the database, that part works, shows the categories of product.
<%#page import="com.sun.xml.internal.txw2.Document"%>
<%#page import="java.util.ArrayList"%>
<%# page import = "com.seminario.beans.categoria" %>
<%# page import = "com.seminario.datos.DbCategoria" %>
<%# page import = "com.seminario.beans.Producto" %>
<%# page import = "com.seminario.datos.DbProducto" %>
<jsp:useBean id="dataProd" class="com.seminario.datos.DbProducto" scope="page"/>
<jsp:setProperty name="dataProd" property="*"/>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="../stylo.css" rel="stylesheet" type="text/css" media="screen" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Alta Producto</title>
</head>
<%
categoria c = new categoria();
DbCategoria bdc = new DbCategoria();
ArrayList <categoria> myList = new ArrayList();
myList = bdc.SelectAll();
%>
<body>
<h1>Nuevo Producto</h1>
<form name ='formulario' action='nuevoProducto.jsp' method='post' >
Descripcion<input name='descripcion' type='text' size='20' required><br>
Precio<input name='precio' type='text' size='20' required><br>
Stock<input name='stock' type='text' size='20' required><br>
**Categoria <select name="categoid" id="categoid">
<% for(int i=0;i<myList.size();i++){%>
<option value="<%= myList.get(i).getId() %>" > <%out.print(myList.get(i).getDescripcion());%></option>
<%}%>
</select><br>**
Imagen<input name="imagen" text="seleccionar archivo" type="file" size="10" accept="image/jpg" /><br>
<input type ="submit" value ='Guardar' />
<!-- <input type="submit" value="guardar">-->
</form>
<br><br><a href='menuAdmin.jsp'>Volver al menu principal</a>
</body>
</html>

How to increment the value of request.getParameter?

I'm trying to make an quiz and my query is ORDER BY RAND() so it means it will be random... My JSP send it to servlet to handle the flow but I'm having a problem, I have stored 4 questions with choices (answer) in the database and in my code below I retreive it. Problem is, when I retrieve the answer of the examinee the only retrieved data is the first answer... See my servlet
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<%#page import="database.Connect" %>
<%
Connect conn = new Connect();
Statement stmt = conn.getDataConn().createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from quiz WHERE category = 'secondary' ORDER BY RAND()");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../../css&js/des.css">
<script src="css&js/modernizr.custom.js"></script>
<title>Question 1</title>
</head>
<body>
<img alt="" src="../../pics/bgimg2.jpg" id="bgimg" />
<div class="md-modal md-effect-1 md-show" id="modal-1">
<form action="../../Check" method="POST">
<table border="1" class="c-form md-content">
<% while(rs.next()){
%>
<tr>
<td><h1><%=rs.getString("question")%>?</h1></td>
<td><select name="answer">
<option value="<%=rs.getString("choice1")%>"><%=rs.getString("choice1")%></option>
<option value="<%=rs.getString("choice2")%>"><%=rs.getString("choice2")%></option>
<input type="hidden" name="correct" value="<%=rs.getString("correct")%>"/>
</select></td>
</tr>
<%}
%>
<tr>
<td align="center" colspan="2"><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
</div>
</body>
I'm trying to make an quiz and my query is ORDER BY RAND() so it means it will be random... My JSP send it to servlet to handle the flow but I'm having a problem, I have stored 4 questions with choices (answer) in the database and in my code below I retreive it. Problem is, when I retrieve the answer of the examinee the only retrieved data is the first answer... See my servlet
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<%#page import="database.Connect" %>
<%
Connect conn = new Connect();
Statement stmt = conn.getDataConn().createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from quiz WHERE category = 'secondary' ORDER BY RAND()");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../../css&js/des.css">
<script src="css&js/modernizr.custom.js"></script>
<title>Question 1</title>
</head>
<body>
<img alt="" src="../../pics/bgimg2.jpg" id="bgimg" />
<div class="md-modal md-effect-1 md-show" id="modal-1">
<form action="../../Check" method="POST">
<table border="1" class="c-form md-content">
<% while(rs.next()){
%>
<tr>
<td><h1><%=rs.getString("question")%>?</h1></td>
<td><select name="answer">
<option value="<%=rs.getString("choice1")%>"><%=rs.getString("choice1")%></option>
<option value="<%=rs.getString("choice2")%>"><%=rs.getString("choice2")%></option>
<input type="hidden" name="correct" value="<%=rs.getString("correct")%>"/>
</select></td>
</tr>
<%}
%>
<tr>
<td align="center" colspan="2"><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
</div>
</body>
Servlet... Im just trying to experiment here but I really need help.. The output is null for the for and past code are also fail because the 1st answer is the olnly retrieve and I need to increment it. Please help
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Check extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
for(int i=0;i<10;i++) {
String Answer = request.getParameter("answer" + i);
System.out.println(Answer);
}
String Answer = request.getParameter("answer");
String Correct = request.getParameter("correct");
int score = 0;
if (Answer.equals(Correct)) {
score++;
}
System.out.println(score);
}
}
It is may be because you select tags has the same name for every question:
<select name="answer">
I think it should unique

Categories

Resources