page always redirects to error page - java

I wrote the below code to test the status of msgCode. If the msgCode is not Success it should redirect to error.jsp file. If it is a Success it should stay on the same page . When I ran the code the page always redirects to error.jsp although msgCode is Success. What mistake did I do in my code. Can you please help me if you can. Thank in advance.
<%# page import="com.siebel.SurveyWebService.SurveyTester" %>
<%
SurveyTester tc = new SurveyTester();
tc.getResult();
java.lang.String msgCode = tc.getResult2().getStatusCode();
%>
<%= msgCode%>
<%
if (msgCode.toString() != "Success")
{
response.sendRedirect("error.jsp");
}
%>

First of all, you should use equal method for string comparison. Secondly, even though it's not a problem at the moment but you are creating objects in your jsp and faking the response. tc.getResult2().getStatusCode() is not an actual HTTP response from server.

Related

how to prevent resubmit after refresh in java

i have multiple web pages jsp and i use for the resubmit in refresh response.sendredirect("blabla.jsp") but one page work good , another page wen i press submit it go to a blank page and the row added to database, any solution for this problem ? thank you
`
<% String UC1 = "INIT";
if (request.getParameter("add_spec") != null) {
UC1 = "ADD_SPEC";
}
if (UC1.equals("INIT")) {
List<Speciality> specs = SpecialityController.INSTANCE.findAll();
%>
<%#include file="./WEB-INF/Add_Spec.jspf" %>
<%#include file="./WEB-INF/view_all_specs.jspf" %>
<%}
if (UC1.equals("ADD_SPEC")) {
String spec = request.getParameter("speciality");
SpecialityController.INSTANCE.create(new Speciality(spec));
List<Speciality> specs = SpecialityController.INSTANCE.findAll();
response.sendRedirect("main_admin.jsp");
%>
<%#include file="./WEB-INF/Add_Spec.jspf" %>
<%#include file="./WEB-INF/view_all_specs.jspf" %>
<% }
%>
`
You can use the Post/Redirect/Get pattern.
When a web form is submitted to a server through an HTTP POST request,
a web user that attempts to refresh the server response in certain
user agents can cause the contents of the original POST request to be
resubmitted, possibly causing undesired results, such as a duplicate
web purchase.
To avoid this problem, many web developers use the PRG
pattern - instead of returning a web page directly, the POST operation returns a redirection command.
In other words, when you submit the data, you should redirect to the page on which you can view (get) the data you've just added.
That way, refreshing will not resubmit the data.
Alternatively, you could use a CSRF/XSRF-like token.
Though this example is in PHP, you should understand the gist of it.
Update
Even better, you can check out this example for CSRF https://services.teammentor.net/article/00000000-0000-0000-0000-000000040a2e

Responding with JSON Array in a JSP page

So I'm working on an old application and I'm forced to use JSP at the moment, which I'm extremely unfamiliar with (and unfamiliar with most aspects of web development tbh).
I'm generating a JSON Array using JSONSimple in a Java class method, and then invoking that method from a JSP on a GET request to get the JSON. Sounds simple enough.
I was able to get my JSON when accessing the URL in my browser. Now I'm trying to access my JSP page from another application, and that's where I'm having difficulty. The content type of my "JSON" was text/html, and not JSON, so I tried setting the content type to JSON in my JSP, and now nothing is showing up in browser, and my Spring application is giving me this error when I try to get JSON from the URL: Could not read document: No content to map due to end-of-input at....
Here's my JSP:
<%# page import="com.company.Someclass" %>
<% if(request.getMethod().equals("GET")){
response.setContentType("application/json");
Someclass.getJSONArray();
}
else if(request.getMethod().equals("POST")){
//todo
}
%>
Any help would be greatly appreciated as I'm pretty lost at the moment. Thanks!
Fixed this myself. I'm able to get JSON in the browser, but having trouble reading it in my Spring application. but thats another battle. Here's my solution:
<%# page import="com.company.Someclass" %>
<% String ret = "";
if(request.getMethod().equals("GET")){
response.setContentType("application/json");
Someclass.getJSONArray().toJSONString();
}
else if(request.getMethod().equals("POST")){
//todo
}
%>
<%= ret %>
the toJSONString() is a method of json-simple's JSONArray class

JSP expression language not working when evaluating variables

