Servlet won't redirect me - java

i have logout button and when its pressed i want to return to main page but it stays on current page. although i receive response in chrome developer tools.
userinfo.jsp
<input type="button" onclick="logout()" value="Logout" class="btn" style="margin-top: 10px; margin-bottom: 10px;"/>
logout.js
function logout(){
$.post("Logout");
}
Logout.java servlet
public class Logout extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = null;
try{
HttpSession sess = request.getSession();
if(sess != null){
sess.invalidate();
}
response.sendRedirect("index.html");

Use RequestDispatcher instead of using sendRedirect
For Example:
RequestDispatcher reqDispatcher = req.getRequestDispatcher("pathToResource/MyPage.jsp");
reqDispatcher.forward(req,res);
Read why and when to use each of RequestDispatcher and sendRedirect

<input type="button" onclick="window.location.href='/path/servlet.java'" value="Logout" class="btn" style="margin-top: 10px; margin-bottom: 10px;"/>

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 ---------------------------------^ -->

I'm having trouble with doGet and doPost methods

PersonalInfoOutput.java servlet is using the doPost method. The user logs in at index.html. From index.html, the request is sent to Login.java servlet.
From there, the user is directed to the PersonalInfoOutput.java servlet.
Now, consider another page called ChangePassAdmin.html. In this html code, one of these goes to PersonalInfoOutput.java. But when I click on it from that page,
I get HTTP Status 405 - HTTP method GET is not supported by this URL.
Can someone please help me as to how I should solve this problem?
I tried changing PersonalInfoOutput.java to doGet instead of doPost but then Login.java servlet will return HTTP Status 405 - HTTP method POST is not supported by this URL. So it seems I need both doGet and doPost for this PersonalInfoOutput.java servlet.
PersonalInfoOutput.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class PersonalInfoOutput extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false);
String employeeid = "";
if(session != null) {
employeeid = (String)session.getAttribute("employeeid");
}
boolean st = false;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps = con.prepareStatement("select employeeID, FirstName, LastName, Admin, DOB, Address, Email, HourlyRate, Gender, ALeaveBalance, SLeaveBalance, ActiveStatus, Role, BSB, BankName, AccNumber, SuperNumber, SuperCompany from payroll_system.employee_info where employeeID = ?");
ps.setString(1, employeeid);
ResultSet rs = ps.executeQuery();
st = rs.next();
if(st){
etc... (rest of the code isn't relevant to question)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel = "stylesheet" type = "text/css" href = "main.css">
<title>Login</title>
</head>
<body>
<form action="Login" method="post">
<h1>
Login
</h1>
<b>Employee ID:</b> <br>
<input type="text"name="employee_id" size="20"><br><br>
<b>Password:</b><br>
<input type="password" name="password" size="20"><br><br>
<input type="submit" value="Login"><br><br>
</form>
</body>
</html>
Login.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String employee_id = request.getParameter("employee_id");
String password = request.getParameter("password");
HttpSession session = request.getSession();
session.setAttribute("employeeid", employee_id);
if(ValidateLogin.user(employee_id, password)) {
RequestDispatcher rs = request.getRequestDispatcher("PersonalInfoOutput");
rs.forward(request, response);
}
else
{
out.print("Employee ID or Password is incorrect. Please try again.");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
ChangePassAdmin.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<link rel = "stylesheet" type = "text/css" href = "main.css">
<link rel = "stylesheet" type = "text/css" href = "sidebar.css">
<title>Change Password</title>
<style>
table { border-collapse: collapse; width: 50%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even){background-color: #f2f2f2}
tr:hover {background-color: #e2f4ff;}
</style>
</head>
<body>
<ul>
<li><a href=PersonalInfoOutput>View Personal Information</a></li>
<li><a href=PersonalInfoOutput>View Expense Claims</a></li>
<li><a href=PersonalInfoOutput>View Payslips</a></li>
<li><a class=active >Change Password</a></li>
<li><a href=PersonalInfoOutput>Maintain Employee Information</a></li>
<li><a href=PersonalInfoOutput>Maintain Tax Information</a></li>
<li><a href=PersonalInfoOutput>Maintain Payroll Items</a></li>
<li><a href=PersonalInfoOutput>Maintain Timesheet</a></li>
<li><a href=PersonalInfoOutput>Maintain Employee Expenses</a></li>
<li><a href=PersonalInfoOutput>Run Payroll</a></li>
<li><a href=PersonalInfoOutput>Generate Reports</a></li>
</ul>
<div style=margin-left:25%;padding:1px;>
</div>
<div id="container">
<h1>Change Password</h1>
<form action ="NewPassword" method = post>
<table border ="1">
<tr>
<td>Existing Password:</td>
<td><input type = "password" name = "oldpassword" size = "20"></td>
</tr>
<tr>
<td>New Password:</td>
<td><input type = "password" name = "newpassword" size = "20"></td>
</tr>
<tr>
<td>Confirm New Password</td>
<td><input type = "password" name = "confirmpassword" size = "20"></td>
</tr>
</table>
<br>
<br>
<input type = "submit" value = "Update Password">
</form>.
</div>
</body>
</html>
In ChangePassAdmin.html, double quotes around post are missing.
Both of your Servlet should have doPost method as your form is using "post" action.
<form action ="NewPassword" method = "post">
Additionally you will need two methods in this case. Add both doGet and doPost in your servlet. doPost will be used by form and doGet by links. By default all links are GET.
You can do it like:
Edit:
public class PersonalInfoOutput extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Your servlets code should be here
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
doPost() method to receive form based request. doGet() method to receive href based request. But in both cases processRequest() method will be called.
I believe the problem is that you're using the PersonalInfoOutput servlet in two ways:
Forwarding from Login servlet, which by forwarding keeps using POST method
And by href from the HTML, which by default uses method GET
Wouldn't a possible solution be for you to refactor your code, which would be good for you to do anyway, so that you implement both doGet() and doPost() in the PersonalInfoOutput servlet without repeating a lot of code?
Or you could refactor the employee database retrieval to an external class, that would be called from Login without the need to redirect from one servlet to another, and implement GET instead of POST in PersonalInfoOutput.

Invoking a JSP Page from a Servlet

Can anyone tell me if there exists any method other than RequestDispatcher, to invoke a jsp page from my servlet? Because i have tried a lot without success.
My servlet works normally and recovred all the data from jsp. All that I need is to be redirected to another page when the user enters the username and password correctly.
my code :
first my servlet " login"
protected void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String user = request.getParameter("username");
String pass = request.getParameter("password");
System.out.println(" le user est "+user+ " le mot de passe est " + pass);
String query = "SELECT * FROM users WHERE username = '"+user+"' and password='"+pass+"'";
dbconn = new DBAccess();
Connection conn = dbconn.connect();
stmt = conn.createStatement();
ResultSet res = stmt.executeQuery(query);
if(res.next()){
ServletContext sc = this.getServletContext();
RequestDispatcher rd =sc.getRequestDispatcher( "inscreption.jsp");
rd.forward(request, response);
System.out.println(" il existe");
}else {
ServletContext sc = this.getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("index.jsp");
// RequestDispatcher rd =request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
System.out.println("not found");
}
} catch (SQLException ex) {
Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
System.out.close();
}
}}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
/* #Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
my jsp that i would to be redirected for
<html>
<head>
<!--local jquery-->
<script src="jQuerys/jquery-1.9.1.min.js"></script>
<script src="jQuerys/jquery.mobile-1.3.1.min.js"></script>
<link rel ="stylesheet" type="text/css" href="css/jqueryMobile-1.3.1.css"/>
<!--/local jquery-->
</head>
<body>
<div data-role="page" id="inscription">
<div data-role="header" data-theme="b">
<center>CERIST</center>
</div>
<form id="insc" method="post" action="login">
<div data-role="content">
<div data-role="fieldcontain">
<label for="identifiant">Identifiant </label>
<input type="text" id="identifiant"/>
</div>
<div data-role="fieldcontain">
<label for="password1">Mot de passe </label>
<input type="password" id="password1"/>
</div>
<div data-role="fieldcontain">
<label for="password2">Confirmation</label>
<input type="password" id="password2"/>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Vous ĂȘtes :</legend>
<input type="radio" name="profil" id="radio-choice-1" value="Candidat" />
<label for="radio-choice-1">Utilisateur</label>
<input type="radio" name="profil" id="radio-choice-2" value="Entreprise" />
<label for="radio-choice-2">Administrateur</label>
</fieldset>
</div>
<br/>
S'inscrire
</form>
</div>
</div>
</body>
</html>
index.jsp :
<form action="Myservlet" method="post"><br>
User name`<`input type="text" name="username"`>`<br>
Password `<`input type="password" name="password"><br>
`<`input type="submit" value="Submit" `>`
</form>
Myservlet.java:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("Oppos!!!");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = request.getParameter("username");
String pass = request.getParameter("password");
RequestDispatcher rd;
if (user.equals("username") && pass.equals("password")) {
rd = request.getRequestDispatcher("/inscreption.jsp");
rd.forward(request, response);
} else {
rd = request.getRequestDispatcher("/wrong.jsp");
rd.forward(request, response);
}
}
You can create more than two pages where you want to dispatch your request so here I created more than two jsp page names: right.jsp and wrong.jsp. If the username and password is correct then it frowards to right.jsp page if it's wrong, it frowards the request to wrong.jsp page.

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

Categories

Resources