Servlet-Servlet-Jsp redirecting - java

I'm developing an application in JAVA where a servlet is taking the inputs from a JSP page. After inserting the values in db it will redirect to another servlet. Then the 2nd servlet will dispatch a JSP page with an ArrayList. But I can't redirect from the 2nd servlet to the JSP page. The ArrayList is going to the JSP page but the page is not showing anything. I'm using NetBeans 6.8.
I'll be thankful if anyone can solve this problem.
Code for 1st Servlet:
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet1?id="+id);
dispatcher.forward(request, response);
Code for 2nd Servlet:
request.setAttribute("list",list);
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);

try this on 2nd servlet ..
request.setAttribute("list",list);
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(url);
v.forward(request, response);
On jsp page ...
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title></title>
</head>
<body>
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
</body>
</html>

public class MySqlConnection {
Connection c;
public Connection getConnection() throws ClassNotFoundException, SQLException {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "ignite292";
String user = "root";
String password = "root";
Class.forName(driver); // You don't need to call it EVERYTIME btw. Once during application's startup is more than enough.
c = (Connection) DriverManager.getConnection(url + dbName, user, password);
return c;
}
public void closeConnection() {
try {
if (!c.isClosed()) {
c.close();
}
} catch (Exception e) {
}
}
}

First things, If you are using any redirect mechanism, It should not be in RequestScope. It must be in Session or Context Scope(Based on your Requirement). So , the resultant code for 2nd Servlet may as follow
request.getSession().setAttribute("list",list);
String url="/test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
Try with this Code.

Sankha,
You can add those objects into session object. and you can use that session obj in any jsp and servlet.
suppose you have an arrayList Obj which have some data objects. and you are trying redirecting your servlet to jsp OR servlet to servlet.
eg:-
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet1?id="+id);
dispatcher.forward(request, response);
request.setAttribute("list",list); // **Insted of using request object use session implicit object**.
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
Please refer below code to sort out your problem.
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet1?id="+id);
dispatcher.forward(request, response);
**session.setAttribute("list",list);**
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
And get this list object by using
List dataList = session.getAttribute("list");
Hope this will help you.

Related

Use Java variable in HTML File

I made a LoginServlet with Java, that gets username and password from a database. Now I want to display the username on my website after logging in.
Servlet Code:
public class LoginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
Sql2o sql2o = DatabaseConnetcionProvider.getSql2oConnection();
User user = UserDAO.findBenutzerByUsername(username, sql2o);
if(user != null && user.getPassword().equals(password)){
UserListe.getInstance().add(user);
HttpSession session = req.getSession();
session.setAttribute("user", user);
resp.sendRedirect("/public/Home.html");
} else {
resp.sendRedirect("/public/Error.html");
}
}
}
Now I want to display the username on my Website.
I hope you can help me :)
In case of JSP you can use session implicit object
<%= ((User) session.getAttribute("user")).getUsername %>
You can retrieve value in your Home.html as below
<script type="text/javascript">
$(document).ready(function() {
userName = "{{user}}";
$("#yourFieldName").val(userName);
});
</script>
if the page is static html page,the static page can not handle the servlet page scope data,use jsp or other dynamic page to handle it,freemarker,velocity is suitable.
in jsp,you can use EL Express to show the data.the format is ${sessionScope.user}.
you should review the pageScope,requestScope,sessionScope,applicationScope concept.
sendRedirect method can cause data missing in pageScope,you should choose the right scope and the redirect or forward method,test it,please.
if the page is static page,please use AJAX to send request and handle the data,jQuery library is classic.

jsp/servlet Pages redirection

i have two page JSP profile.jsp and comprofile.jsp
I will make a direction towards page profile.jsp if my attribut booleen etatin my table etat=1 redirection profile.jsp
else if etat=0 redirection comprofile.jsp
My code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession Session = request.getSession();
// response.getWriter().print("welcome" + Session.getAttribute("idoperateur"));
// Object getAttribut(int idoperateur);
String idoperateur = (String)Session.getAttribute("idoperateur");
int etat;
try {
dbcon= new javaConnectDB();
conn=dbcon.setConnection();
stmt=conn.createStatement();
query="select * from operateur where idoperateur='"+idoperateur+"' ";
res=dbcon.getResult(query, conn);
etat=res.getInt(6);
while(res.next()){
etat=res.getInt(6);
lst.add(res.getString("idoperateur"));
lst.add(res.getString("nom_o"));
lst.add(res.getString("prenom_o"));
//lst.add(res.getString("password"));
}
if(etat==0){
request.setAttribute("data", lst);
RequestDispatcher rd= request.getRequestDispatcher("profile.jsp");
rd.forward(request, response);
lst.clear();
res.close();
}
}
catch(Exception e){
System.out.println();
}
}
but it did not work
your etat variable's scope is restricted to while{} loop alone..... then at your if condition etat will not be resolved to a variable
Your usage of try,catch & finally is bad.finally should be used for closing the connections etc.
Anyway it should not be a problem to display the .jsp.
RequestDispatcher rd=response.getRequestDispatcher("full path of jsp");//not just the file name.
You should mention the complete path when you are dispatching to RequestDispatcher.
If you can mention the specific error you are getting i can help.

NullPointerException while retrieving data from the database

