jsp/servlet Pages redirection - java

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.

Related

Java servlet not receiving request attributes [duplicate]

This question already has answers here:
Difference between getAttribute() and getParameter()
(10 answers)
Closed 3 years ago.
I'm currently working on a web app in which I want to update the user as to whether or not an operation was successful. I attempt to achieve this by setting request attributes and forwarding from one servlet to the next. However, the attribute is always null in the receiving controller.
code block that sets the attribute:
try {
updateXRef(request, response, cmds);
} catch (Exception e) {
request.setAttribute("results", "Error encountered. Contact system administrator.");
push(request, response);
}
request.setAttribute("results", "Update Successful");
push(request, response);
}
else {
push(request, response);
}
the method that sends to the other servlet:
private void push(HttpServletRequest request, HttpServletResponse response) {
String url = "/PushServer";
try {
request.getServletContext().getRequestDispatcher(url).forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
and the servlet that processes the request:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(FileFactory.getFileOperationsObject() == null || request.getParameterValues("input") == null) {
initiliaze(request, response);
String url = "/Display.jsp";
request.setAttribute("xRefFile", FileFactory.getXRefFileObjects());
request.setAttribute("platforms",FileFactory.getUniqueSortedPlatforms());
request.setAttribute("showModal", 0);
if(request.getParameter("results") == null) {
request.setAttribute("results", "Update Pending");
}
request.getServletContext().getRequestDispatcher(url).forward(request, response);
}
My only guess is that a new request is somehow being generated. If that is indeed what is happening - how do I avoid it?
The problem is method selection.
request.getParameter("yourAttributeName") only works for retrieving form data (<form></form>) - aka data from your .jsp page - as well as query parameters.
If one wishes to send information from one Java servlet to another Java servlet, as in the above code, one must use:
request.getAttribute("myAttributeName");

How to get page name from WebSphere Portal page?

I am creating a portlet for WebSphere portal 8 and would like to retrieve the page name where my portlet is rendered. This is important because depending on the page, the portlet will server content differently
I've tried to use the NavigationSelectionModel API but do not think I'm using it correctly. I want this code to happen before the view is rendered and I put the code in the doView method. The problem is that I cannot cast a ServletRequest/Response because I only have the RenderRequest and RenderResponse available in the doView method.
public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
// Declarations
List<ForeignAuthority> faList = new ArrayList<ForeignAuthority>();
String resp;
// Set the MIME type for the render response
response.setContentType(request.getResponseContentType());
// Check if portlet session exists
ForeignAuthoritiesPortletSessionBean sessionBean = getSessionBean(request);
if (sessionBean == null) {
response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
return;
}
try{
Context ctx = new InitialContext();
NavigationSelectionModelHome home = (NavigationSelectionModelHome)
ctx.lookup("portal:service/model/NavigationSelectionModel");
if (home != null) {
NavigationSelectionModelProvider provider =
home.getNavigationSelectionModelProvider();
NavigationSelectionModel model =
provider.getNavigationSelectionModel((ServletRequest)request, (ServletResponse)response);
for (java.util.Iterator i = model.iterator(); i.hasNext(); )
{
NavigationNode node = (NavigationNode) i.next();
if (i.hasNext()) {
System.out.println(node.getObjectID().getUniqueName());
}
}
}
}catch(Exception e){
e.printStackTrace();
}
PortletRequestDispatcher rd = getPortletContext()
.getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
rd.include(request, response);
}
The expected result would be to retrieve the page name or unique name of the current page that the portlet is rendered on.
You can try whether the below code snippet helps. You can get the URI value and extract the page name from it.
HttpServletRequest httpServletRequest = PortletUtils.getHttpServletRequest(renderRequest);
httpServletRequest.getRequestURI();

How to resolve NullPointerException in JSP

I am developing a web application using jsp and servlet and I want to show all my records from my database and the number of records in a table.
I have created a DAO in which I performed queries where they returned the data correctly and put it in a session in a servlet giving the name of sessaoListaMotoristasTodos and totalMotorista.
But when passing the values ​​retrieved from the session and assigning the variables, the values ​​are not assigned, the called variables are List ListMotoristas and Integer totalRegistros giving a java.lang.NullPointerException
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
MotoristasDAO dao= new MotoristasDAO();
MotoristasDAO dao2= new MotoristasDAO();
String pesquisa=request.getParameter("pesquisa");
try {
if(pesquisa==null){
pesquisa="";
}
Integer totalMotorista=dao.totalRegistros(pesquisa);
request.setAttribute("totalMotoristas", totalMotorista);
List listaMotoristas2=dao2.mostrarMotoristas();
request.setAttribute("sessaoListaMotoristasTodos", listaMotoristas2);
RequestDispatcher rd= request.getRequestDispatcher("/listaMotoristas2.jsp");
rd.forward(request, response);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro na servelet"+e);
}
}
JSP:
<%
List listaMotoristas=(List) request.getAttribute("sessaoListaMotoristasTodos");
Integer totalRegistros= (Integer) request.getAttribute("totalMotorista");
int totalPaginas=totalRegistros/limite;
if(totalRegistros%limite!=0){
totalPaginas++;
}else{
totalPaginas=0;
}
%>
MotoristasDAO dao2= new MotoristasDAO();
List listaMotoristas2=dao2.mostrarMotoristas();
As per your code you are doing this
request.setAttribute("sessaoListaMotoristasTodos", dao2);
But you should do this
request.setAttribute("sessaoListaMotoristasTodos", listaMotoristas2);
or this
request.setAttribute("sessaoListaMotoristasTodos", dao2.mostrarMotoristas());
you should set the list "listaMotoristas2" in the request and not the "dao2"
and now in the jsp your code is as follows
List listaMotoristas=(List) request.getAttribute("sessaoListaMotoristasTodos");
This will not return a list it will return dao2

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

simple HTML can't getJSON from servlet (java) + mysql

I am trying to get JSON from a simple HTML but I can't do it successfully :c .. I generate JSON from a java Servlet, from MySQL, like this ...
Prueba.java (Servlet)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
Connection conn = ConexionBD.obtenerConexion();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM grifo where id=1");
while(rs.next()){
String grifo = rs.getString("grifo");
String distrito = rs.getString("distrito");
String latitud = rs.getString("latitud");
String longitud = rs.getString("longitud");
JSONObject json = new JSONObject();
json.put("grifo", grifo);
json.put("distrito", distrito);
json.put("latitud", latitud);
json.put("longitud", longitud);
out.print(json);
}
} catch (Exception e){
out.print(e);
}
}
So, when I run this, I get the JSON:
{"grifo":"Grifo Libertad","distrito":"San Juan de Lurigancho",
"latitud":"-123.059028347924","longitud":"93.945783454234234"}
In my java project I have another page called index.jsp, that gets the JSON.
I get the json correctly, but when I create a .html (in desktop: file:///C:/Users/Jhonatan/Desktop/prueba.html in the web browser) with the same code:
http://freetexthost.com/w2xgabhaks
I can't get the JSON, just display NOTHING! Is there a problem with the file on the server (.jsp), at some other location (desktop: .html) or maybe with the database (mysql)?
How does https://graph.facebook.com/zombies work then?
Thanks for all of you!
Have you looked at what the JS console says? My guess is that it will throw something like Origin null is not allowed by Access-Control-Allow-Origin.
JavaScript requests have a same-origin policy. What you're trying to do is a cross-origin request.
The simple fix is for your server to return the following header:
Access-Control-Allow-Origin: *
But I recommend you read all about this and understand what are the implications.

Categories

Resources