I'm trying to make a list of members of type Party, and linking their memberID to an update page which automatically gets the memberID of the one which was clicked.
I've already written code in the servlet to display a view of all of the members, with each of their IDs linked to a page called UpdateParty.jsp however what I want is for the ID clicked to be passed on with the request so that it can be used in the UpdateParty.jsp as a parameter so that the user does not have to enter it.
I'm using postgres for my SQL if anyone wants to know.
Servlet code which produces a list of all party members:
else if (request.getParameter("listallmembers") != null) {
try {
User sessionuser = (User) session.getAttribute("User");
String u = sessionuser.getUsername();
ArrayList<Party> p = new ArrayList<Party>();
ResultSet rs = this.findAllMembers(u);
while (rs.next()) {
Party party = new Party();
party.setMemberID(rs.getString("memberID"));
party.setPartyFirstname(rs.getString("partyFirstname"));
party.setPartySurname(rs.getString("partySurname"));
party.setUsername(rs.getString("username"));
p.add(party);
}
request.setAttribute("members", p);
request.getRequestDispatcher("ViewPartyMembers.jsp").forward(request, response);
} catch (Exception e) {
out.print(e);
e.printStackTrace(out);
}
Code for ViewPartyMembers.jsp:
<%#page import="HolidayExchange.Party"%>
<%#page import="HolidayExchange.User"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<%
List<Party> l = (List<Party>) request.getAttribute("members");
if(l!=null){
out.println("<table>");
out.println("<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>");
for(int i = 0; i < l.size();i++){
out.println("<tr><td>"+ l.get(i).getMemberID() +
"</td><td><a href='UpdateParty.jsp'>"+ l.get(i).getPartyFirstname() +
"</a></td><td>"+ l.get(i).getPartySurname() +
"</td><td>" + l.get(i).getUsername() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}else{
%>
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
<%
}
%>
</body>
</html>
Here's something a little more sane for you. It uses the JSTL Expression Language and tag library.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<c:if test="${!empty members}">
<table>
<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>
<c:forEach items="${members}" var="member">
<tr><td>${member.memberID}</td>
<c:url value="link" value="UpdateParty.jsp">
<c:param name="memberId" value="${member.memberID}"/>
</c:url>
<td>${member.partyFirstname}</td>
<td>${member.partySurname}</td>
<td>${member.username}</td>
</tr>
</c:forEach>
</table>
</c:if>
<c:if test="${empty members}">
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
</c:if>
</body>
</html>
If you want the ID to be available on the UpdateParty.jsp your link should look like:
<a href='UpdateParty.jsp?id=" + l.get(i).getMemberID() + "'>"+ l.get(i).getPartyFirstname()"</a>
So the id property will be available in the JSP as a request parameter.
Anyway, I recommend you not use scriptlet in your JSP and instead point directly to a JSP point to a Controler/Action
Related
I have an issue with formatting the date.
In my addstudent.jsp file I am asking user ti enter their date of birth. This I am doing using input type="text".Add the format to enter is dd-mm-yyyy. Now I have to store the date in yyyy-mm-dd format as mysql stores in yyyy-mm-dd format.
I did this in addprocess.jsp file. But something is wrong which I do not understand. When I give 08-05-2009 as input, I am getting 2009-01-08
as output to store in mysql database. What am I doing wrong?
This is my addstudent.jsp file.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Adding Student</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function validateform(){
var errorString="";
var name=document.myform.name.value;
var email=document.myform.email.value;
var parentemail=document.myform.parentemail.value;
if (name==null || name=="" || !(/^[A-Za-z\s]+$/.test(name))){
document.getElementById("error").innerHTML=errorString+"Name can have only alphabets and spaces";
return false;
}
function validateEmail(email){
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)| (".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
if(!validateEmail(email)){
document.getElementById("error").innerHTML=errorString+" Your email is not valid";
return false;
}
if(!validateEmail(parentemail)){
document.getElementById("error").innerHTML=errorString+" Your parent's email is not valid";
return false;
}
}
</script>
</head>
<body>
<div id="outer">
<%#include file="header.jsp" %>
<%# page import="java.util.*"%>
<%# page import="java.util.regex.*"%>
<%#page import="java.sql.*"%>
<div id="error"></div>
<div id="main">
<div id="box">
<form name="myform" method="post" action="addprocess.jsp" onsubmit="return validateform();">
<table>
<tr><td style="color:navy;"><B> Login Form</B></td> </tr>
<tr><td><br></td></tr>
<tr><td>User Name:</td><td><input type="text" name="name" placeholder="Enter your name"/></td></tr>
<tr><td><br></td></tr>
<tr><td>Email Id:</td><td><input type="text" name="email" placeholder="Enter Email ID"/></td></tr>
<tr><td><br></td></tr>
<tr><td>Parent Email Id:</td><td><input type="text" name="parentemail" placeholder="Enter Parent's Email ID"/></td></tr>
<tr><td><br></td></tr>
<tr><td>Date Of Birth:</td><td><input type="text" name="dateofbirth" placeholder="dd-mm-yyyy"/></td></tr>
<tr><td><br></td></tr>
<tr><td>Address:</td><td><input type="text" name="address" placeholder="Enter your address"/></td></tr>
<tr><td><br></td></tr>
<tr><td> </td><td><input type="submit" value="Sign in"></td></tr>
</table>
</form>
<br>
</div>
</div>
</div>
</body>
</html>
And this is addprocess.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<%# page import="java.util.*"%>
<%# page import="java.util.regex.*"%>
<%#page import="java.sql.*"%>
<%#page import="java.text.ParseException"%>
<%#page import="java.text.SimpleDateFormat"%>
<%#page import="java.text.DateFormat"%>
<%#page import="java.util.Date"%>
%>
<%
String name=request.getParameter("name");
String email=request.getParameter("email");
String parentemail=request.getParameter("parentemail");
SimpleDateFormat format = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date util_Date = format.parse( request.getParameter("dateofbirth") );
java.sql.Date dateOfBirth = new java.sql.Date( util_Date.getTime() );
System.out.println(dateOfBirth);
String address=request.getParameter("address");
%>
</body>
</html>
Thanks in advance.
"mm" in date formatting is minute; "MM" in date formatting is month.
i am working on java application where user's login and predict football matches , i create an admin jsp to get all teams name from stored table in database to set this week matches and set the final results later when the matches finish to compare them with users results and calculate points , top users etc ...
my admin.jsp where i choose matches team from jstl foreach loop and set the final result later to compare them with user prediction results.
<%#page import="pws.daoImp.UsersDaoImp"%>
<%#page import="java.lang.String"%>
<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
<%#page import="pws.beans.Users"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<% request.getAttribute("admminresult");
%>
<%
List<String> teams1 = new ArrayList();
UsersDaoImp udi = new UsersDaoImp();
List<String> admminresult = new ArrayList();
admminresult = udi.getadminresult();
request.setAttribute("admminresult", admminresult);
List<String> teams = new ArrayList();
teams = udi.getallteams();
request.setAttribute("teams", teams);
%>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Match Prediction</title>
</head>
<body>
<div>
<h1 class="title">Welcome to Match Prediction Site </h1>
<div id="logo" >
<img src="images/cl.png" alt="Smiley face" width="142" height="142">
</div>
</div>
<form action ="AdminUserHandling" method = "post" >
<div class="form-lables">
<h1><select name="clteam1" >
<c:forEach items="${teams}" var="teams" >
<option name="clm1g1" value="${teams}">
${teams}
</option>
</c:forEach>
</select> Vs <select name="clteam1" >
<c:forEach items="${teams}" var="teams" >
<option name="clm1g1" value="${teams}">
${teams}
</option>
</c:forEach>
</select> </h1>
<label for="user_lic">Goals : </label><input id="user_lic" name="clm1g1" type="number" min="" max="10" step="1" value ="1"/>
<label for="user_lic">Goals : </label><input id="user_lic" name="clm1g2" type="number" min="" max="10" step="1" value ="1"/>
</div>
<input type ="submit" value="Submit" />
</form>
</body>
</html>
and my servlet code
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UsersDaoImp udi = new UsersDaoImp();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String team1 = request.getParameter("clteam1");
String team2 = request.getParameter("clteam2");
String team1gl = request.getParameter("clteam1gl");
String team2gl = request.getParameter("clteam2gl");
Users user = (Users) request.getSession().getAttribute("user");
System.out.println(team1);
System.out.println(team2);
udi.adminhandling(team1, team2,team1gl,team2gl); //save teams name and goals in database
processRequest(request, response);
}
}
my question is that i set the teams name and final result in admin page jsp but have problem to pass them to users jsp dynamically , iam running out of ideas to do so any help would be much appreciated.
You can use RequestDispatcher.
Defines an object that receives requests from the client and sends
them to any resource (such as a servlet, HTML file, or JSP file) on
the server. The servlet container creates the RequestDispatcher
object, which is used as a wrapper around a server resource located at
a particular path or given by a particular name.
RequestDispatcher rd = request.getRequestDispatcher("/path/to/your/users.jsp"); // mention correct path to your user.jsp here
request.setAttribute("teams",teams);
rd.forward(request, response);
Or
You can set the object into Session.
HttpSession session = request.getSession(false);
session.setAttribute("teams",teams);
I wish to create a simple script to store information dynamically without refreshing or redirecting to another page. I've sourced high and low for answers before coming here, and I followed this.
However, I'm still unable to get it to store data because I don't know where I've goen wrong. Also, I wish to ask the purpose of success: function(msg)
Thanks a lot!
Update 1: Got it to work after following Anoop's solutions. However, such a popup appears when the data is submitted
StaffReg.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Staff Registration</title>
</head>
<body>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Javascript --%>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Register').click(function(e) {
e.preventDefault();
$.ajax({
url: "StaffRegAuth.jsp",
type: "post",
data: {
username: $('#username').val(),
password: $('#password').val(),
userGroup: $('#userGroup').val()
},
success: function(msg) {
alert(msg);
}
});
});
});
</script>
<%-- Main body --%>
<h1 align="center"> Account Registration: </h1>
<div align="center">
<table style="width = 30%" >
<tr>
<td> User Name: </td>
<td><input type="text" id="username"></td>
</tr>
<tr>
<td> Password: </td>
<td><input type="password" id="password"></td>
</tr>
<tr>
<tr>
<td> User Group: </td>
<td><select name = "userGroup" id="userGroup">
<option value="1">Administrator
</optin>
<option value="2">Clerk
</optin>
<option value="3">Operations
</optin>
<option value="4">Sales
</optin>
</select></td>
</tr>
<tr>
</table>
<input type="submit" value="Register" id="Register">
</div>
</body>
</html>
StaffRegAuth.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%-- Imports --%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%#page import="javax.servlet.*" %>
<%#page import="javax.servlet.http.*" %>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Variables that will be written --%>
<% String sUsername = request.getParameter("username");
String sPassword = request.getParameter("password");
int sUserGroup = Integer.parseInt(request.getParameter("userGroup"));
%>
<%-- Creating new staff account - writing --%>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conURL= "jdbc:odbc:HOD_DATA";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
int status = st.executeUpdate("insert into Staff(username, password, user_group) values('"+sUsername+"','"+sPassword+"',"+sUserGroup+")");
if(status>0){
//out.println("Update sucessful");
}
else{
//out.println("Update unsuccessful");
}
st.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
</body>
</html>
Remove the submit button and use a normal html button with Id as Register.
Modify your html input types and replace the name attribute with id attribute. Ex: use id="username" instead of name="username"
Debugging:
Use firebug to check what value is passed to server. Ensure the correct ajax request is submitted.
Hope it helps.
This is my jsp page
<%#page import="java.util.List"%>
<%#page import="org.hibernate.cfg.Configuration"%>
<%#page import="org.hibernate.Session"%>
<%#page import="org.hibernate.SessionFactory"%>
<%#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>
<script>
function page_hide_show()
{
for(var i=8;i<22;i++)
{alert(i)
document.getElementsByClassName(i).style.display='none';
}
}
</script>
</head>
<body onload="page_hide_show()">
<%
SessionFactory sessionfactory=null;
Session Listsession=null ;
sessionfactory=new Configuration().configure().buildSessionFactory();
Listsession = sessionfactory.openSession();
String name="";
String age="";
String address="";
String phone_no="";
try
{
int c=0;
if(request.getAttribute("c")!=null)
{
c=Integer.parseInt(request.getAttribute("c").toString());
}
org.hibernate.Query query=Listsession.createQuery("select name,age,address,phone_number from paging order by auto_inc");
query.setFirstResult(c);
query.setMaxResults(10);
List check1 =query.list();
java.util.Iterator on=check1.iterator();
while(on.hasNext())
{
Object oo[]=(Object[])on.next();
name=(String)oo[0].toString().trim();
age=(String)oo[1].toString().trim();
address=(String)oo[2].toString().trim();
phone_no=(String)oo[3].toString().trim();
%>
<div align="center" style="border-bottom:1px solid #ccc "> Name <input type="text" name="text" value="<%=name %> " disabled="disabled">
<br><br>
</div>
<% }
}
catch(Exception ee){
out.print(ee.getMessage());
}
%>
<center> <img src="fgfdg.png"> </center>
<table align="center">
<tr>
<!-- <td>First Page</td> -->
<%
int value_counter=0;
int pagecount=0;
long counters=0;
try{
org.hibernate.Query query=Listsession.createQuery("select count(*) from paging order by auto_inc");
List check1 =query.list();
java.util.Iterator on=check1.iterator();
while(on.hasNext())
{
Object oo=on.next();
counters=((Number)oo).longValue();
}}
catch(Exception e)
{
out.println(e);
}
int count=(int)counters/10;
int Counter_in_int=count*10;
double xyz=Counter_in_int-counters;
if(xyz>=0)
{
for(int i=0;i<count;i++)
{
pagecount++;
%>
<td class="<%=pagecount%>"><%= pagecount%></td>
<% value_counter=value_counter+10;} }
else
{
%>
<%
for(int i=0;i<=count;i++)
{
pagecount++;
%>
<td class="<%=pagecount%>"><a href="Pagecount?c=<%=value_counter %>" ><%= pagecount%></a></td>
<% value_counter=value_counter+10;} }
%>
<!-- <td>Last Page</td> -->
</tr>
</table>
</body>
</html>
So My question is
in the above code I am trying to hide td tags with classname from 8 to 21 but I am unable to do so.I think my javascript function is right.Also when I am giving id to as
< td id="<%=pagecount%>">
I am unable to do so.
kindly tell me how to hide the td's with classname from 8 to 21 in this code.Is my javascript function wrong.
Your problem is that document.getElementsByClassName(something) returns an Array (the plural in elements). That means that you have to have something like this :
var list = document.getElementsByClassName(class_name);
for (i = 0; i < list.length; i++) alert(list[i]);
However, I see you only have one of each class name. In this case, you should just do something like this : document.getElementsByClassName(i)[0].style.display = 'none'.
Hope this was useful :)
My project is StaffAllocation, and I want to retrieve information from the database. I'm very new and this is my very first project. I created a drop down list retrieving staffnames from one of my table. Now I want to perform a query action to view the details of the selected staffnames from the drop-down list. The following is the coding which i have, which is not correct:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%# page import="java.lang.*" %>
<%# page import="javax.servlet.*" %>
<%# page import="javax.servlet.http.*" %>
<%ResultSet resultset =null; %>
<!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>Staff Details</title>
</head>
<BODY>
<form method=post>
<h3>Select Stafftype:</h3>
<p><input type="radio" name="Stafftype" value="Male"> Male</input></p>
<p><input type="radio" name="Stafftype" value="Female"> Female</input></p>
<input type="submit" value="Submit">
</form>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/StaffAllocation? user=root&password=success");
Statement statement = connection.createStatement() ;
String Stafftype= request.getParameter("Stafftype");
out.print(Stafftype);
if(Stafftype.contentEquals("Male")){
resultset=statement.executeQuery("select * from tblstaffdetails where Stafftype= 'Male'");
}
else if(Stafftype.contentEquals("Female")){
resultset=statement.executeQuery("select * from tblstaffdetails where Stafftype= 'Female'");
}
else
{
System.out.println("your coding is wrong");
}
%>
<select> <% while(resultset.next()){ %>
<option><%= resultset.getString(2)%></option>
<%} %>
<%
String StaffName= request.getParameter("StaffName");
int staffId;
String subcode;
if(StaffName != null) {
resultset=statement.executeQuery("SELECT a.staffId, a.StaffName, b.subcode FROM tblstaffdetails a LEFT JOIN tblsubhandled b ON a.staffId = b.staffId where StaffName='request.getParameter('StaffName')'");
}
}
catch(Exception e)
{
out.println("wrong entry"+e);
}
%>
<form method = "get">
<br><br>
<input name="Submit" type="button" value="Submit">
</form>
</body>
</html>`
Tables:
tblstaffdetails -(1).staffId(2).StaffName(3).Stafftype(male or female)
tblsubhandled - (1).staffId(2).subcode
I have fiddled sample implementation for your reference. You can implement like that. All you need to do is include jQuery plugin. Sample code lke this,
$.ajax({
url : 'ur_servlet_url' + selValue,
type : "POST",
async : false,
success : function(data) {
//Sample data
var data = "<select id='child'>
<option value='11'>Value11</option></select>"
$("#fillValue").html(data);
}
});
You need to compose your java response like select tag and return it to your ajax response. Finally you can fill the second dropdown like that. Let me know if this helps.
<form method="post" action="select.jsp">
<select name="sell">
<option value="Alto">Alto</option>
<option value="Esteem">Esteem</option>
<option value="Honda City">Honda City</option>
<option value="Chevrolet">Chevrolet</option>
</select>
<br>
<input type="Submit" value="Submit">
</form>
<%
String st=request.getSelectedIndex("sell");
if(st!=null){
out.println("You have selected: "+st);
}
%>