I am trying to send some data from JSP to Servlet using JQuery/Ajax. Below are the important items of my JSP file.
script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var form = $('#customItemForm');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
}
});
return false;
});
</script>
<!--add custom item -->
<div class="modal fade" id="customItemModel" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"> <img src="images/arrow-back-512.png" width="30px" height="30px"> <small>Back</small> <span id="myModalLabel" style="margin-left:20px;"><font size="+2"><b>Add Custom Item</b></font></span> </div>
<div class="modal-body">
<form class="form-horizontal" name="customItemForm" method="post" action="PastSurgicalCustomItem">
<fieldset id="modal_form">
<!-- Text input-->
<div class="form-group">
<label class="col-md-1 control-label" for="textinput">Name</label>
<div class="col-md-8">
<input id="customName" name="customName" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<div class="modal-footer">
<input type="submit" id="additional" class="btn btn-primary" data-dismiss="modal" value="Submit">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<!-- /add custom item -->
Below is the Servlet class
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PastSurgicalCustomItem extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String customName = request.getParameter("customName");
System.out.println(customName);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
However the servlet do not print the value, which means the JQuery didn't pass anything. What have I done wrong here?
Set a breakpoint in you doGet method and step through the code to see whether it is not executed at all or whether it is executed, but throws an exception.
Additionally, you should monitor your AJAX call in the browser (e.g., by looking at the network connections in the developer view available in all modern browsers) and reviewing the returned header and content of the AJAX call.
Related
I have created a registration form. And I don't know why now it doesn't work anymore.
Now I receive a 404 error:
Type Status Report
Message /HotelReservation/Registration
Description The origin server did not find a current representation
for the target resource or is not willing to disclose that one exists.
This is my
Registration.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hotel;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author OOPs
*/
public class Registration extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String s1 = request.getParameter("ename");
String s2 = request.getParameter("nname");
String s3 = request.getParameter("pname");
String s4 = request.getParameter("usid");
String s5 = request.getParameter("gm");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code.
out.println(s1);
out.println(s2);
out.println(s3);
out.println(s4);
out.println(s5);*/
// out.println(s1);
//concetivity...............
Class.forName("com.mysql.jdbc.Driver");
out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/HotelReservation","root" ,"123456789");
out.println("Connect");
Statement st = con.createStatement();
out.println("conncetion successfull");
st.executeUpdate("insert into register (email,name,pass) values ('"+s1+"','"+s2+"','"+s3+"')");
out.println("<h1> Register sucsefulltttt </h1>");
response.sendRedirect("thankyou.jsp");
}catch(Exception e){
out.println("nahiiiiiiiiiiiii" +e);
}
finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
And this is my
registration.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
<style>
#import url( css/default.css);
</style>
</head>
<body>
<div id="container">
<div id="nav">
Home
Prenotazione
Camere
Login
Registrazione
</div>
<script>
function validate()
{
if(document.getElementById("ename").value=="")
{
alert("blank");
return false;
}
return true;
}
</script>
<h2>Registrazione</h2>
<form action="Registration" method="post" onsubmit="return validate();">
<div class="gender">
<label id="icon" for="name"><i class="icon-envelope "></i></label>
<input type="text" name="ename" id="ename" placeholder="Email" required/>
<br>
<br>
<label id="icon" for="name"><i class="icon-user"></i></label>
<input type="text" name="nname" id="nname" placeholder="Name" required/>
<br>
<br>
<label id="icon" for="name"><i class="icon-shield"></i></label>
<input type="password" name="pname" id="pname" placeholder="Password" required/>
<br>
<input class="button" type="submit" value="Sign UP" name="b1"> </input>
<input class="button" type=button onClick="location.href='login.jsp'" value="Login" name="b" > </input>
</form>
<div id="footer">
<h4>Hotel Reservation </h4>
Viale Marco Polo, 81 Roma
tel: +39 01 0000000 | info#hotelreservation.it
P.IVA 000000001
</div>
</div>
</body>
</html>
How can I solve it in your opinion? Thanks
EDIT:
This is my :
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Hotelbooking</display-name>
<servlet>
<servlet-name>Hotelbooking</servlet-name>
<servlet-class>hotel.Hotelbooking</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hotelbooking</servlet-name>
<url-pattern>/hotelbooking</url-pattern>
</servlet-mapping>
<display-name>Login</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>hotel.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<display-name>Logout</display-name>
<servlet>
<servlet-name>Logout</servlet-name>
<servlet-class>hotel.Logout</servlet-class>
</servlet>
<display-name>Registration</display-name>
<servlet>
<servlet-name>Registration</servlet-name>
<servlet-class>hotel.Registration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registration</servlet-name>
<url-pattern>/registration</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>
HTTP Status 404 – Not Found
Type Status Report
Message /HotelReservation/Registration
Description The origin server did not find a current representation
for the target resource or is not willing to disclose that one exists.
myProject
Write your doGet method to forward at registration.jsp like this
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/registration.jsp").forward(request, response);
}
Another thing in error message map showing /HotelReservation/Registration
but in web.xml file servlet mapping is /registration. So hit correct url
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 2 years ago.
I m trying to pass formatted text from a text-editor that has been embedded in my jsp file. I m using enctype="multipart/form-data" in my form tag. I can pass the parameters to underyling servlet when using the default enctype. But I get null when using the multipart/form-data enctype in my servlet.
My form
<form action="pdfGenServlet" method="post" enctype="multipart/form-data">
<!-- input notes title-->
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Title of the notes" name="title">
</div>
</div>
<!-- input notes description-->
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Enter short description" name="description">
</div>
</div>
<div class="form-group">
<textarea name="content" id="myEditor"></textarea>
<div id="button-panel" class="panel panel-default">
<p>
<button type="submit" class="btn btn-primary "><span class="glyphicon glyphicon-plus"></span><strong> Create Note</strong></button>
<button class="btn btn-primary" type="reset"><strong>Reset</strong></button>
</p><!-- buttons -->
</div><!-- panel Button -->
</div>
</form>
My pdfGenServlet.java
#WebServlet("/pdfGenServlet")
public class pdfGenServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// Get the text that will be added to the PDF
request.setCharacterEncoding("UTF-8");
String title = request.getParameter("title");
String description = request.getParameter("description");
String notes_content = request.getParameter("content");
Date date = new Date();
} catch(exception e)
{e.printStackTrace();}
}
If you want to get parameters from HTML(JSP) form that content attribute " enctype="multipart/form-data" ".
You should add #MultipartConfig in a servlet that will receive all these parameters (Also add #MutipartConfig in the Convey/Dispatch Servlet).
In #MultipartConfig contains three elements :fileSizeThreshold, maxFileSize, maxRequestSize;
(I used Servlet 3 File Upload for upload file)
Refer to the following link it will help you to upload image with input parameters:
http://www.avajava.com/tutorials/lessons/how-do-i-upload-a-file-to-a-servlet.html
I solve this problem by using below code.
You should add #MultipartConfig annotation into your Servlet class:
For Example:
#WebServlet("/admin/create_book")
#MultipartConfig(
fileSizeThreshold = 1024 * 10, // 10 KB
maxFileSize = 1024 * 300, // 300 KB
maxRequestSize = 1024 * 1024 // 1 MB
)
public class CreateBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CreateBookServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BookServices bookServices = new BookServices(request, response);
bookServices.createBook();
}
}
I'm starting off in NetBeans, and implementing a form which, when you press the "submit" button, performs validation and tells you if the data entered is correct. I haven't gotten to the validation part yet, for the moment all I'm trying to do is, when the "submit" button is clicked, a message pops up. I'm having trouble here, I have a feeling its a quick simple fix but I'm not finding anything on message boards or documentation.
EDIT - Thanks guys! was missing the "form" tag. I figured it would be simple, thanks again for your help everyone!
Here's my index.html file:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Client Information</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><h1>Client Information</h1><table border="1">
<tbody>
<tr>
<td>First Name</td>
<td><input type="text" name="FirstName" value="" size="50" /></td>
<td>Surname</td>
<td><input type="text" name="Surname" value="" size="50"/></td>
</tr>
<tr>
<td>Age</td>
<td><input type="number" name="Age" value="" min="0" max="120"/></td>
<td>Gender</td>
<td><input type="text" name="Gender" value="" size="1" maxlength="1"/></td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit" name="validation" />
</div>
</body>
</html>
And here is the ClientInformationServlet.java file, most important is the processRequest method, and if (request.getParameter("validation")!= null) line is where I am trying to have the action take place.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clientInformation;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author nicolasdubus
*/
#WebServlet(name = "ClientInformationServlet", urlPatterns = {"/clientinformationservlet"})
public class ClientInformationServlet extends HttpServlet {
/*
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Client Information</title>");
out.println("</head>");
out.println("<body>");
String sfirst = request.getParameter("FirstName");
String ssecond = request.getParameter("SurName");
String sAge = request.getParameter("Age");
String sGender = request.getParameter("Gender");
try {
Integer age = Integer.parseInt(sAge);
if (request.getParameter("validation") != null) {
System.out.println("<h1>Client information is valid</h1>");
out.println("<h1>Client</h1>");
System.exit(0);
}
} catch (IllegalArgumentException e) {
out.println("<h1>Client information is invalid, please verify entries</h1>");
}
out.println("<body>");
out.println("</html");
/* */
out.close();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
The HTML specification states
The elements used to create controls generally appear inside a FORM
element, but may also appear outside of a FORM element declaration
when they are used to build user interfaces. This is discussed in the
section on intrinsic events. Note that controls outside a form cannot
be successful controls.
A <input> element for submit is a control. Therefore, if it appears outside a <form>, as you currently have it, clicking it won't do anything.
Nest your <input> elements (and whatever other display elements) within a <form> which specifies the action and method to use to submit your data.
You should add
<body><form action="/clientinformationservlet" method="POST">
....
</form></body>
inside the body.
If you want to submit then you should have a <form> in your htmml
e.g.
<form name="input" action="/clientinformationservlet" method="POST">
// your inputs
</form>
This is my web servlet. its first job is to retrieve from the db a list of countries and print out in a select form element. for this point everything works. When I click the submit button in the form, I call the servlet through the action="/submit". Let suppose that I don't insert any username then when I submit the form. the validateSignUpForm return `true. Instead to return to signup page, I am in submit page. I don't understand. When the validationErrorFlag is true I should come back to signup page instead to be in submit page again. Where is the error?
#WebServlet(name = "SignUpServlet", urlPatterns =
{
"/signup"
})
public class SignUpServlet extends HttpServlet
{
#EJB
private UtilBeanInterface utilBean;
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
request.setAttribute("CountriesList", utilBean.getContriesList());
request.getRequestDispatcher("/WEB-INF/view/signup.jsp").forward(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
String confirm_password = request.getParameter("confirm_password");
String email = request.getParameter("email");
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String address = request.getParameter("address");
String city = request.getParameter("city");
String zipcode = request.getParameter("zip_code");
String country = request.getParameter("country");
String homenumber_code = request.getParameter("homenumber_code");
String homenumber = request.getParameter("homenumber");
String mobilenumber_code = request.getParameter("mobilenumber_code");
String mobilenumber = request.getParameter("mobilenumber");
boolean validationErrorFlag = false;
validationErrorFlag = utilBean.validateSignUpForm(username,
password,
confirm_password,
email,
name,
surname,
address,
city,
zipcode,
country,
homenumber_code,
homenumber,
mobilenumber_code,
mobilenumber,
request);
if(validationErrorFlag == true)
{
doGet(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo()
{
return "Short description";
}
}
JSP PAGE
<article class="container_12">
<section id="signupform" class="grid_5">
<h4>Registrazione membri</h4>
<p>(*) Campi richiesti</p>
<h6>I tuoi dati d'accesso su VolaConNoi.it</h6>
<form action="submit" method="POST">
<div>
<label>Username* <span class="advice">(max 16 caratteri)</span></label>
<input type="text" name="username" autofocus>
<c:if test="${!empty usernameInvalid}">
<p class="errorSignUp">Errore: inserisci un username valido</p>
</c:if>
<c:if test="${!empty usernameAlreadyExist}">
<p class="errorSignUp">Errore: l'username è già in uso</p>
</c:if>
</div>
<div>
<label>Password*</label>
<input type="password" name="password">
</div>
<div>
<label>Conferma Password*</label>
<input type="password" name="confirm_password">
</div>
<div>
<label>E-mail*</label>
<input type="email" name="email">
</div>
<br/>
<h6>Dati Personali</h6>
<div>
<label>Nome*</label>
<input type="text" name="name">
</div>
<div>
<label>Cognome/i*</label>
<input type="text" name="surname">
</div>
<div>
<label>Indirizzo*</label>
<input type="text" name="address">
</div>
<div>
<label>Città*</label>
<input type="text" name="city">
</div>
<div>
<label>CAP*</label>
<input type="text" name="zip_code">
</div>
<div>
<label>Paese*</label>
<select name="country">
<c:forEach items="${CountriesList}" var="country">
<option value="${country.iso}">${country.nicename}</option>
</c:forEach>
</select>
</div>
<div>
<label>Fisso</label>
<select name="homenumber_code">
<c:forEach items="${CountriesList}" var="country">
<option value="${country.phonecode}">${country.nicename} (+${country.phonecode})</option>
</c:forEach>
<input type="text" name="homenumber">
</select>
</div>
<div>
<label>Mobile*</label>
<select name="mobilenumber_code">
<c:forEach items="${CountriesList}" var="country">
<option value="${country.phonecode}">${country.nicename} (+${country.phonecode})</option>
</c:forEach>
</select>
<input type="text" name="mobilenumber">
</div>
<div>
<input type="submit" value="Registrati"/>
</div>
</form>
<div id="signupfooter"></div>
</section>
</article>
Compare:
#WebServlet(name = "MainControllerServlet",
loadOnStartup = 1,
urlPatterns = {"/signup",
"/submit"})
with:
String url = "/WEB-INF/view" + userPath + ".jsp";
Even if userPath = "/signup"; you'll never get to the signup servlet, because you appeneded that ".jsp" in there.
Also, if you ever did get to /signup it looks like it would be an infinite loop forwarding to itself over and over.
BTW, it would probably be a lot simpler to actually make separate servlets for each different operation than to double up on them and do this kind of string manipulation.
This question already has an answer here:
HTTP request parameters are not available by request.getAttribute()
(1 answer)
Closed 6 years ago.
Hi all this is how i set value is hidden variable through java script,
function logintosystem(){
document.forms["frmLogon"].funtiontype.value="logon";
document.forms["frmLogon"].submit();
}
and this is what is my jsp page :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
String path = "", userName = "", message = "", userType = "";
path = request.getContextPath();
if(request.getAttribute("message")!=null) message =(String)request.getAttribute("message");
%>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="ACCT"/>
<meta name="keywords" content="acct,accesscardcomparision" />
<meta name="author" content="slingmedia" />
<link rel="stylesheet" type="text/css" href="acct.css" title="andreas09" media="screen,projection" />
<title>ACCT</title>
<script>
function logintosystem(){
document.forms["frmLogon"].funtiontype.value="logon";
document.forms["frmLogon"].submit();
}
</script>
</head>
<body>
<div id="container">
<div id="sitename">
<h1>ACCT</h1>
<h2>Access Card data comparision with Leave portal</h2>
</div>
<div id="mainmenu">
<ul>
<%
if (userName.length() > 0 || !userName.equals(null) || !userName.equals("")) {
%>
<li><a href="#" class="current" >Welcome <%=userName%></a></li>
<%}%>
<%
if (userName.length() > 0 && userType.length() > 0) {
%>
<li>Tempcard</li>
<%}%>
<%
if (userType.equals("HR")) {
%>
<li>Report</li>
<%}%>
<%
if (userName.length() > 0 && userType.length() > 0) {
%>
<li>Logout</li>
<%}%>
</ul>
</div>
<div id="wrap">
<div id="content">
<h1>Please Enter your code</h1>
<form name="frmLogon" id="frmLogon" action="LogonServlet" method="post">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr align="center" valign="middle">
<td width="100%" align="center" valign="middle">
<table width="100%" align="left" border="0" cellspacing="0" cellpadding="2" >
<tr>
<td width="5%" align="left"> </td>
<td width="35%" align="right">ACCT Code</td>
<td width="20%"><input type="text" name="acctcode" id="acctcode" class="inputBoxes" /></td>
<td width="15%" align="left"><input type="button" class="submitButton" value="Logon" onclick="logintosystem();"/></td>
<td width="15%"> </td>
<td width="10%" align="center"> </td>
</tr>
<br></br>
</table>
</td>
</tr>
</table>
<input type="hidden" name="funtiontype" id="funtiontype" value=""/>
</form>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#FFFFF0">
<tr>
<td id="message" align="center">
<b><font color="brown" size="3"><%=message%></font></b>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div class="clearingdiv"> </div>
</div>
</div>
<div id="footer">
<p>© 2012 slingmedia | ACCT </p>
</div>
</body>
</html>
and my servlet is :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.slingmeadia.notifier.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author anthony.savarimut
*/
public class LogonServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet LogonServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet LogonServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
String funtiontype = "",acctcode="",pageRedirect="";
if(request.getAttribute("funtiontype")!=null) funtiontype =(String)request.getAttribute("funtiontype");
if(request.getAttribute("acctcode")!=null) acctcode =(String)request.getAttribute("acctcode");
if(funtiontype.equals("logon")){
request.setAttribute("message","Loggedon code is "+acctcode);
pageRedirect="notifier/notifier.jsp";
}else{
request.setAttribute("message","loggedout code is "+acctcode);
pageRedirect="index.jsp";
}
response.sendRedirect(pageRedirect);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
System.out.println("Called logon");
doGet(request,response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
the page is getting submited but the values that i set for hidden variable is not coming in servlet also i have a text box that value also is not coming to servlet when submitting the page.
Kindly help me to find out this.
You should do this:
funtiontype =request.getParameter("funtiontype");
acctcode = request.getParameter("acctcode");
Try this..
function logintosystem(){
document.frmLogon.funtiontype.value="logon";
document.frmLogon.submit();
}
Update:
String funtionType = request.getAttribute("funtiontype") == null ? request.getParameter("funtiontype") : request.getAttribute("funtiontype");
String acctCode = request.getAttribute("acctcode") == null ? request.getParameter("acctcode") : request.getAttribute("acctcode");