404 error in servlets [duplicate] - java

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
It's my first day trying servlets. It's just a simple login function, but I get an error that doesn't explain what I'm doing wrong. It just says
404: The requested resource is not available.
Here's my servlet:
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String key = "ole";
String username = request.getParameter("username");
String password = request.getParameter("password");
response.sendRedirect("NewFile.jsp");
if (session.getAttribute(username).equals(key)
&& session.getAttribute(password).equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
And here's my login page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login page</title>
</head>
<body>
Enter username and password below.
<form method=get action="hej">
<input type="text" user="username" /> <input type="password"
user="password" /> <input type="submit" value="Login" />
</form>
</body>
</html>
There is a file called secret.jsp as well, but there's nothing interesting in there. I don't understand why it's returning 404. When I have remove the if statement it works... only then, there's not much function.

As you say it works without IF-ELSE then I guess your web.xml entry is correct.
First change this to
<input type="password" user="password" />
this
<input type="password" name="password" />
input tag does not have any user attribute , it's name.
Next mistake is , you are using session.getAttribute to access parameters that you have not set, yet.
Your code should be
if (username.equals(key)
&& password.equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
session.getAttribute can only be used when you have in your code session.setAttribute
example session.setAttribute("username","ole");session.setAttribute("password","ole");.
Then only you could get a value with session.getAttribute("username") OR session.getAttribute("password"). But right now it only returns NULL. So code won`t work.
You could add this code in your existing code and it will work.
session.setAttribute(username,username);
session.setAttribute(password,password);
Your complete code should be
String username = request.getParameter("username");
String password = request.getParameter("password");
session.setAttribute(username,username);
session.setAttribute(password,password);
//response.sendRedirect("NewFile.jsp");
if (session.getAttribute(username).equals(key)
&& session.getAttribute(password).equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}

Replace user="... by name="... in your HTML and it will work.

Replace user="... by name="... in your HTML and it will work. NullPointerException is thrown because because of the wrong HTML the request parameters are NULL and these are used for the session lookup.

Related

How to configure the return in AMP-Access?

In theory when the AMPByExample server receives the POST request
from the login page, if the credentials are correct, it will redirects
the request to the URL of returnURL and the parameter is added
success = true. Once done, the AMP execution time can finally
authorize the page.
The login page is the following:
login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<form method="post" action="loginauthorization">
Correo Electronico: <input type="text" name="correo"><br>
Contraseña: <input type="password" name="clave"><br>
<input name="returnurl" type="hidden" value="https://cdn.ampproject.org/v0/amp-login-done-0.1.html?url=https%3A%2F%2Fampbyexample.com%2Fplayground%2F">
<input type="submit" value="Ingresar">
</form>
</body>
</html>
As you can see, in the returnurl it is the same login URL ofAmpByExample and it does not work.
I already tried to make my own url in the following way:
<input name="returnurl" type="hidden" value="https://cdn.ampproject.org/v0/amp-login-done-0.1.html?url=http%3A%2F%2Flocalhost%3A8084%2Fmypage%2Fpanel.jsp">
And it doesn't work either.
In the servlet loginauthorization.java I receive thatreturnurl and I add the # success = true (supposedly I must verify username and password, but I want to make it work first).
loginauthorization.java:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class loginauthorization extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html");
//I get the parameters
String email = request.getParameter("correo");
String password = request.getParameter("clave");
String url = request.getParameter("pageurl");
int ridini = url.indexOf("rid=")+4;
int ridend = url.indexOf("&url=");
String rid = url.substring(ridini, ridend);
String returnurl = request.getParameter("returnurl");
//assuming that the username and password are correct, add to the returnurl success true
returnurl= returnurl + "#success=true";
//create a session
HttpSession session=request.getSession();
session.setAttribute("umail",email);
session.setAttribute("upass",password);
session.setAttribute("rid",rid);
session.setAttribute("returnurl",returnurl);
//redirect after login with the success = true
response.sendRedirect(returnurl);
}catch(Exception exp){
System.out.println(exp);
}
}
}
The configuration of the panel is as follows:
panel.jsp
<script id="amp-access" type="application/json">
{
"authorization": "http://localhost:8084/mypage/jsonauthorization",
"noPingback": "true",
"login": {
"sign-in": "/mypage/login.jsp?rid=READER_ID&url=CANONICAL_URL&return=RETURN_URL",
"sign-out": "/mypage/endsession"
},
"authorizationFallbackResponse": {
"loggedIn": false
},
"type": "server"
}
</script>
The jsonauthorization prints{"loggedIn": true}or{"loggedIn": false}:
jsonauthorization.java
import java.io.*;
import javax.servlet.http.*;
public class jsonauthorization extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("application/json");
response.setHeader("AMP-Access-Control-Allow-Source-Origin", "http://localhost:8084/mypage");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
if(session != null){
String email=(String)session.getAttribute("umail");
if(email==null){
session.invalidate();
pwriter.print("{\"loggedIn\":false}");
}else{
String rid;
rid = (String) session.getAttribute("rid");
Cookie AmpCookie = new Cookie("authorized",rid);
AmpCookie.setPath("/");
AmpCookie.setDomain("/mypage");
response.addCookie(AmpCookie);
pwriter.print("{\"loggedIn\":true}");
}
}else{
pwriter.print("{\"loggedIn\":false}");
}
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
I appreciate the answers, if the error is not in the returnurl please tell me where :P
I am also trying to figure out AMP integration with login/registration. Not sure if this will help, but I found that the return url is automatically added to the url param, so you don't necessarily have to add it to your sign-in url within your initialization json object.
I figured out, it is not necessary to configure the return url. Simply add the hidden input inside the html in order to close the login window and read the json url approving the login.
Just like this:
<input name = "returnurl" type = "hidden" value = "https://cdn.ampproject.org/v0/amp-login-done-0.1.html">
Then, if the json url aproves the login it will works.
Actually the code is fine, the problem was in the json generator file.
CORS problems. Is necessary to set the header "AMP-Access-Control-Allow-Source-Origin" right.

Update password from database using JavaServlet

Hello, im working on a project in the university, and im stuck on an error.
Im working on a mypage feature, where you can update your old password, when you are looged in. The problem is that ChangepasswordServlet is not doing what it is supposed to do.
Here you can see my servlet, the problem is probably somewhere in the IF sentence. (Manager=Entitymanager)
#WebServlet(name = "ChangePasswordServlet", urlPatterns = {"/ChangePassword"})
public class ChangePasswordServlet extends HttpServlet {
#EJB
UserManagerLocal manager;
private void changePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
String loggedInUsersUsername = request.getRemoteUser();
/* PrintWriter writer = response.getWriter(); */
User userFromTheDB = manager.getUser(loggedInUsersUsername);
String oldPasswordFromDB = userFromTheDB.getPassword();
String oldPasswordFromForm = (String) request.getAttribute("theOldPW");
;
String newPasswordFromForm = (String) request.getAttribute("theNewPW");
String newPasswordToCheckFromForm = (String) request.getAttribute("theNewPWCheck");
try {
if (oldPasswordFromDB.toLowerCase().equals(oldPasswordFromForm.toLowerCase()) && newPasswordFromForm.toLowerCase().equals(newPasswordToCheckFromForm.toLowerCase())) {
userFromTheDB.setPassword(newPasswordFromForm);
manager.updateUser(userFromTheDB);
response.sendRedirect("/Slit/MyPage/PasswordSucsess.jsp");
} else {
response.sendRedirect("Slit/Error/error.jsp");
}
}
catch (NullPointerException en) {
PrintWriter print = response.getWriter();
print.println("nullpointeryes");
print.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
#Override
protected void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
so
Here is my JSP with the form
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<title>Her kan du endre ditt nåværende passord</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="/Slit/Templates/CSS/MainPageTemplate.css">
</head>
<body>
<title>Slit</title>
<div>
<div class="form">
<form method="post" action="/Slit/ChangePassword">
<input type="Password" name="theOldPW" placeholder="Gammelt
Password"/>
<input type="Password" name ="theNewPW" placeholder="Nytt
Password"/>
<input type="Password" name ="theNewPWCheck" placeholder=" Nytt
Password på nytt"/>
<input type="submit" name="ByttePassord" value="Trykk her for å bytte
passord!"/>
</form>
</div>
</div>
</body>
</html>
</head>
<body>
</body>
So im getting nullpointer after i have filled in the form with the old and the new password.
If im running the code now, im getting the "nullpointeryes" error.
Edit:
This is the console error after filling in the form:
12:39:37,194 INFO [stdout] (default task-12) Hibernate: select
user0_.username as username2_3_0_, user0_.fName as fName3_3_0_, user0_.lName
as lName4_3_0_, user0_.password as password5_3_0_, user0_.DTYPE as
DTYPE1_3_0_ from User user0_ where user0_.username=?
Thanks for any answers
After hours i figured that i used get.attribute instead of parameter :/
String newPasswordFromForm = (String) request.getParameter("theNewPW");
String newPasswordToCheckFromForm = (String)
request.Paramter("theNewPWCheck");

RequestDispatcher Showing Page's source code Java Servlet

Everything is working fine else why RequestDispatcher showing source code of page?
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String uName=req.getParameter("uEmail");
String uPass=req.getParameter("uPass");
try{
DBConnection con=new DBConnection();
if(con.login(uName, uPass)){
HttpSession on = req.getSession();
on.setAttribute("u_id", uName);
res.sendRedirect("dashboard.jsp");
}
else{
RequestDispatcher dis= getServletContext().getRequestDispatcher("/login.jsp");
PrintWriter write = res.getWriter();
write.println("Wrong Username or Passowrd");
dis.include(req, res);
}
}catch(ClassNotFoundException | SQLException e){}
}
}
Page redirecting fine to given url /login.jsp and also showing the error message, but why as source code?
Wrong Username or Passowrd
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="LoginServlet" method="POST" />
<input type="text" name="uEmail" />
<br /><br />
<input type="text" name="uPass" />
<br /><br />
<input type="Submit" name="Register" value="Register" />
<br /><br />
</form>
</body>
</html>
direct link to login.jsp works fine.
from http://docs.oracle.com/javaee/6/api/javax/servlet/RequestDispatcher.html#include(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
The include method of Request Dispatcher gets the content of the resource that why you are getting the source code in browser.
I think what you want to do is forward the request to login.jsp so use forward method of request dispatcher.
As #JBNizet mentioned in his comment due to your message from Servlet, HTML is going to be invalid.
before dis.include(req,res);
add this line res.setContentType("text/html); it
I was facing the same issue when I used RequestDispacther method and try to return and String massage along with html page then i have found you have to put some kind of tag to the String massage like then use include method
so if my code was
out.println("Terms & Condition not accepted");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
i changed it to "
out.println("<h1>Terms & Conditions not accepted </h1>")
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
"
You need to set the content type of the response.
Add the below line in your doPost method.
response.setContentType("text/html;charset=UTF-8");
Hope it works for you!!

JSP - validate form and show errors in same jsp [duplicate]

This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 3 years ago.
I have a JSP which will let a user register for an account at my website. If the user submits wrong or illegal info into the JSP, then I want to return the same JSP with an appropriate error message next to/above each wrongly filled (form) fields.
If possible, highlight the wrongly filled form field - this feature is not necessary though.
I have given a sample below to show what I need. I understand that the sample must be using something like javascript, but I don't know all that client side scripting. I only want to use JSP to do it. As I said, I want to sort of return the JSP form to the user after marking all the mistakes and how to correct them.
How do I do this ? I only need some initial direction. I will make the code myself and post it here later.
Thanks.
EDIT - I don't want the drop down box. I don't want red borders around wrongly entered fields. I only want to display the error messages (in red color) next to the relevant fields.
Here is some sample code -
<%# page language="java" contentType="blah..." pageEncoding="blah..."%>
<!DOCTYPE html PUBLIC "blah...">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user"><br>
password : <input type="password" name="pwd">
</form>
</body>
</html>
RegServlet -
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static String okUser = "loser";
public RegServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(user.equalsIgnoreCase(okUser) == false){
//Do something MAGICAL to set an error next to username field of Form.jsp, then forward.
RequestDispatcher view = request.getRequestDispatcher("/jsp/Form.jsp");
view.forward(request, response);
}
}
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax Validation</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- or download to a directory -->
<!-- <script src="js/jquery-1.9.1.js"></script> -->
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#user').change(function() {
var userName = jQuery(this).val();
jQuery.ajax({
type : 'GET',
url : 'AjaxUserCheck',
data : {user:userName},
dataType : 'html',
success : function(data) {
if(jQuery.trim(data)=='1')
{
jQuery("#userLabel").html("Sorry! username is taken");
//write other stuff: border color ...
}
else if(jQuery.trim(data)=='0')
jQuery("#userLabel").html("user name available");
else
alert(data); //possible error
},
error : function(xhr,status,error){
console.log(xhr);
alert(status);
}
});
});
});
</script>
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user" id="user">
<label id="userLabel"></label>
<br>
password : <input type="password" name="pwd">
</form>
</body>
</html>
---------Servlet------
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
//if(dao.isUserExist(user)){
if(user.equals("java")){ // check for db if userid exists in DB print '1' else '0'
out.print("1");
}
else
out.print("0");
have the page post to itself, like this login.jsp fragment:
<div class="error">
<%
String usrName = "" + request.getParameter("username");
String usrPass = "" + request.getParameter("password");
if (isValid(usrName,usrPass){
openUserSession(usrName); //here you open a session and set the user, if the session doesn't have an user redirect to login.jsp
response.sendRedirect("index.jsp"); //user ok redirect to index (or previous page)
} else {
out.print("Invaid user or password");
}
%>
</div>
<form action="login.jsp" method="POST"> <!-- login.jsp post to itself -->
<input type="text" name="username" id="username"/>
<input type="password" name="password" />
<input type="submit" value="login" name="login" />
<input type="submit" value="register" name="register" />
</form>

Reveal / know / get the sending page using request or session in servlet

I have jsp page (say, source.jsp) with form:
<html>
<head>
<body>
<form action="Servlet123" method="POST">
// form fileds ...
</form>
</body>
</head>
</html>
And the required doPost in servlet -
#WebServlet("/Servlet123")
public class Servlet123 extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//use with requset...
}
}
How can I get the page (in this case - source.jsp) sending the request to this servlet? Is there a method in request/session?
Use passing parameter in a request through a hidden field:
In your jsp page:
<form action="Servlet123" method="post">
<input type="hidden" name="namePage" value="sourcePage" />
</form>
In your servlet:
String namePage = request.getParameter("namePage");
String referer = request.getHeader("referer");
But read Alternative to "Referer" Header
(especially BalusC's answer).

Categories