Passing value to servlet from image - java

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.

Related

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

Java servlet doPost method not working

Edit:
I pointed the post request to /vault/Login but the servlet was on /vault/index and vault/login
when pointing it towards index it worked.
I'm trying to make a login system.
I have an html file which a post method is requested from but the doPost method is never fired when requested.
When the submit button is clicked the url changes with the parameters in it but nothing happens.
Every time the doPost() is executed the first statement writes something to the console but neither does that happen.
public class Login extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
System.out.println("fired");
HttpSession session = request.getSession();
session.setAttribute("loginFailed", false);
RequestDispatcher rd = request.getRequestDispatcher("Login.jsp");
rd.forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("this is another test");
HttpSession session = request.getSession();
String username = (String)session.getAttribute("username");
String password = (String)session.getAttribute("password");
System.out.println(username + " " + password);
boolean succes = false;
if (!"".equals(username) && !"".equals(password)){
try {
succes = Authentication.checkCredentials(username, password);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
switch ((String)session.getAttribute("platform")){
case "browser":
RequestDispatcher rd = request.getRequestDispatcher("Lobby.jsp");
rd.forward(request, response);
break;
case "desktop":
int id = Tracker.getIdByUsername(username);
List vaults = (List)VaultManagement.getVaultsByUserId(id);
int[] vaultIds = new int[vaults.size()];
if (vaults.isEmpty()){
vaultIds[0] = -1;
}else{
int x = 0;
for (Object vault : vaults){
Vault v = (Vault)vault;
vaultIds[x] = v.getId();
x++;
}
}
DAL.Entities.Account account = AccountManagement.getAccountByUsername(username);
LoginPackage pack = new LoginPackage(username, password, account.getEmail(), vaultIds);
String json = JSON.dataPackageToJson(pack);
PrintWriter writer = response.getWriter();
writer.print(json);
break;
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Post
<div class="jumbotron" width="10%">
<form id="form" action="/vault/Login.jsp">
<h6>Username:</h6>
<input type="text" class="form-control" id="username" name="username">
<h6>Password:</h6>
<input type="password" class="form-control" id="password" name="password"><br>
<button type="button" onclick="location.href='vault/Register.jsp'" class="btn btn-secondary">Register</button>
<input type="hidden" name="platform" value="browser"/>
<input type="submit" value="Login"/>
</form>
</div>
You forgot to specify the method attribute to be post:
<form id="form" action="/vault/Login.jsp" method="post">
<!-- Here ---------------------------------^ -->

httpservlet parameter are null [duplicate]

This question already has answers here:
Http Servlet request lose params from POST body after read it once
(13 answers)
Closed 7 years ago.
I have a jsp page with a form. After submitting it is calling a httpservlet class. But all getParamter() operations are returning null. What am I doing wrong?
JSP
<form action="GatherController" method="post">
<input type='text' name="a"/>
<input type='date' name="b" />
...
<input type="submit" />
</form>
Servlet
#WebServlet(name = "GatherController", urlPatterns = { "/GatherController" })
public class GatherController extends HttpServlet {
...
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("a");
System.out.println(a);
...
}
}
Edit
-I am using Tomcat v8.0
-doPost(...) method is executed, I am getting an output with System.out.println(a); which is null
I have no enough reputation to put comments, so I put it as answer if you don't mind.
Please make sure that you don't call other methods on httpServletRequest before, like getReader() or getInputStream(). You can't access your post parameters after these calls.
<form action="GatherController" method="post"><input type="text" name="a"/>
Please use double quotes,it might work
<html>
<h1>Register</h1><br>
<body>
<form name="userRegistration" method="post">
<input type="text" name="firstname" class="textbox" required/>
<input type="text" name="lastname" class="textbox" required/>
<input type="text" name="email" class="textbox" required/>
</form>
</body>
</html>
servlet code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
HttpSession session = request.getSession(false);
if (//handle your logic) {
out.print("<p style=\"color:red\">Account Created</p>");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
} else {
out.print("<p style=\"color:red\">Error Occured </p>");
RequestDispatcher rd = request.getRequestDispatcher("newuser.jsp");
rd.include(request,response);
}
}

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.

JSP + JavaScript + Servlet Unexpected Results

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?

Categories

Resources