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.
Related
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.
I was trying to forward from doPost to doGet of the ControllerServlet urlPattern = "/remove_person", so I can re-update findAll query inside my doGet method of the ControllerServlet class, and then forward to remove_person.jsp from doGet method, but AS-WEB-CORE-00089 exception is thrown
WARNING: StandardWrapperValve[ControllerServlet]: Servlet.service() for servlet ControllerServlet threw exception
javax.servlet.ServletException: AS-WEB-CORE-00089
at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:863)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:739)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:575)
at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:546)
at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:428)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:378)
at server.ControllerServlet.doPost(ControllerServlet.java:130)
where ControllerServlet.java:130 line is in doPost() method:
request.getRequestDispatcher(url).forward(request, response);
Here is the code of servlet class:
#WebServlet(
name = "ControllerServlet",
loadOnStartup = 1,
urlPatterns = {
"/index",
"/search_person",
"/add_person",
"/remove_person"})
public class ControllerServlet extends HttpServlet {
#PersistenceUnit
private EntityManagerFactory emf;
#Resource
private UserTransaction utx;
private EntityManager em;
#Override
public void init() throws ServletException {
assert emf != null;
em = emf.createEntityManager();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String servletPath = request.getServletPath();
if (servletPath.equals("/index")) {
}
else if (servletPath.equals("/search_person")) {
List persons = em.createNamedQuery("Person.findAll").getResultList();
request.setAttribute("findByNameAndYearBirth", persons);
}
else if (servletPath.equals("/add_person")) {
}
else if (servletPath.equals("/remove_person")) {
List persons = em.createNamedQuery("Person.findAll").getResultList();
request.setAttribute("findAll", persons);
}
String url = servletPath + ".jsp";
request.getRequestDispatcher(url).forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String servletPath = request.getServletPath();
if (servletPath.equals("/index")) {
}
else if (servletPath.equals("/search_person")) {
String name = request.getParameter("name");
String yearBirth = request.getParameter("yearBirth");
Query query = em.createNamedQuery("Person.findAll");
if (!name.isEmpty() && !yearBirth.isEmpty()) {
query = em.createNamedQuery("Person.findByNameAndYearBirth");
query.setParameter("name", name);
query.setParameter("yearBirth", Short.parseShort(yearBirth));
}
else if (!name.isEmpty()) {
query = em.createNamedQuery("Person.findByModel");
query.setParameter("name", name);
}
else if (!yearBirth.isEmpty()) {
try {
Short sYearBirth = Short.parseShort(yearBirth);
query = em.createNamedQuery("Person.findByYearBirth");
query.setParameter("yearBirth", sYearBirth);
} catch (NumberFormatException nfe) {}
}
List persons = query.getResultList();
request.setAttribute("findByNameAndYearBirth", persons);
}
else if (servletPath.equals("/add_person")) {
String name = request.getParameter("name");
String hobby = request.getParameter("hobby");
String yearBirth = request.getParameter("yearBirth");
int personsLen = em.createNamedQuery("Person.findAll").getResultList().size();
Person newPerson = new Person(
++personsLen, name, hobby, Short.parseShort(yearBirth)
);
try {
utx.begin();
em = emf.createEntityManager();
em.persist(newPerson);
utx.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
else if (servletPath.equals("/remove_person")) {
String id = request.getParameter("id");
Person person = null;
try {
utx.begin();
person = em.find(Person.class, Integer.parseInt(id));
em.remove(person);
utx.commit();
} catch (Exception e) {
e.printStackTrace();
}
servletPath = "/remove_person";
}
String url = servletPath;
request.getRequestDispatcher(url).forward(request, response);
}
}
Problem is, my line inside doPost method
String url = path;
does not contain a ".jsp" part.
But if I add ".jsp" part to a string url, then how I will update findAll query data inside remove_person.jsp if i don't go to servlet doGet first to collect new data after adding or deleting entities?
remove_person.jsp
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Remove Person</h1>
<form action="remove_person" method="post">
<table border="3">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<c:forEach var="person" begin="0" items="${findAll}">
<tr>
<td>${person.id}</td>
<td>${person.name}</td>
</tr>
</c:forEach>
</table>
<strong>Remove person: </strong>
<select name="id">
<c:forEach var="person" items="${findAll}">
<option value="${person.id}">${person.id}. ${person.name} </option>
</c:forEach>
</select>
<input type="submit" id="remove_person" value="Remove" />
</form>
<br>
Home page
</body>
</html>
Actually, is it even possible to forward from doPost to doGet method of the same servlet ? The reason I was trying to do this is because, inside doGet I already use this code:
List persons = em.createNamedQuery("Person.findAll").getResultList();
request.setAttribute("findAll", persons);
So why should I duplicate this code inside doPost method, when I can forward from doPost to doGet method and invoke that code?
UPDATE:
Bad approach:
String url = servletPath;
request.getRequestDispatcher(url).forward(request, response);
Correct approach:
String url = request.getContextPath() + servletPath;
response.sendRedirect(url);
Use redirect instead of forward. The pattern (called Post/Redirect/Get) is:
1) the client calls the post url, which does your update
2) the servlet sends a redirect to the client with the url for the get.
3) the client calls the url from the redirect.
When the response from the GET comes back the browser has the GET url, so the browser ends up with a url that's bookmarkable. Also this way the user can't repost the same data by hitting f5 or clicking multiple times.
For when to use forward vs redirect see this advice:
Forward
a forward is performed internally by the servlet
the browser is completely unaware that it has taken place, so its original URL remains intact
any browser reload of the resulting page will simple repeat the original request, with the original URL
Redirect
a redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the
original
a browser reload of the second URL will not repeat the original request, but will rather fetch the second URL
redirect is marginally slower than a forward, since it requires two browser requests, not one
objects placed in the original request scope are not available to the second request
In general, a forward should be used if the operation can be safely repeated upon a browser reload of the resulting web page; otherwise, redirect must be used. Typically, if the operation performs an edit on the datastore, then a redirect, not a forward, is required. This is simply to avoid the possibility of inadvertently duplicating an edit to the database.
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);
}
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