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");
Related
I have a simple servlet 'Login' deployed in Server A tomcat
Index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
</body>
Validate.java
doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("Welcome");
}
else
{
PrintWriter out = response.getWriter();
out.println("Wrong password!!!");
}
}
Welcome.Java
doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String)session.getAttribute("user");
out.println("Welcome"+user);
}
This set up works fine.
Now what I want to try is to create another Servlet 'Validate' which would be deployed in another Server B tomcat with a different IP. I need to pass the parameters from Servlet 'Login' to Servlet 'Validate' which will then validate the credentials and send back the validation message, a String, to the Servlet 'Login' which will then display the same on its index.jsp page.
Please provide some help on this. Let me also add that I have no prior experience in servlets.
I need a filter that will record a login attempt and then print to a jsp that there was a login attempt. I'm a but puzzled in how to do this? I'm a newbie so please be patient. Thank you.
Here is my index.html
<html>
<head>
<title>First Web App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="LoginServlet" method="post">
<div><h2>My First Webapp</h2></div>
<p></p>
<div><h3>User Name:<input type="text" name="username" id="username"></h3></div>
<p></p>
<div><h3>Password:<input type="password" name="password" id="password"></h3></div>
<p></p>
<input type="submit" value="login" id="loginsubmit"/>
</form>
</body>
Here is my servlet
public class LoginServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
if (username.equalsIgnoreCase("admin") && password.equalsIgnoreCase("password")) {
HttpSession session=request.getSession();
session.setAttribute("username", username);
RequestDispatcher rd=request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
else
{
response.sendError(response.SC_BAD_REQUEST, "Denied Access");
}
}
finally
{
out.close();
}
}
Here is a very small and pitiful start to my filter, I'm just stalling on this part:
public class AuditFilter implements Filter {
public AuditFilter() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String audit = request.getParameter("audit");
if (audit !=
}
Any guidance would be very helpful.
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>
I wrote the following form and servlet , hoping that the servlet would return the value of the text field from the form , but it returns null instead. What should be corrected ?
<html>
<head>
<title>Simple form</title>
</head>
<body>
<form method="post" action="theServlet">
<input type="text" id="userName"/>
<input type="submit" value="Post"/>
</form>
</body>
</html>
public class theServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username=request.getParameter("userName");
response.setContentType("text/html");
PrintWriter writer=response.getWriter();
writer.println("<html>");
writer.println("userName = "+ username);
writer.println("</html>");
}
}
You should use name attribute instead of id to send parameters to the server.
<input type="text" id="userName" name="username" />
index.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<h1>
<font color=orange ><center> Authentification </font> </h1>
<form name"loginform" action="login" method="post">
<p> Enter your ID: <input type="text" name="id"><br>
<input type="submit">
</form>
</body>
</html>
Authentification.java:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
int IdUser = Integer.valueOf(request.getParameter("id"));
session.setAttribute("ide", IdUser);
try {
if(auth.authen(IdUser)){
session=request.getSession();
request.getRequestDispatcher("acceuil.jsp").forward(request, response);
System.out.println("found");}
else{
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println("not found");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
acceuil.jsp: Where I want to display IdUser
<% Integer idUser = (Integer)session.getAttribute("IdUser"); %>
<!--some HTML code-->
<div id="corps"><h1>
Welcome <%=idUser%> </h1></div>
So what I want to have is after the user enter's his id and if the id is found in the database(this operation works) there would be a message ncluding the user's id. the get.Attribute doesn't return a value instead in my page the result is "Welcome NULL".
You saved the attribute in session with name "ide" but try to recover it with name "IdUser". Use the same attribute name in both places.