I want to create Hang man game, but I need to save the session and the username, but I have problems for pass the username. I wrote the JSP, servlet and Javabean, but after the login my user, in the next view I only have Welcome + NULL. Help me please. thanks for the help.
I don't know how Can I pass the name to the next view.
enter code here
this is the JavaBean(Userdata.java):
public class Userdata {
String userName;
public Userdata() {
}
public Userdata(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
This is the servlet, in this code I need to use a session, but I want to that, in all the time that the user is logging, cans see his/her name
loginServlet.java
public class loginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session = request.getSession();
Userdata = new Userdata(usuari);
if(request.getParameter("username")!=null &&
!request.getParameter("username").trim().equals("") ){
usuari = new Userdata(request.getParameter("username"));
}
if(request.getParameter("logout")!=null){
session.invalidate();
}
request.setAttribute("username", username);
RequestDispatcher view = request.getRequestDispatcher("juego.jsp");
view.forward(request, resp);
}
}
Finally the Views in JSP, The first view is the login
Nom de jugador:
Contrasenya:
And this is the response of servlet -> juego.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Penjat</title>
</head>
<h2>Benvingut</h2>
<%=request.getAttribute("usuari")%>
<div align="center">
<h1>Joc del Penjat</h1>
</div>
<div align="center">
<!--Delaració d'imatges-->
<img src="Imatges/p_JEE_3.png">
</div>
<div align="center">
<!--Declaració de les lletres-->
Lletra:
<input type="text" name="lletra" size="1" maxlength="1">
<br/>
<p>
<input type="hidden" name="id" value=""/>
<input type="hidden" name="vegades_jugades" value=""/>
<input type="hidden" name="pistes" value=""/>
<input type="submit" name="boto_jugar" value="Jugar">
</p>
</div>
First you have to put username in request, in your servlet use request.setAttribute in the following manner
request.setAttribute("username", value);
where value happens to be the object you want to read later.
Use it later in a different servlet/jsp using request.getAttribute as
String value = (String)request.getAttribute("username")
or
<%= request.getAttribute("username")>
Thanks for your help, now I understand, I modificated and now I can get the username.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session = request.getSession();
Userdata usuari = new Userdata();
if(request.getParameter("username")!=null &&
!request.getParameter("username").trim().equals("") ){
usuari = new Userdata(request.getParameter("username"));
}
if(request.getParameter("logout")!=null){
session.invalidate();
}
request.setAttribute("username", usuari);
RequestDispatcher view = request.getRequestDispatcher("juegoOriginal.jsp");
view.forward(request, resp);
}
Related
I have followed many tutorials.
the login page (index.jsp) opens, but when I submit it doesn't redirect (go to welcome page (welcome.jsp)) and gives error 404
im new to using servlets as you can see, any help will be appreciated
login class
#WebServlet(name = "login" ,urlPatterns = "/login")
public class Login extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("index.jsp");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String password = req.getParameter("password");
if (name.equalsIgnoreCase("ahmad") && password.equalsIgnoreCase("ahmad")) {
resp.sendRedirect("welcome.jsp");
} else {
resp.sendRedirect("index.jsp");
}
}
}
index.jsp
<html>
<head>
<title>login</title>
</head>
<body>
<form action = "/login" method = "post">
Name : <input name = "name" type = "text" />
Password : <input name = "password" type = "password" />
<input type = "submit" />
</form>
</body>
</html>
welcome.jsp
<html>
<head>
<title>welcome</title>
</head>
<body>
<p><font color="red">welcome</font></p>
</body>
</html>
Error Description:
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
I'm creating a basic website where you can add products to a database. The problem is when completing the form for adding a product in the JSP file. I'm able to submit the form but no response is retrieved from the servlet. Once the form is submitted the form is empty again. This happens repeatedly unless I force a FormatNumberException to occur. I've been searching but I couldn't find a solution yet.
Thanks in advance for your help.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Ingrese un producto
<hr>
<% if(request.getAttribute("mensaje")!= null){
out.print(request.getAttribute("mensaje"));
}
%>
<form action="IngresarServlet" method="POST">
Descripción: <input type="text" name="descr"/><br>
Precio: <input type="text" name="precio"/><br>
<input type="submit" value="enviar">
</form>
</body>
#WebServlet(name = "IngresarServlet", urlPatterns = {"/IngresarServlet"})
public class IngresarServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String descripcion = request.getParameter("descr");
Double precio = Double.valueOf(request.getParameter("precio"));
Producto p = new Producto(descripcion, precio);
ProductoDAO dao = new ProductoDAO();
try {
dao.insertar(p);
request.setAttribute("mensaje", "El producto se ha insertado correctamente.");
} catch (Exception ex) {
request.setAttribute("mensaje", ex.getMessage());
}
request.getRequestDispatcher("Ingresar.jsp").forward(request, response);
}
}
Don't work servlet to .jsp connection.
I have doPost in servlet:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF8");
getUser(req, resp);
}
private void getUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getParameter("id");
//In future implements database worker this for check
User user = new User(1, "test", "test", "test", new Timestamp(System.currentTimeMillis()));
req.setAttribute("user", user);
req.getRequestDispatcher("user.jsp").forward(req, resp);
}
And user.jsp file which use User object for view on web page:
<h1>User view</h1><br />
<ul>
<% User user = (User) request.getSession().getAttribute("user"); %>
<li>Id: <% user.getId(); %></li>
<li>Name: <% user.getName(); %></li>
<li>Login: <% user.getLogin(); %></li>
<li>Email: <% user.getEmail(); %></li>
<li>Create date: <% user.getCreateAccount(); %></li>
</ul><br />
menu
But it's don't work. On user's web-page all information is empty. All block <ul> don't view. I see only href to menu. And i don't understand why. Please tell me what wrong? Why? How correct it? Thank You!
In Servlet you are putting User object into request but in Jsp you are looking it up from session.
Try this in your JSP:
User user = (User) request.getAttribute("user");
I think that your jsp have some syntax error.
e.g:<% user.getId(); %>. the proper syntax : <%=user.getId()%>.
You can try it:
<% User user = (User) request.getSession().getAttribute("user"); %>
<ul>
<li>Id: <%=user.getId()%></li>
<li>Name: <%=user.getName()%></li>
<li>Login: <%=user.getLogin()%></li>
<li>Email: <%=user.getEmail()%></li>
<li>Create date: <%=user.getCreateAccount()%></li>
</ul><br/>
menu
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.
In my Java web app I have a unique Front Controller which maps all the requests, and various controllers that execute the logic and return a string representing the next page the user is forwarded to.
This works, but when I submit a form with post method, the form action gets appended to the URL in the address bar. For example, if the login method in LoginController returns false (so that nextPage="/index.jsp"), it correctly redirects to that page, but in the address bar I'll have /MyAPP/app/home.jsp anyway. Is there a way to avoid this?
I took a look to the Post/Redirect/Get pattern, but I'd like to figure out how can I implement this without aggressively changing the structure.
#WebServlet("/app/*")
public class FrontController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private Map<String, Controller> controllers = new HashMap<String, Controller>();
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
private void processRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String pathInfo = req.getPathInfo();
String controllerName = pathInfo.substring(pathInfo.lastIndexOf('/'));
Controller c = controllers.get(controllerName);
String resource = c.action(req, resp);
req.getRequestDispatcher(resource).forward(req, resp);
}
#Override
public void init() throws ServletException {
super.init();
controllers.put("/index.jsp", new IndexController());
controllers.put("/home.jsp", new LoginController());
}
}
public class LoginController implements Controller {
private static final String USERNAME_PARAM = "username";
private static final String PASSWORD_PARAM = "password";
private static final String USERBEAN_ATTR = "userBean";
public String action(HttpServletRequest request, HttpServletResponse response) {
String username = request.getParameter(USERNAME_PARAM);
String password = request.getParameter(PASSWORD_PARAM);
boolean result = false;
UserBean userBean = (UserBean)request.getSession().getAttribute(USERBEAN_ATTR);
userBean.setUsername(username);
userBean.setPassword(password);
if (!username.isEmpty() && !password.isEmpty())
result = userBean.doLogin();
String nextPage = result ? "/home.jsp" : "/index.jsp";
if (!result)
request.setAttribute("error", "Login Error");
return nextPage;
}
}
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Welcome!</title>
</head>
<body>
<h1>Welcome</h1>
<form
action="${pageContext.request.contextPath}/app/home.jsp"
method="post">
Username: <input type="text" name="username"> <br>
Password: <input type="text" name="password"> <br> <input
type="submit" value="Log In" />
</form>
<p>${error}</p>
</body>
</html>