Next button will generate a new set of questions - java

I am trying to create an online quiz system using jsp and servlets.
When the user chooses the topic, it goes to the first question. After the user chooses their choice, and clicks on the next button, it is supposed to show a new set of questions and choices. I am not sure how to do that part. Here is my code so far:
Database:
public static MathQuestion getQuestionInfo(int questionNum)
{
MathQuestion math = new MathQuestion();
// int questionNum = 1;
try
{
Connection conn = DBConnection.getConnection();
String query = "SELECT * FROM MathQuestions where QuestionNumber = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setInt(1, questionNum);
// questionNum++;
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
math.setQuestionNum(rs.getInt("QuestionNumber"));
math.setQuestion(rs.getString("Question"));
String questionOptions = rs.getString("QuestionOptions");
String[] splittedValues = null;
for(int i = 0; i < 4; i++)
{
splittedValues = questionOptions.split(",");
}
math.setQuestionOptions(splittedValues);
math.setCorrectAnswer("CorrectAnswer");
}
}
catch (Exception e)
{
System.out.println(e);
}
return math;
}
JSP
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Math</title>
</head>
<body>
<h1>Math Section</h1>
<%
String email = (String) session.getAttribute("email");
int questionNum = (Integer) request.getAttribute("questionNum");
MathQuestion math = new MathQuestion();
if(email != null)
{
math = MathService.getQuestionInfo(questionNum);
}
String[] questionOptions = math.getQuestionOptions();
%>
<form name="MathForm" action="Math" method="post">
Question <input type="text" value="<%=math.getQuestionNum()%>"> <br/>
<input type="text" value="<%=math.getQuestion()%>"> <br/>
<input type="radio" name="options" value="OptionA"><%=questionOptions[0]%> <br/>
<input type="radio" name="options" value="OptionB"><%=questionOptions[1]%> <br/>
<input type="radio" name="options" value="OptionC"><%=questionOptions[2]%> <br/>
<input type="radio" name="options" value="OptionD"><%=questionOptions[3]%> <br/>
<input type="button" name="Next" value="Next">
</form>
</body>
</html>
Servlet:
#WebServlet(name = "Math", urlPatterns =
{
"/Math"
})
public class Math extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
if (SessionService.validateSession(request, response))
{
RequestDispatcher dispatcher = request.getRequestDispatcher("math-page.jsp");
request.setAttribute("questionNum", 1);
dispatcher.forward(request, response);
}
else
{
RequestDispatcher dispatcher = request.getRequestDispatcher("login-page.jsp");
dispatcher.forward(request, response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
for(int i = 2; i <= 10; i++)
{
RequestDispatcher dispatcher = request.getRequestDispatcher("math-page.jsp");
request.setAttribute("questionNum", i);
dispatcher.forward(request, response);
}
String userChoice = request.getParameter("options");
}
}

Related

