I am new to this so I am a little bit green in jsf based applications.I am trying to display the set attribute in dashboard.xhtml page
Here is my servlet class:
public class LoginServlet extends HttpServlet{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
LoginDAO loginService = new LoginDAO();
boolean result = loginService.authenticateUser(username, password);
Users users = loginService.getUserByuserName(username);
if(result == true ){
request.getSession().setAttribute("user", users);
System.out.println("user"+users.getuserName());
response.sendRedirect("dashboard.xhtml");
}
else{
response.sendRedirect("error.jsp");
}
}
}
dashboard.xhtml:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>DASHBOARD</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<h:outputText value="#{user.username)}"/>
</body>
But, it is not displaying anything? What am I missing? Any help will be appreciated. Thank you!
Related
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");
I've an InitializeServlet that creates and instantiates a HttpSession then redirects to a JSP (betFinalize.jsp). Here I can work on my session. When from that JSP I redirect (through a form) to another Servlet, FinalizeServlet I loose my session. I cannot figure out why. Following code.
InitializeServlet.java
public class InitializeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String result = request.getParameter("result");
Bet s = new Bet();
s.setFirstLastName(fName + " " + lName);
s.setResult(result);
s.setMultiplier(calculateMultiplier());
request.getSession(true).setAttribute("bet", s);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/betFinalize.jsp");
rd.forward(request, response);
}
private double calculateMultiplier() {
return 0.8;
}
}
betFinalized.jsp
<%# page import="it.unibo.tw.model.beans.Bet"%>
<%# page import="it.unibo.tw.model.beans.Bets"%>
<%# page session="true"%>
<jsp:useBean id="bet" class="it.unibo.tw.model.beans.Bet" scope="session"></jsp:useBean>
<jsp:useBean id="finalizedBets" class="it.unibo.tw.model.beans.Bets" scope="application"></jsp:useBean>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>Hi, <%= bet.getFirstLastName() %></h1>
<h2>Current bet: <i><%= bet.toString() %></i></h2>
<form action="finalize" method="get">
<input id="import" type="number" name="import" onkeyup="calculateWin()" ><br />
<input id="win" type="text" name="win" readonly ><br />
<input type="submit">
</form>
<hr />
<ul>
<% for(Bet s : finalizedBets.getList()) { %>
<li><%= s.toString() %></li>
<% } %>
</ul>
</body>
<script>
function calculateWin() {
var multiplier = <%= bet.getMultiplier() %>
var imp = document.getElementById("import").value
document.getElementById("win").value = imp * multiplier
}
</script>
</html>
FinalizeServlet.java
public class FinalizeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
double vincita = Double.parseDouble(request.getParameter("win"));
Bet s = (Bet) request.getSession().getAttribute("bet");
if(s != null) {
// NEVER REACH HERE
s.setWin(vincita);
s.setFinalized(true);
Bets scommesseFinalized = (Bets) getServletContext().getAttribute("scommesseFinalized");
scommesseFinalized.getList().add(s);
}
request.getSession().invalidate();
RequestDispatcher rd = getServletContext().getRequestDispatcher("/start.html");
rd.forward(request, response);
}
}
You're trying to get the wrong attribute. When you set the session variable you have:
request.getSession(true).setAttribute("scommessa", s);
When you try to read it:
request.getSession().getAttribute("bet");
it should be:
request.getSession().getAttribute("scommessa");
instead.
Encode the session id in the action of the form as below:
<form action="<%=response.encodeURL("finalize")%>" method="get">
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.
I am trying a simple login page using JSP form and Displaying HomePage through a servlet.I am storing a couple of username and passwords inside a hashmap.I would like to compare the username and password entered by the user with those existing inside the hashmap and display an error message if username or password is wrong.How can I achieve this?
TIA
Login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<center>
<b>LOGIN PAGE</b><br>
</center>
<form name="login" method="post" action="Servlet1">
<center>
USER NAME: <input type="text" name="username">
<br>
<br>
PASSWORD: <input type="password">
<br>
<br>
<input type="submit" value="LOGIN">
</center>
</form>
</body>
Servlet1.java
public class Servlet1 extends HttpServlet{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException{
String username;
String password;
String uname;
String pwd;
username = request.getParameter("username");
password = request.getParameter("password");
PrintWriter out = response.getWriter();
Map<String,String>users = new HashMap<String,String>();
users.put("Sheetal", "sss");
users.put("Raj","rrr");
}
}
public boolean checkAccess(String username,String password){
return password.equals(users.get(username));
}
Retrieve the user's password from the map and check it against the supplied password.
boolean valid = password.equals(users.get(username));
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String args[]) {
Map<String, String> credentials = new HashMap<String, String>();
credentials.put("user", "correctpass");
String inputUsername = "user";
String inputPassword = "correctpass";
String passOnMap = credentials.get(inputUsername);
if (passOnMap != null
&& passOnMap.equals(inputPassword)) {
// correct login
} else {
// wrong user/passw
}
}
}
public class Servlet1 extends HttpServlet{
final Map<String, String> users = new HashMap<>();
#Override
public void init() throws ServletException {
// user name as key and it is unique for every user. password as value.
users.put("user1", "pwd1");
users.put("user2", "pwd2");
users.put("user3", "pwd3");
users.put("user4", "pwd4");
users.put("user5", "pwd5");
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String strUserName = request.getParameter("user1");
String strPassword = request.getParameter("pwd1");
String userpassword = users.get(strUserName);
if (userpassword != null
&& userpassword.equals(strPassword)) {
// login success
} else {
// invalid user
}
}
}
public boolean checkAccess(Map<String, String> users, String username,String password) {
boolean retunValue = Boolean.FALSE;
if (users != null && users.size() > 0 && !username.isEmpty()
&& !password.isEmpty()) {
if (users.get(username) != null) {
if (password.equals(users.get(username)))
retunValue = true;
}
}
return retunValue;
}
I get following error after trying to launch my first servlet... what may be wrong? I am using proper method (get) and the same code works for my friend... is it possible to be tomcat's fault?
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet Ciastko threw exception
java.lang.NullPointerException
DOGET method:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
HttpSession sesja = request.getSession(true);
PrintWriter out = response.getWriter();
String login = request.getParameter("login");
String pass = request.getParameter("pass");
if(login.isEmpty() || pass.isEmpty()){
out.println("Brak sesji lub atrybutu.");
}
if(login.equals("admin") || pass.equals("admin")){
out.println("ADMIN");
}
else{
sesja.setAttribute("login", login);
sesja.setAttribute("pass", pass);
}
}
and here is index.html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tytuł</title>
</head>
<body>
<form action="Ciastko" method="GET">
<p>Login: </p><input name="login" id="login" />
<p>Hasło: </p><input name="pass" id="pass" />
<input type="submit" value="Wyślij!" />
</form>
</body>
</html>
ServletRequest.getParameter
Returns the value of a request parameter as a String, or null if the parameter does not exist.
You're not checking your login/pass for null, which will make isEmpty crash if the parameters are not set.