JSP + JavaScript + Servlet Unexpected Results - java

I have a form on a jsp which calls a javascript function which latter calls a servlet. However the code mention below works once in while and when the code does reach the servlet the parameters return null. Also its really bizarre but it jumps between The doGet and doPost method even though i specify "POST". Can someone assist me with the correction.
JAVASCRIPT:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$().ready(function() {
$('.my_button').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "POST",
data: dataf,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});
</script>
JSP FORM:
<form id="newsletter" method="POST">
<div class="wrapper">
<div class="bg">
Email:<input type="text" id="email">
</div>
<div class="bg">
Password:<input type="password" id="password">
</div>
<button class="my_button" name="login" >login</button>
</div>
</form>
SERVLET "loginServlet":
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
String email = request.getParameter("email");
String password = request.getParameter("password");
String loginResult = login(email,password);
System.out.println("EMAIL:" +email);
System.out.println("PASSWORD:" +password);
System.out.println("IM INSIDE GET!!!!");
response.getWriter().write(loginResult);
}
/**
* 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);
String email = request.getParameter("email");
String password = request.getParameter("password");
String loginResult = login(email,password);
System.out.println("IM INSIDE POST!!!!");
response.getWriter().write(loginResult);
}
If any other information is required please let me know. Thank you for the help in advance.

I Found the solution through this site, thank you for the help everyone!
http://coderlearner.com/Java_Servlet_doGet_Ajax_JSON#LoginJSON.java

Three points here,
In the html, your button will end up submitting your form to the current url (Refer https://stackoverflow.com/a/9824845/1304559)
Set type="button" to change that. type="submit" is the default (as specified by the HTML recommendation).
In the html, <form>, add onsubmit="return false". Just to be entirely safe that it does not post back to the current url.
One question - what does processRequest do in your servlet code?

Related

Redirect to new page

I I have a form in my "login.html" and after I click the "login" button, this form will be submitted to my java back-end code. However, I don't know how to redirect my login page to the new page.
In the following code:
<script>
$(function() {
$('#ff').form({
url: "LoginServlet",
success:function(data){
$.messager.alert(data);
}
});
});
</script>
In the success part, my redirected page will show in this message window. But I want it jump to the page returned by the servlet.
This is my login.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
$(function() {
$('#ff').form({
url: "LoginServlet",
success:function(data){
$.messager.alert(data);
}
});
});
</script>
</head>
<body>
<form id="ff" role="form" method="post">
<div>
<h1>User Login</h1>
</div>
<div>
<input id="username" name="username" class="easyui-textbox" data-options="iconCls:'icon-man',iconWidth:30,iconAlign:'left',prompt:'Username'" style="width:100%;height:35px;" />
</div>
<div>
<input id="password" name="password" class="easyui-passwordbox" data-options="iconWidth:30,iconAlign:'left',prompt:'Password'" style="width:100%;height:35px;" />
</div>
<div>
Submit
</div>
<div>
<div style="display:inline;">
Register
</div>
</div>
</form>
</body>
</html>
This is my java servlet code:
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
IUserService userService = new UserServiceImpl();
User user = userService.login(username, password).get(0);
if (user != null) {
response.sendRedirect(request.getContextPath() + "/index.jsp");
} else {
}
}
}
You could try removing the Javascript function and calling directly the jsp using the form action.
So I would remove the following part
<script>
$(function() {
$('#ff').form({
url: "LoginServlet",
success:function(data){
$.messager.alert(data);
}
});
});
</script>
This part here needs to be removed because of the structure that you have. Most projects with JSP have this structure that you have.
You want in first step to take all the form parameters and to visit the url .../LoginServlet.
Then as you have structured your servlet it makes the authentication and if successful it sends a message to your browser and says: Please browser keep these headers in the http message but please visit another URL (index.jsp) to see what you wait for.
As you can see it's up to the client (aka browser) to move between different URL in order to be served.
That is why that simple Javascript function does not work as expected.
So a simple solution would be to make the call directly in the form action
<body>
<form id="ff" role="form" method="post" action="/LoginServlet">
....
If the authentication was not successful then I would serve an error page from my servlet.
if (user != null) {
response.sendRedirect(request.getContextPath() + "/index.jsp");
} else {
response.sendRedirect(request.getContextPath() + "/error.html");
}

Servelt Page doesn't Redirect to second Page using Servlet

I am a beginner of servlet jsp. I am creating a simple login form if the login successful page redirects to the second servlet along with the username. but it doesn't work it shows the error java.lang.IllegalArgumentException: Path second does not start with a "/" character
what I tried so far I attached below.
Form
<div class="row">
<form method="POST" action="login">
<div class="form-group">
<label>Username</label>
<input type="text" id="uname" name="uname" placeholder="uname" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="pword" name="pword" placeholder="pword" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-success">
</div>
</form>
</div>
Login Servlet Page
#WebServlet("/login")
public class login extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String uname = request.getParameter("uname");
String pass = request.getParameter("pword");
if(uname.equals("John") && pass.equals("123"))
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
session.putValue("username", uname);
ServletContext context=getServletContext();
RequestDispatcher rd=context.getRequestDispatcher("second");
rd.forward(request, response);
}
}
Second Servlet Page
#WebServlet("/second")
public class second extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
String uname = (String)session.getValue("uname");
out.println("User Name is " + uname);
}
There are some big differences between redirect and forward . This article will help you to understand better your problem.
Some things to keep in mind from the article :
FORWARD
1) Request and response objects will remain the same object after forwarding. Request-scope objects will be still available (this is why if you try to add the "/" you get the 405 status - it will try to forward you to the "/second" servlet but the only request overridden is GET)
REDIRECT
1) The request is redirected to a different resource
2) A new request is created
So instead of using rd.forward I would suggest you to use the sendRedirect() method from HttpServletResponse class.
response.sendRedirect(request.getContextPath() + "/second");
AND the correct way to get the session username attribute is this:
String uname = (String) session.getValue("username");
Otherwise it will try to look after uname key which is not set. The uname was only a value mapped to the username key ( session.putValue("username",uname);
this exception indicates, path does not start with a "/".
try below instead.
RequestDispatcher rd=context.getRequestDispatcher(request.getContextPath() +"/second");

Passing value to servlet from image

From JSP I have
..
<form action="TestMartController" method="post">
<input type="hidden" value="math">
<input type="image" src="<%=request.getContextPath()%>/css/categories/math.jpg">
</form>
..
In my servlet I have
...
private static final String MATH = "WEB-INF/jsp/math.jsp";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward = null;
String action=request.getParameter("action");
if(action.equals("math")){
forward = MATH;
flag = 1;
}
RequestDispatcher rd = request.getRequestDispatcher(forward);
rd.forward(request, response);
}
...
When I clicked the image I got null pointer exception. I want to know why it does not pass the value where it should. Since hidden will always get the values to pass.
your input type="hidden" field is missing a name="action" attribute. Thus, the action parameter is null.

getParameters keeps returning null

So, I'm having trouble retrieving information from my the client-side jsp. The javascript executes, and the alert prints, however query becomes null in the java servlet, and null is then written to the logger. I can't seem to figure out why the query is now null.
HTML:
<div id="query">
<div id="querybar">
<form onsubmit="query();return false;" method="get">
<input type="text" id="querytext" placeholder="Run a query" name="querytext">
</form>
<div id="queryimg-container">
<img src="styles/magnifyingglass.png" id="queryimg" alt="" />
</div>
</div>
</div>
JS:
function query() {
$.get('QueryHelper', function(data) {
alert("Somesortofalert");
});
}
Java Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String query = request.getParameter("querytext");
response.setContentType("text/plain");
#SuppressWarnings("resource")
PrintWriter writer = response.getWriter();
sLogger.info(query);
}
Can anyone see anything wrong? I'm super stumped here.
It'll be null because no parameter by that name is being sent with the Ajax request.
Despite being started by an onsubmit event, $.get() doesn't have any automatic knowledge of the <form>. It's up to you to gather or specify any parameters to be included with the request using the data parameter.
$.get('QueryHelper', { querytext: 'foo bar' }, function (res) {
// ...
});
Provided you have a reference to the <form> or its inputs, you can use .serialize() to prepare the fields' names and values as data.
<form onsubmit="query(this); return false;" method="get">
<!-- ^^^^ -->
function query(form) {
// ^^^^
$.get('QueryHelper', $(form).serialize(), function (res) {
// ^^^^^^^^^^^^^^^^^^^
// ...
});
}

Pass GET parameter and resultset to a servlet in Java

I want to pass two values to a servlet from a jsp page. 1- a result set value, 2- a get parameter value.
It should look something like this in jsp page:
SCcalculator.getValue(rs.getString("value1"),request.getParameter("value1"));
on the servlet side how can i receive and manipulate this data in the SCcalculator package? any suggestions please?
In your servlet class use :
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
String s = request.getParameter("value1");
String s1 = request.getParameter("value");
}
in JSP don't do like that, instead do :
<form action="name" method="post"> //here action=name is name of your servlet class name
<input type="text" name="value">
<input type="text" name="value1">
<input type="submit" value="Send">
</form>
Conside this example
<html>
<head>
<title>Demo application</title></head>
<body>
<form id = "form1" method = "GET" action = "../Sample Application">
link1 : <input type = "text" id = "nRequests" name = "nRequests" />
<input type = "submit" name = "submit" id = "submit"/>
</form></body></html>
Now how you servlet will accept the request
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
nRequests = request.getParameter("nRequests");
In this way you can get the value from a HTML page to your servlets.

Categories

Resources