How get and use java object in jsp file from doPost()? - java

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

Related

Submitting a post method doesn't redirect to target page using Servlets

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.

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

JSP & MVC: Passing object from controller to jsp pages

I'm using MVC design pattern in jsp. I can pass an object to a single jsp page but not to other jsp pages(there could be many pages). I want to display userName and password of Teacher class using an Object (or through getters).
public class Teacher {
String userName;
String password;
/*GETTERS AND SETTERS*/
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName;
String password;
userName = request.getParameter("tUserNameTxt");
password = request.getParameter("tPasswordTxt");
Teacher teacher = new Teacher();
teacher.setUserName(userName);
teacher.setPassword(password);
request.setAttribute("teacher", teacher);
RequestDispatcher dispatch;
dispatch = request.getRequestDispatcher("login-success-teacher.jsp");
dispatch.forward(request, response);
}
Data to be displayed on pages:
<body>
<%
Teacher teacher = (Teacher) request.getAttribute("teacher");
session.setAttribute("teacher", teacher);
out.println("Welcome "+ teacher.getUserName());
out.println("Your ID is "+ teacher.getPassword());
%>
<h1>
Click Here
</h1>
</body>
Page 2:
<body>
<%
Teacher teacher = (Teacher) request.getAttribute("teacher");
session.setAttribute("teacher", teacher);
out.println("Welcome "+ teacher.getUserName());
out.println("Your ID is "+ teacher.getPassword());
%>
</body>
Set the Teacher teacher in session scope in your Servlet rather than in your specific pages:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//...
Teacher teacher = new Teacher();
//...
request.getSession().setAttribute("teacher", teacher);
//...
}
Then, retrieve it and use it in your JSP code with no problems:
Page1.jsp:
<body>
Welcome ${teacher.username}. Your ID is ${teacher.password}
<h1>
Click Here
</h1>
</body>
Page2.jsp:
<body>
Welcome ${teacher.username}. Your ID is ${teacher.password}
</body>
Hints:
Do not use scriptlets anymore.
Don't use a password field as ID. Not even for test purposes. Assign a proper ID and do not store (real) password anywhere but in your database, and at least hashed.

Hang Man Game in MVC with JSP

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

Fetch, process and display the result on the same page

I have a jsp page containing a form where a user fills in some value. Now i pass these values into a servlet which processes it and retieves a related set of data. Now, i am able to retrieve the data in the servlet page, but am not able to display it on the same jsp page at which i fetched the request.
I do not want to use java code inside jsp. I wish to do the same using servlets only. I do not want to do something like this
<% if(rollno==null)
// then display the form
else
// process the request on the jsp page itself
%>
I want to process all my reults in a servlet file and then dispaly the result on the jsp page by passing data from servlet to jsp. I am posting my code below :
<form id="form" method="post" action="searchServlet">
Student Roll No :<br><input type="text" value="" name="rollno"><br><br>
<input type="submit" value="SHOW DETAILS" />
</form>
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String rollno=request.getParameter("rollno");
ResultSet rs=null;
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/schooldatabase";
Connection con = DriverManager.getConnection(url,"root","passwd");
Statement st= (Statement) con.createStatement();
String strquery="SELECT name,regno FROM `schooldatabase`.`student_info` WHERE rollno="+ rollno+ ";";
if(!con.isClosed()) {
rs=st.executeQuery(strquery);
while(rs.next())
{
out.println(rs.getString("name"));
out.println(rs.getString("regno"));
}
}
else
{ // The connection is closed
}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
You shouldn't be doing the presentation in the servlet. You should not have any of those lines in the servlet.
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// ...
out.println(rs.getString("name"));
out.println(rs.getString("regno"));
// ...
out.println(e);
You should instead be storing the data in a sensible collection and be setting it as a request attribute and finally forward the request/response to a JSP which in turn generates the proper HTML around all those data. Something like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Student> students = studentDAO.find(request.getParameter("rollno"));
request.setAttribute("students", students); // Will be available as ${students} in JSP
request.getRequestDispatcher("/WEB-INF/students.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain students from DB", e);
}
}
with this in the students.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${students}" var="student">
<tr>
<td>${student.name}</td>
<td>${student.regno}</td>
</tr>
</c:forEach>
</table>
For a more concrete example, see also this answer: Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
See also:
Our Servlets wiki page - Contains several Hello World examples

Categories

Resources