When I am trying to retrieve data from database it's showing NullPointerException.
Here is my servlet code:
public class displayData extends HttpServlet {
String query;
Connection conn;
Statement st;
ResultSet res;
ConnectionManager dbconn;
List lst= new ArrayList();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
dbconn= new ConnectionManager();
conn=dbconn.getConnection();
st=conn.createStatement();
query="select * from reg";
res=dbconn.getResultSet(query, conn);
System.out.println(res);
while(res.next())
{
lst.add(res.getString("uname"));
lst.add(res.getString("password"));
}
res.close();
}catch(Exception e)
{
RequestDispatcher rd= request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
finally
{
request.setAttribute("EmpData", lst);
response.sendRedirect("/success.jsp");
RequestDispatcher rd= request.getRequestDispatcher("/success.jsp");
rd.forward(request, response);
lst.clear();
out.close();
}
}
And Here is JSP Code for Retrieving Data from database using above servlet Code:
<body>
<h1>Employee List</h1>
<% Iterator itr;%>
<% List data = (List) request.getAttribute("EmpData");
for(itr=data.iterator(); itr.hasNext();)
{
%>
<tr>
<% String s= (String) itr.next();%>
<td><%=s%></td>
<td><%=itr.next()%></td>
<td><input type="submit" value="Edit" onclick="editRecord(<%=s%>;)"</td>
<td><input type="submit" value="Delete" onclick="deleteRecord(<%=s%>;)"</td>
<%}%>
</tr>
</body>
Please help me for solving this problem.
After seeing your Servlet code I found multiple issues,Lets go one by one
I am not sure whether you defined your servlet as a servlet or not.
Either do mapping in web.xml or add annotation like this
#WebServlet("/displayData") public class displayData extends
HttpServlet {
In the servlet you don't have doGet and doPost method. So your
method processRequest will not be invoked by the container. either
put doGet and call your service method or rename your service method
to doGet. Reference - Is it mandatory to have a doGet or doPost method?
The disaster you done in try catch finally block. finally will be always called so there is no use writing the redirection code there as it will executed after catch also. In addition to that finally blocks first four lines are causing serious issues. You should not call both sendRedirect and forward one followed by another. Either do sendRedirect or do forward but not both at the same time.
You will get this exception illegalstateexception-cannot-forward-after-response-has-been-committed Reference - java.lang.IllegalStateException: Cannot forward after response has been committed
What to do forward or sendRedirect at last, In this case you have to
use forward as its a server side action. Reference -
Request Attributes not available in jsp page when using sendRedirect from a servlet
Based on your path of jsp do forward. if your success and error
jsp's are directly under Webcontent then do like this
request.getRequestDispatcher("success.jsp");
Change these things and try again if not working let me know

servlet not forwarding session attribute to jsp

Using embedded tomcat, this code works:
Servlet:
String test = "test";
request.setAttribute("test", test);
request.getRequestDispatcher("/index.jsp").forward(request, response);
JSP:
<%= request.getAttribute("test") %>
It sets the attribute test and then prints it out on the servlet /example's jsp page example.jsp.
However, if I try to set the attribute within the session then I don't get the same result, instead, I get a null when using this:
Servlet:
String test = "test";
request.getSession().setAttribute("test", test);
request.getRequestDispatcher("/index.jsp").forward(request, response);
JSP:
<%= session.getAttribute("test") %>
On the JSP side, you don't need to say request.getSession(), just session.getAttribute();And you had a problem in your Main.java when creating the servlet context (a trick of using embedded Tomcat); you were not getting the context created by adding the webapp to tomcat, you had some other context.
// File base = new File("src/main/webapp");
// context = tomcat.addContext("", base.getAbsolutePath());
// tomcat.addWebapp(null, "/", base.getAbsolutePath());
context = tomcat.addWebapp("/", new File("src/main/webapp").getAbsolutePath());
context.setSessionTimeout(10080);
I commented out your code and changed the context handling and now things work. And a new exception to be caught.
} catch (ServletException | InterruptedException | LifecycleException exception) {
You may want to compare the session id in the servlet and the jsp. If they are different maybe check your session and cookie configuration in tomcat

In Home Page when we navigate to another page and come back to home there is an error returning the username

Hello i am developing a web Application.. Where on login the user will be redirected to his respected login page with a welcome text as WElCOME Username.. But when the user navigates to some other page and comes back it is displaying welcome msg as null... How to keep the username constant on the homepage even after navigation to different pages??
I use this code on JSp to display Welcome msg:
String un = request.getParameter("txtUsername");
out.println("Welcome " + un);
An d my LoginServlet is this:
String username = request.getParameter("txtUsername");
String category = (request.getParameter("txtCategory"));
Login login = new Login();
login.setUserName(username);
login.setPassWord(request.getParameter("txtPassword"));
login.setCategory(category);
LoginService ls = new LoginService();
ls.loginValidate(login);
Boolean check = ls.loginValidate(login);
if (check == true) {
HttpSession session = request.getSession();
// setting attribute on session
session.setAttribute("user", username);
if (category != null) {
if (category.equalsIgnoreCase("Admin")) {
RequestDispatcher rd = request
.getRequestDispatcher("WEB-INF/WebPages/Admin.jsp");
rd.forward(request, response);
} else if (category.equalsIgnoreCase("Affiliate")) {
RequestDispatcher rd = request
.getRequestDispatcher("WEB-INF/WebPages/Affiliate.jsp");
rd.forward(request, response);
} else {
RequestDispatcher rd = request
.getRequestDispatcher("WEB-INF/WebPages/Client.jsp");
rd.forward(request, response);
}
}
}
else {
RequestDispatcher rd = request
.getRequestDispatcher("WEB-INF/WebPages/Error.jsp");
rd.forward(request, response);
}
}
Please help me fix this.. Thanks in advance....
As you put the value in a session attribute, you need to get it from the session not the request
<c:out value="${sessionScope.user}"/>
or
<% request.getSession().getAttribute("user") %>
Make sure the JSP is allow access session.
<%# page session="true" %>

Categories

Resources