How to solve after push the submit button it shows 404 error with controller message [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
im currently doing my final year project about lost and found system using java and oracle database (MVC).
my problem is after I submit the form the page will show this the message says it redirect to the FoundRegisterController
it supposedly register the found item. but it did not. how can I solve this problem? Below are the codes for the jsp, controller and DAO
this is registerFoundItem.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!doctype html>
<html class="no-js" lang="en">
<head>
<jsp:include page="css.jsp"></jsp:include>
</head>
<body>
<jsp:include page="header.jsp" />
<!-- tabs & register form Start -->
<div class="basic-form-area mg-b-15">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="sparkline8-list mt-b-30">
<div class="sparkline8-graph">
<div class="basic-login-form-ad">
<div class="row">
<div class="col-lg12 col-md-12 col-sm-12 col-xs-12">
<h2>
<center>Register New Found Item</center>
</h2>
<br> <br>
</div>
</div>
<%
String userEmail = (String) session.getAttribute("currentSessionUser");
%>
<%
String userNoPhone = (String) session.getAttribute("currentSessionUserNoPhone");
%>
<%
String userName = (String) session.getAttribute("currentSessionUserName");
%>
<div class="row">
<form action="FoundRegisterController" method="post">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<div class="basic-login-inner">
<h4>Reporter Details:</h4>
<div class="form-group-inner">
<label>Post by:</label> <input type="text"
class="form-control" name="UserName"
value="<c:out value="<%=userName%>" />" disabled />
</div>
<div class="form-group-inner">
<label>Contact Number: </label><input type="text"
class="form-control" name="UserNoPhone"
value="<c:out value="<%=userNoPhone%>" />" disabled />
</div>
<div class="form-group-inner">
<label>Email: </label><input type="text"
class="form-control" name="UserNoPhone"
value="<c:out value="<%=userEmail%>" />" disabled />
</div>
<br>
</div>
</div>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
<h4>Found Item Details :</h4></div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label>Date:</label> <input class="form-control"
name="FItemDate" type="date" required />
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label>Time:</label> <input class="form-control"
name="FItemTime" type="time"
required />
</div>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
<div class="form-group-inner">
<label><br>Found Item Name:</label> <input type="text"
class="form-control" name="FItemName"
placeholder="eg: iPhone 8 Plus | ASUS | GoPro 5 Black"
title="Please enter the valid name. Do not use shortform"
required />
</div>
<div class="form-group-inner">
<label>Found Item Category:</label>
<div class="form-select-list">
<select class="form-control custom-select-value"
name="account" name="FItemCategory">
<option disabled selected value>-- Select
Category --</option>
<option value="FoundItem">Mobile Phone</option>
<option value="FoundItem">Laptop/Notebook</option>
<option value="FoundItem">Keys</option>
<option value="FoundItem">Cards</option>
<option value="FoundItem">UiTM Matrics Card</option>
<option value="FoundItem">Other..</option>
</select>
</div>
</div>
<div class="form-group-inner">
<label>Location:</label> <input class="form-control"
name="FItemLocation"
placeholder="eg: Blok Kuliah 17 | JMK 8 | Cafe Kuliah"
title="Please enter the valid name. Do not use shortform"
required />
</div>
<div class="form-group-inner">
<label>Description: </label>
<div class="form-group edit-ta-resize res-mg-t-15">
<textarea name="description" name="FItemDescription" placeholder="eg: Barang dijumpai di bawah meja/atas lantai/depan pintu/atas meja pensyarah/etc.. anggaran waktu dijumpai 2ptg-6ptg"></textarea>
</div>
</div>
<div class="login-btn-inner">
<div class="inline-remember-me">
<button
class="btn btn-sm btn-primary pull-right login-submit-cs"
type="submit" name="action">
<b>Register</b>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
</div>
<!-- tabs & Register form End-->
<!-- JS -->
<jsp:include page="js.jsp"></jsp:include>
</body>
</html>
this is my FoundRegisterController.java
package lofo.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lofo.dao.foundDAO;
import lofo.model.FoundItemBean;
/**
* Servlet implementation class RegisterController
*/
#WebServlet("/FoundRegisterController")
public class FoundRegisterController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String VIEW ="/lofo/viewFound.jsp";
private foundDAO dao;
String forward="";
String action="";
/**
* #see HttpServlet#HttpServlet()
*/
public FoundRegisterController() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if(action.equalsIgnoreCase("viewFound")) {
forward = VIEW;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = dao.getUserByEmail(UserEmail);
request.setAttribute("found", found);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
action = request.getParameter("action");
try {
String FItemID = request.getParameter("FItemID");
String UserEmail = request.getParameter("UserEmail");
String FItemName = request.getParameter("FItemName");
String FItemCategory = request.getParameter("FItemCategory");
String FItemDate = request.getParameter("FItemDate");
String FItemTime = request.getParameter("FItemTime");
String FItemLocation = request.getParameter("FItemLocation");
String FItemDescription = request.getParameter("FItemDescription");
FoundItemBean found = new FoundItemBean();
found.setFItemID(FItemID);
found.setUserEmail(UserEmail);
found.setFItemName(FItemName);
found.setFItemCategory(FItemCategory);
found.setFItemDate(FItemDate);
found.setFItemTime(FItemTime);
found.setFItemLocation(FItemLocation);
found.setFItemDescription(FItemDescription);
dao = new foundDAO();
found = foundDAO.getUser(found);
try {
dao.FoundAdd(found);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<script>");
pw.println("alert('The item post has been created');");
pw.println("window.location.href='FoundController?action=listFoundItem';");
pw.println("</script>");
}
catch (Throwable ex) {
System.out.println(ex);
}
}
}
this is my FoundController.java
package lofo.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lofo.dao.foundDAO;
import lofo.model.FoundItemBean;
/**
* Servlet implementation class UserController
*/
#WebServlet("/FoundController")
public class FoundController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String VIEW ="viewFound.jsp";
private String VIEWALL ="listFoundItem.jsp";
private static String UPDATE = "updateFound.jsp";
private static String DELETE = "deleteFound.jsp";
private static String SEARCH = "registerFoundItem.jsp";
String forward;
private foundDAO dao;
/**
* #see HttpServlet#HttpServlet()
*/
public FoundController() {
super();
dao = new foundDAO();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if(action.equalsIgnoreCase("viewFound")) {
forward = VIEW;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = foundDAO.getUserByEmail(UserEmail);
List<FoundItemBean> founds = foundDAO.getAllFound();
request.setAttribute("founds", founds );
request.setAttribute("found", found);
}
else if (action.equalsIgnoreCase("listFoundItem")) {
forward = VIEWALL;
request.setAttribute("founds", foundDAO.getAllFound());
}
else if (action.equalsIgnoreCase("updateFound")){
forward = UPDATE;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = foundDAO.getUserByEmail(UserEmail);
List<FoundItemBean> founds = foundDAO.getAllFound();
request.setAttribute("founds", founds);
request.setAttribute("found", found);
}
else if (action.equalsIgnoreCase("search")){
forward = SEARCH;
List<FoundItemBean> found = foundDAO.getAllFound();
request.setAttribute("founds", found);
}
else if (action.equalsIgnoreCase("deleteFound")){
forward = DELETE;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = foundDAO.getUserByEmail(UserEmail);
request.setAttribute("found", found);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String action = request.getParameter("action");
if(action.equalsIgnoreCase("Submit")) {
String UserEmail = request.getParameter("UserEmail");
String FItemName = request.getParameter("FItemName");
String FItemCategory = request.getParameter("FItemCategory");
String FItemDate = request.getParameter("FItemDate");
String FItemTime = request.getParameter("FItemTime");
String FItemLocation = request.getParameter("FItemLocation");
String FItemDescription = request.getParameter("FItemDescription");
FoundItemBean found = new FoundItemBean();
found.setUserEmail(UserEmail);
found.setFItemName(FItemName);
found.setFItemCategory(FItemCategory);
found.setFItemDate(FItemDate);
found.setFItemTime(FItemTime);
found.setFItemLocation(FItemLocation);
found.setFItemDescription(FItemDescription);
dao = new foundDAO();
try {
dao.updateFound(found);
/*forward = VIEW;
user = UserDAO.getUserByEmail(UserEmail);
request.setAttribute("user", user); */
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<script>");
pw.println("alert('The account is updated');");
pw.println("window.location.href='/lofo/FoundController?action=viewFound&UserEmail="+ UserEmail +"';");
pw.println("</script>");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//}
//else if(action.equalsIgnoreCase("Delete")) {
//String UserEmail = request.getParameter("UserEmail");
// = new foundDAO();
//dao.deleteUser(UserEmail);
//response.setContentType("text/html");
//PrintWriter pw = response.getWriter();
//pw.println("<script>");
//pw.println("alert('The account has been deleted');");
//pw.println("window.location.href='/Inventory/UserController?action=listAll';");
//pw.println("</script>");
//}
}
}
}
this is my foundDAO.java
package lofo.dao;
import java.sql.Statement;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import lofo.model.FoundItemBean;
import lofo.model.UsersBean;
import lofo.connection.ConnectionManager;
public class foundDAO {
static Connection currentCon = null;
static ResultSet rs = null;
static PreparedStatement ps = null;
static Statement stmt = null;
static String FItemID, UserEmail, FItemName, FItemCategory, FItemDate, FItemTime, FItemLocation, FItemDescription;
public static FoundItemBean getUser(FoundItemBean bean) {
UserEmail = bean.getUserEmail();
String searchQuery = "select * from founditem where useremail='" + UserEmail + "'";
try {
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
boolean more = rs.next();
// if user exists set the isValid variable to true
if (more) {
String UserEmail = rs.getString("UserEmail");
bean.setUserEmail(UserEmail);
bean.setValid(true);
}
else if (!more) {
System.out.println("Sorry");
bean.setValid(false);
}
}
catch (Exception ex) {
System.out.println("Log In failed: An Exception has occurred! " + ex);
}
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;
}
//get user by email
public static FoundItemBean getUserByEmail(String UserEmail) {
FoundItemBean found = new FoundItemBean();
try {
currentCon = ConnectionManager.getConnection();
ps=currentCon.prepareStatement("select * from founditem where useremail=?");
ps.setString(1, UserEmail);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
found.setFItemID(rs.getString("FItemID"));
found.setUserEmail(rs.getString("UserEmail"));
found.setFItemName(rs.getString("FItemName"));
found.setFItemCategory(rs.getString("FItemCategory"));
found.setFItemDate(rs.getString("FItemDate"));
found.setFItemTime(rs.getString("FItemTime"));
found.setFItemLocation(rs.getString("FItemLocation"));
found.setFItemDescription(rs.getString("FItemDescription"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return found;
}
//create Found Item
public void FoundAdd (FoundItemBean bean) throws NoSuchAlgorithmException {
FItemID = bean.getFItemID();
UserEmail = bean.getUserEmail();
FItemName = bean.getFItemName();
FItemCategory = bean.getFItemCategory();
FItemDate = bean.getFItemDate();
FItemTime = bean.getFItemTime();
FItemLocation = bean.getFItemLocation();
FItemDescription = bean.getFItemDescription();
try {
currentCon = ConnectionManager.getConnection();
ps=currentCon.prepareStatement("insert into founditem(FItemID, UserEmail, FItemName, FItemCategory, FItemDate, FItemTime, FItemLocation, FItemDescription) values (FOUNDITEM_SEQ.nextval,?,?,?,?,?,?,?)");
ps.setString(1,UserEmail);
ps.setString(2,FItemName);
ps.setString(3,FItemCategory);
ps.setString(4,FItemDate);
ps.setString(5,FItemTime);
ps.setString(6,FItemLocation);
ps.setString(7,FItemDescription);
ps.executeUpdate();
System.out.println("Your FItemName is " + FItemName);
}
catch (Exception ex) {
System.out.println("failed: An Exception has occured!" + ex);
}
finally {
if (ps != null) {
try {
ps.close();
} catch (Exception e) {
}
ps = null;
}
if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}
currentCon = null;
}
}
}
//update account
public void updateFound(FoundItemBean bean) throws NoSuchAlgorithmException {
FItemName = bean.getFItemName();
FItemCategory = bean.getFItemCategory();
FItemDate = bean.getFItemDate();
FItemTime = bean.getFItemTime();
FItemLocation = bean.getFItemLocation();
FItemDescription = bean.getFItemDescription();
String searchQuery = "";
searchQuery = "UPDATE founditem SET FItemName ='"+ FItemName +"', FItemCategory='" + FItemCategory + "', FItemDate='" + FItemDate + "', FItemTime='" + FItemTime + "', FItemLocation='" + FItemLocation + "', FItemDescription='" + FItemDescription + "' WHERE UserEmail= '" + UserEmail + "'";
System.out.println(searchQuery);
try {
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
stmt.executeUpdate(searchQuery);
System.out.println(searchQuery);
} catch (SQLException e) {
e.printStackTrace();
}
}
//getAllFound for list table
public static List<FoundItemBean> getAllFound() {
List<FoundItemBean> founds = new ArrayList<FoundItemBean>();
try {
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
String q = "select * from founditem";
ResultSet rs = stmt.executeQuery(q);
while (rs.next()) {
FoundItemBean found = new FoundItemBean();
found.setUserEmail(rs.getString("UserEmail"));
found.setFItemName(rs.getString("FItemName"));
found.setFItemCategory(rs.getString("FItemCategory"));
found.setFItemDate(rs.getString("FItemDate"));
found.setFItemTime(rs.getString("FItemTime"));
found.setFItemLocation(rs.getString("FItemLocation"));
found.setFItemDescription(rs.getString("FItemDescription"));
founds.add(found);
}
} catch (SQLException e) {
e.printStackTrace();
}
return founds;
}
}
The error message shown in the attached picture is -
"The origin server did not find a current representation for the target resource..."
This error is usually not due to a problem in the code.
This error is caused due to an issue with the IDE (Common with Eclipse), or due to the way the application is deployed on the Web server.
Here is a workaround for this problem:
Take a backup of the project files.
Delete the project from eclipse.
Make sure that the character encoding is set to 'utf-8' in all the html template files**
<html lang="en">
<head>
<meta charset="utf-8"/>
</head>
Restart eclipse.
Do a fresh import of the project into eclipse.
Verify the web.xml file for the correct mapping of servlets
More help:
https://www.codejava.net/java-ee/servlet/solved-tomcat-error-http-status-404-not-found
The origin server did not find a current representation for the target resource or is not ... error when running jsp page
Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Display Database of relational database records using hyperlink on JSP [duplicate]

This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 4 years ago.
I am basically displaying MySQL database records on JSP/JSTL page using Servlet & JDBC. I have two tables one is "Employee Table" & other "Location Table"(both tables are related via PK & FK). Now I am able to display Employee Table on JSP which looks like:
Employee Table on JSP
Now the hyperlink is appearing on the column "Department #" that is supposed to display the "Location Table" for each employee, not all rows of different employees. My coding for this project includes 2 POJO classes for Employee & Location table, an EmployeeDbUtil class for JDBC connection, Employee Servlet and two JSP files for Employee & Location table display.
Location Table for single Employee when clicked on hyperlink
Now what my problem is that I have hard coded the SQL query part on DbUtil class for getting the single row for Location Table by saying "where location.dept_no = 10" that's why it gives same row when clicked on any of the hyperlinks, this is not good. So please show me code segment that I can use such that I can get different results when clicked on different hyperlinks for different employees. I really don't know how to do that so please help me here. Thank you!
Here's my complete code (DbUtil, Servlet & JSP):
EMPLOYEE DbUtil(For JDBC Connection)
private DataSource dataSource;
public EmployeeDbUtil(DataSource theDataSource) {
dataSource = theDataSource;
}
public List<Employee> getEmployee() throws Exception {
List<Employee> employees = new ArrayList<>();
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
try {
// Get connection
myConn = dataSource.getConnection();
// SQL Query
String sql = "SELECT * FROM order_customer.employee; ";
myStmt = myConn.createStatement();
myRs = myStmt.executeQuery(sql);
while (myRs.next()) {
// retrieving data
String employeeID = myRs.getString("employee_id");
String name = myRs.getString("name");
int salary = myRs.getInt("salary");
String hireDate = myRs.getString("hire_date");
int deptNum = myRs.getInt("dept_no");
// create new customer object
Employee tempEmployee = new Employee(employeeID, name, salary, hireDate, deptNum);
// Now add tempCustomer to the ArrayList
employees.add(tempEmployee);
}
return employees;
}
finally {
close(myConn, myStmt, myRs);
}
}
private void close(Connection myConn, Statement myStmt, ResultSet myRs) {
}
////////////////////////////////////////////////////////////////////////
public List<Location> getLocation() throws Exception {
List<Location> location = new ArrayList<>();
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
try {
// Get connection
myConn = dataSource.getConnection();
// SQL Query
String sql = "SELECT location.dept_no,location.state,location.city \r\n" +
"from order_customer.employee JOIN order_customer.location\r\n" +
"on employee.dept_no=location.dept_no\r\n" +
"WHERE location.dept_no = '10' ";
myStmt = myConn.createStatement();
myRs = myStmt.executeQuery(sql);
while (myRs.next()) {
// retrieving data
int deptNum = myRs.getInt("dept_no");
String state = myRs.getString("state");
String city = myRs.getString("city");
// create new customer object
Location tempLocation = new Location(deptNum, state, city);
location.add(tempLocation);
}
return location;
}
finally {
close(myConn, myStmt, myRs);
}
}
}
Servlet Code:
private EmployeeDbUtil employeeDbUtil;
#Resource(name = "jdbc/order_customer")
private DataSource dataSource;
#Override
public void init() throws ServletException {
super.init();
try {
employeeDbUtil = new EmployeeDbUtil(dataSource);
} catch (Exception exc) {
throw new ServletException(exc);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// read the "command" parameter
String theCommand = request.getParameter("command");
if (theCommand == null) {
theCommand = "LIST";
}
// route to the appropriate method
switch (theCommand) {
case "LIST":
listEmployee(request, response);
break;
case "LOAD":
loadLocation(request, response);
break;
default:
listEmployee(request, response);
}
} catch (Exception exc) {
throw new ServletException(exc);
}
}
private void loadLocation(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<Location> location = employeeDbUtil.getLocation();
request.setAttribute("THE_LOCATION", location);
RequestDispatcher dispatcher = request.getRequestDispatcher("/location-info.jsp");
dispatcher.forward(request, response);
}
private void listEmployee(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<Employee> employees = employeeDbUtil.getEmployee();
request.setAttribute("EMPLOYEE_LIST", employees);
RequestDispatcher dispatcher = request.getRequestDispatcher("/list-employee.jsp");
dispatcher.forward(request, response);
}
}
JSP PAGE CODE:
<
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<title>Employee Details</title>
<link type="text/css" rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="wrapper">
<div id="header">
</div>
</div>
<div id="container">
<div id="content">
<table>
<tr>
<th>Employee ID</th>
<th>Name</th>
<th>Salary</th>
<th>Hire Date</th>
<th>Department #</th>
</tr>
<c:forEach var="tempEmployee" items="${EMPLOYEE_LIST}">
<c:url var="employeeLink" value="EmployeeServlet">
<c:param name="command" value="LOAD" />
<c:param name="deptNum" value="${tempEmployee.deptNum}" />
</c:url>
<tr>
<td>${tempEmployee.employeeID}</td>
<td>${tempEmployee.name}</td>
<td>${tempEmployee.salary}</td>
<td>${tempEmployee.hireDate}</td>
<td> ${tempEmployee.deptNum} </td>
</c:forEach>
</table>
</div>
</div>
</body>
JSP for Location table:
<<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<title>Employee Department</title>
<link type="text/css" rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>Department Details</h2>
</div>
</div>
<div id="container">
<div id="content">
<table>
<tr>
<th>Department #</th>
<th>State</th>
<th>City</th>
</tr>
<c:forEach var="tempLocation" items="${THE_LOCATION}">
<tr>
<td>${tempLocation.deptNum}</td>
<td>${tempLocation.state}</td>
<td>${tempLocation.city}</td>
<%-- <td> ${tempLocation.name} </td> --%>
</tr>
</c:forEach>
</table>
</div>
</div>
</body>
</html>
You can get the "deptNum" parameter by the same way you do with "command", pass it to DBUtil and then replace the '10'

Getting null value when passing the variable from jsp to servlet

I am trying to get a value from jsp to sevlet.First the variable value is taken by session setArribute(), getAttribute() then I need to pass that particular variable from jsp to servlet but I am getting null value for that variable.
Here below I am sharing my code, can anyone findout how can I solve this issue?
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#page import="java.sql.*"%>
<html>
<head>
<title>Welcome to survey</title>
</head>
<body>
<%
ResultSet rset;
String sur_id = request.getParameter("surveyid");
session.setAttribute( "surveyid", sur_id );
int new_survey_id = Integer.parseInt(sur_id);
if (request.getParameter("surveyid") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request.getParameter("surveyid")+"</b>!");
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ new_survey_id ;
Statement stmt = con.createStatement();
rset = stmt.executeQuery(query);
while(rset.next()){
// out.println(rset.getString(1));
// out.println(rset.getString(2));
// out.println(rset.getString(3));
// out.println(rset.getString(4));
%>
<table border="3">
<tr><td>Survey_Id</td><td><%=rset.getString(1)%></td></tr>
<tr><td>Family name</td><td><%=rset.getString(2)%></td></tr>
<tr><td>First name</td><td><%=rset.getString(3)%></td></tr>
<tr><td>Middle name</td><td><%=rset.getString(4)%></td></tr>
<tr><td>gender</td><td><%=rset.getString(5)%></td></tr>
<tr><td>dat of birth</td><td><%=rset.getString(6)%></td></tr>
<tr><td>income</td><td><%=rset.getString(7)%></td></tr>
<tr><td>complete address</td><td><%=rset.getString(8)%></td></tr>
<tr><td>coordinates</td><td><%=rset.getString(9)%></td></tr>
<tr><td>mobile number</td><td><%=rset.getString(10)%></td></tr>
<tr><td>email address</td><td><%=rset.getString(11)%></td></tr>
<tr><td>present Internet provider</td><td><%=rset.getString(12)%></td></tr>
<tr><td>comments</td><td><%=rset.getString(13)%></td></tr>
<tr><td>remarks</td><td><%=rset.getString(14)%></td></tr>
<br>
<form>
<table>
<tr><td><input type="button" value="edit" onclick="javascript:document.forms[0].action = 'EditSurvey.jsp'; document.forms[0].submit();"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="delete"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="print"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="send mail"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
</tr>
</table>
</form>
</table>
<%
}
%>
</body>
</html>
from the above code I have set the session variable as surveyid
and I can get it from the below code.It is working properly
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Edit survey</title>
</head>
<body>
<%
ResultSet resultSet;
String surveyId = (String) session.getAttribute("surveyid");
out.println("check"+surveyId);
request.setAttribute("surveyid", surveyId);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ surveyId ;
Statement stmt = con.createStatement();
ResultSet rset = stmt.executeQuery(query);
while(rset.next()){
%>
<form name="Editsurveyform" method="post" action="EditSurvey">
<table>
<tr><td>Family name:</td><td><input type="text" name="familyName" value='<%=rset.getString(2)%>'></td></tr>
<tr><td>First name:</td><td><input type="text" name="firstName" value='<%=rset.getString(3)%>'></td></tr>
<tr><td>Middle name:</td><td><input type="text" name="middleName" value='<%=rset.getString(4)%>'></td></tr>
<tr><td>Gender:</td>
<td>
<%
if(rset.getString(5).equals("male")){
%>
<input type="radio" name="sex" value="male" checked>Male
<input type="radio" name="sex" value="female">Female
<%}
else{
%>
<input type="radio" name="sex" value="male">Male
<input type="radio" name="sex" value="female" checked>Female
<%
}
%>
</td>
</tr>
<tr><td>Birthday:</td><td><input type="date" name="dob" value='<%=rset.getString(6)%>'></td></tr>
<tr><td>Income : A?B?C?D?</td><td><input type="text" name="income" value='<%=rset.getString(7)%>'></td></tr>
<tr><td>Complete Address:</td><td><input type="text" name="address" value='<%=rset.getString(8)%>'></td></tr>
<tr><td>Coordinates:</td><td><input type="text" name="coordinates" value='<%=rset.getString(9)%>'></td></tr>
<tr><td>Mobile number:</td><td><input type="tel" name="mobileno" value='<%=rset.getString(10)%>'></td></tr>
<tr><td>Email Address:</td><td><input type="email" name="email" value='<%=rset.getString(11)%>'></td></tr>
<tr><td>Present internet provider:</td><td><input type="text" name="iprovider" value='<%=rset.getString(12)%>'></td></tr>
<tr><td>Positive comments with present provider:</td><td><textarea name="comments" cols="40" rows="5"><%=rset.getString(13)%></textarea></td></tr>
<tr><td>Negative remarks with present provider:</td><td><textarea name="remarks" cols="40" rows="5"><%=rset.getString(14)%></textarea></td></tr>
<tr><td><input type="submit" name="editsurvey" value="update survey details"></td><td><input type="reset" name="cancel" value="cancel"></td></tr>
</table>
</form>
<%}
//response.sendRedirect("EditSurvey?surveyId="+surveyId);
%>
</body>
</html>
But I encounter the problem in below java
package com.survey;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
* Created by rajee on 2/18/15.
*/
public class EditSurvey extends HttpServlet {
public String familyName;
public String firstName;
public String middlename;
public String gender;
public String dateOfBirth;
public String income;
public String completeAddress;
public String coordinates;
public String mobileno;
public String emailAddress;
public String presentIP;
public String comment;
public String remark;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String surveyId = (String) request.getAttribute("surveyid");
System.out.println(surveyId);
familyName = request.getParameter("familyName");
firstName = request.getParameter("firstName");
middlename = request.getParameter("middleName");
gender = request.getParameter("sex");
dateOfBirth = request.getParameter("dob");
income = request.getParameter("income");
completeAddress = request.getParameter("address");
coordinates = request.getParameter("coordinates");
mobileno = request.getParameter("mobileno");
emailAddress = request.getParameter("email");
presentIP = request.getParameter("iprovider");
comment = request.getParameter("comments");
remark = request.getParameter("remarks");
System.out.println(familyName);
System.out.println(firstName);
System.out.println(middlename);
System.out.println(gender);
System.out.println(dateOfBirth);
System.out.println(income);
System.out.println(completeAddress);
System.out.println(coordinates);
System.out.println(mobileno);
System.out.println(emailAddress);
System.out.println(presentIP);
System.out.println(comment);
System.out.println(remark);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="surveysample";
String driver="com.mysql.jdbc.Driver";
//String dbUserName="root";
//String dbPassword="root";
// try{
//
//
// Class.forName(driver).newInstance();
// conn = DriverManager.getConnection(url + dbName, "root", "root");
// PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into surveysample.surveydetail(familyname,firstname,middlename,gender,dateofbirth,income,complete_address,coordinates,mobilenumber,emailaddress,presentiprovider,comments,remarks) values (?,?,?,?,?,?,?,?,?,?,?,?,?)");//try2 is the name of the table
//
// pst.setString(1,familyName);
// pst.setString(2,firstName);
// pst.setString(3,middlename);
// pst.setString(4,gender);
// pst.setString(5,dateOfBirth);
// pst.setString(6,income);
// pst.setString(7,completeAddress);
// pst.setString(8,coordinates);
// pst.setString(9,mobileno);
// pst.setString(10,emailAddress);
// pst.setString(11,presentIP);
// pst.setString(12,comment);
// pst.setString(13,remark);
//
//
// int i = pst.executeUpdate();
// //conn.commit();
// String msg=" ";
// if(i!=0){
// msg="Record has been inserted";
// pw.println("<font size='6' color=blue>" + msg + "</font>");
//
//
// }
// else{
// msg="failed to insert the data";
// pw.println("<font size='6' color=blue>" + msg + "</font>");
// }
// pst.close();
// }
// catch (Exception e){
// pw.println(e);
// }
//
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
code
If your problem is for surveyId being null is servlet, it is normal because you try to get it from request :
String surveyId = (String) request.getAttribute("surveyid");
As you put it in session, you should read it from there :
String surveyId = (String) request.getSession().getAttribute("surveyid");
You can try below code in your servlet as :
HttpSession session = request.getSession(false);
String surveyId = (String) session.getAttribute("surveyid");
this method request.getSession(false) will not create new session if session object is already exists. it will simply return old session object if its there otherwise it will return null.

I want to automatically increase table row after clicking button

Hi, my problem is increasing the table row automatically. Actually, when I click GET button the product type and product name values are getting from database. Here, after getting those values, I will give another id based on that id again for values will come. But it was not setting in another row. Here is my java code and jsp:
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms?user=root&password=root");
System.out.println("Connection created");
Statement st =con.createStatement();
String query="select * from product where ProductType_v='"+a+"' and ProductId_v='"+b+"'";
ResultSet rs = (ResultSet)st.executeQuery(query);
int i=0;
while(rs.next())
{
i++;
request.getSession().setAttribute("edit","success");
request.getSession().setAttribute("proType ", rs.getString("ProductType_v"));
request.getSession().setAttribute("proId", rs.getString("ProductId_v"));
request.getSession().setAttribute("strength", rs.getString("Strength_v"));
request.getSession().setAttribute("proName", rs.getString("ProductName_v"));
request.getSession().setAttribute("brand", rs.getString("BrandName_v"));
request.getSession().setAttribute("generic", rs.getString("GenricName_v"));
request.getSession().setAttribute("uom", rs.getString("UOM_v"));
request.getSession().setAttribute("formE", rs.getString("FormE_v"));
request.getSession().setAttribute("presReqd", rs.getString("PresReqd_v"));
}
if(i==0)
{
request.getSession().setAttribute("edit", "fail");
}
}
catch(Exception e)
jsp code
<tr>
<td>
<input class="textfield-form-date-req" type="text" id="pro_type">
</td>
<%
if(editStatus =="success")
{
%>
<script type="text/javascript">
document.getElementById("pro_type").value='<%=session.getAttribute("proType")%>';
</script>
<%
}
<td>
<input class="textfield-form-date-req" type="text" id="pro_id">
</td>
<%
if(editStatus =="success")
{
%>
<scripttype="text/javascript">
document.getElementById("pro_id").value='<%=session.getAttribute("proName")%>';
</script>
<%
}
%>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
I have created a sample for you with ajax. It gets the data from the server side and append it , in the existing table.
The jar files I have used is ,
jackson-all-1.9.0.jar - to convert the java object to json format
servlet-api-2.4.jar - for servlet
My TableAppend.jsp will be,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
//alert("DOM is ready");
});
function sendData() {
$.ajax({
type : 'POST',
url : "TableAppend",
data : "name=" + $('#name').val() + "&age=" + $('#age').val()
+ "&sid=" + new Date(),
dataType : 'html',
success : function(result) {
//alert("Result ::::>>> "+result);
if(result != null && $.trim(result) != "" && result != undefined){
var json = JSON.parse(result);
//alert(json.name);
//alert(json.age);
appendToTable(json.name, json.age);
}
},
error : function(e) {
alert('Error in Processing');
}
});
}
function appendToTable(name, age) {
var tr = "<tr><td>" + name + "</td><td>" + age + "</td></tr>"
$('#mytable').append(tr);
}
</script>
</head>
<body>
Name :
<input type="text" id="name" name="name" /> Age :
<input type="text" id="age" name="age" />
<input type="button" value="Append to table" onclick="sendData()">
<br></br>
<br></br>
<br></br>
<table id="mytable" border="1">
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>HumanBeing</td>
<td>25</td>
</tr>
<tr>
<td>Saideep</td>
<td>26</td>
</tr>
</tbody>
</table>
</body>
</html>
My TableAppend.java servlet will be,
public class TableAppend extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TableAppend() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("UTF");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
String json ="";
System.out.println("-----------------");
if(name != null && age != null){
TableAppendPojo obj = new TableAppendPojo();
obj.setName(name);
obj.setAge(age);
ObjectMapper mapper = new ObjectMapper();
json = mapper.writeValueAsString(obj);
System.out.println("json : "+json);
}
out.println(json);
}
}
Then java class will be,
public class TableAppendPojo {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Note : Please apply the above logic in your code . In your case , you don't need to give the data from the UI. You retrieves the data from the database in the servlet.So please convert the retrieved data from the database to the json format and append it to the table.
Hope this helps.

In struts 1.3 how to retrieve data from database and display it using DAO

*M new to struts. I am making simple login page that display username and password by retrieving it from database. I m using DAO.
I have LoginDAO.java, LoginAction.java and Displaydata.jsp pages. *
LoginDAO.java
public boolean login(String user,String pass) throws SQLException
{
Connection con = getConnection();
Statement st;
try {
st = con.createStatement();
st.executeQuery("select * from login where Username='" + user + "' and Password='" + pass + "'");
return true;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
}
LoginAction.java
public class LoginAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm rf= (DynaValidatorForm) form;
String username = rf.get("username").toString();
String password = rf.get("password").toString();
HttpSession session=request.getSession();
session.setAttribute("user", username);
Login dao= new Login();
if(dao.login(username,password))
{
System.out.println("GOT");
return mapping.findForward("success");}
else
{System.out.println("NOT");
return mapping.findForward("failure");
}
}
}
and also what do i write in Dislpaydata.jsp to display username and password in it dont want any java code in it.
Thankyou
Right. Some time ago I built an application with Struts 1.x and MySql with login.
LoginAction
public ActionForward login( ... ) throws Exception {
String forward;
final String mail = PropertyUtils.getProperty(form, "mail");
final String password = PropertyUtils.getProperty(form, "password");
if (LoginService.getInstance().validate(mail, password)) {
// Do something e.g. put name of user in session
forward = SUCCESS;
} else {
forward = ERROR;
}
return mapping.findForward(forward);
}
LoginService
public boolean validate(final String mail, final String password)
throws ServiceException {
try {
final boolean valid;
// Validate null and empty
// Validate with DB
final UserDAO dao = new UserDAO();
final User user = dao.findByPk(mail);
if (user == null) {
valid = false;
} else {
if (password.equals(user.getPassword())) {
valid = true;
} else {
valid = false;
}
}
return valid;
} catch (DAOException e) {
throw new ServiceException("Error validating user and password.", e);
}
}
UserDAO
private static final String FIND_BY_PK_SQL
= "SELECT mail, name, password, admin FROM user WHERE mail = ?";
public User findByPk(final String mail) throws DAOException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection();
ps = conn.prepareStatement(FIND_BY_PK_SQL);
ps.setString(1, mail); // PK, NOT NULL
rs = ps.executeQuery();
if (rs.next()) {
return fill(rs);
}
return null;
} catch (final SQLException e) {
throw new DAOException(e);
} finally {
// Close DB resources
}
}
private User fill(final ResultSet rs) throws SQLException {
final User user = new User();
user.setMail(rs.getString("mail"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setAdmin(rs.getBoolean("admin"));
return user;
}
In my case I have a table user with mail as a primary key. There are various forms.
More examples:
Building a Login Application
Struts Login Application Using Action Form Tutorial | DZone
Creating a Email Login Web Application with Struts
e.g. For show the name of variable user in session scope from the database:
LoginAction
if (LoginService.getInstance().validate(mail, password)) {
final HttpSession session = request.getSession();
final User user = UserService.getInstance().getUser(mail);
session.setAttribute("user", user);
forward = SUCCESS;
}
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
Welcome,
<bean:write scope="session" name="user" property="name" filter="false" />
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
</head>
<body bgcolor="#2EFEF7">
<form action="action" method="post" id="formDemo" name="MyForm">
<div id="header">
<h2 style="color: red;">Training</h2>
</div>
<hr>
<h3>Login</h3>
<div id="center" style="padding-top: 50px; padding-bottom: 220px;">
<table align="center">
<tr>
<th colspan="2"><h1 style="color: BLUE;">LOGIN</h1></th>
</tr>
<tr>
<th colspan="2"><h5 id="error" style="color: red;"></h5></th>
</tr>
<tr>
<td>UserID:</td>
<td><input type="text" size="40" name="UserId" maxlength="8"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" size="40" name="Password" maxlength="8"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Login"> <input type="button" id="reset"
value="Clear"></td>
</tr>
</table>
</div>
<hr>
<div id="footer">
<label>Copy right# 2000-2008 FUJINET, All Rights Reserved.</label>
</div>
</form>
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate() {
if (document.MyForm.UserId.value === ""
|| document.MyForm.UserId.value === null) {
document.getElementById("error").innerHTML = "Please insert userId";
return false;
}
if (document.MyForm.Password.value === ""
|| document.MyForm.Password.value === null) {
document.getElementById("error").innerHTML = "Please insert password";
return false;
}
return (true);
}
$("#reset").click(function(event) {
document.MyForm.UserId.value = "";
document.MyForm.Password.value = "";
document.getElementById("error").innerHTML = "";
});
$("#formDemo").submit(function(event){
return validate();
});
</script>
</body>
</html>

Categories

Resources