I am new to JSP and working with Tomcat 8. The problem is that JSP EL is not working properly. Like when i write ${1>2} it gives the right output but when I put a variable name in it it does not give the output. I have this in my code
<%# page import = "java.util.*" isELIgnored="false"%>
but it is still not working. This is my code:
<%
String GuessErrorMsg = null;
if (GuessErrorMsg != null) {
%>
<div class='bad-field-error-message'>${GuessErrorMsg}</div>
<%
}
%>
i found the problem in my code due which i could not get the EL expresion evaluated.
so i am sharing it with everyone. it may be a very beginner's mistake thats what I am.
the problem was that i have not set the variable using setAtrribute(Expression,variable) .thats why i wasnt getting the value .

Redirecting the page with Servlets Java

I have a jsp page with a form that when it’s submitted goes to a Servlet that inserts the form data into the database.
When the data is inserted into the database, I’m trying to get the browser back to my jsp page and show a javascript alert saying that the data was inserted successfully, my code is the following:
RequestDispatcher rd;
if(dao.insertClient(client)) {
rd = getServletContext().getRequestDispatcher("/pages/clients.jsp");
rd.include(request, response);
out.print(
"<script type=\"text/javascript\">"
+ "alert("Client inserted successfully!");"+
"</script>"
);
}
This code is doing exactly what I want, but this method getRequestDispatcher() redirects the page to the servlet itself, and the URL is like http://localhost:8080/Servlet, this way I can’t access any intern link of the page, since the links to the other pages obviously are outside of the servlet context, and the glassfish returns the 404 error.
Instead of using getRequestDispatcher(), I’ve tried using the response.sendRedirect(), this way I can insert the data into the database and access the intern links, but the javascript alert isn’t shown.
Somebody has a suggestion on how I can redirect the page to the clients.jsp and display the javascript alert?
Thanks!
you can try another approach :
Set parameter from servlet like this :
RequestDispatcher rd;
if(dao.insertClient(client)) {
rd = getServletContext().getRequestDispatcher("/pages/clients.jsp");
request.setAttribute("isSuccess", "success");
rd.include(request, response);
}
access the parameter in jsp to check whether to show alert or not.
<%
String result = request.getParameter("isSucess");
if("success".equals(result)){
%>
<script type="text/javascript" >
alert("Client inserted successfully!");
</script>
<%
}
%>

adding security in Struts 2 spring application

I am developing an application with spring 3 struts 2 and hibernate. After login only i have to display the pages
It is working fine. when i testing i found the big mistake
that is i copy the url of the page which needs to display only to logged-in user
and paste it in other browser means it is displaying the page without login.
<%
String userId= (String)session.getAttribute("userId");
System.out.println(userId);
if(userId == null || userId.equals("") ){
response.sendRedirect("login.jsp");
}
%>
I have included this for all jsp. I know this is not a best practice. Is any better option available?
How would i overcome this error?
if(userId == null || userId.equals("") ){
response.sendRedirect("login.jsp");
}
should probably have a return in there to prevent rendering the page content:
if(userId == null || userId.equals("") ){
response.sendRedirect("login.jsp");
return;
}
Nothing in the javadoc suggests that sendRedirect causes abrupt exit or causes the response body to not be shipped to the client.
What is probably happening is that your response contains a redirect header, but also contains the page content which you might not have meant to send.
I am still at education so do know how good is my solution , but i did not crash so hope it is correct
and it is quite similar to #muthu 's code
I had used JPA-eclipselink and Struts2
Action Class
String checkLogin = "SELECT user FROM UserEntity user WHERE user.username = :username AND user.password = :password";
Query checkLoginQuery = em.createQuery(checkLogin);
checkLoginQuery.setParameter("username", loginUsername);
checkLoginQuery.setParameter("password", loginPassword);
userEntity = (UserEntity) checkLoginQuery.getSingleResult();
Map sessionMap = ActionContext.getContext().getSession();
sessionMap.put("userEntity", userEntity);
JSP -> all jsp pages have this(bug:affected if session is not killed when browser is not closed )
<%# taglib prefix="s" uri="/struts-tags" %>
<s:if test="%{#session.userEntity == null}">
<jsp:forward page="login.jsp"/>
</s:if>
Correct me if I am wrong
Quoting this page
Both and RequestDispatcher.forward() are what I refer to as "server-side" redirects
The response.sendRedirect() is what I call a "client-side" redirect.
so a server side forward looks more safe to me , maybe I am wrong (I am sorry if I am miss interpreting it ,not worked in real life projects yet)

Categories