Denying direct access to jsp pages - java

I'm using struts 1.3 for my application and all jsp pages are forwarded through controller (action class). But If I access the jsp page directly, I'm able to access it. How do I prevent this?

put all your jsp-s inside WEB-INF folder (for example in WEB-INF/jsp folder) and dont forget to change your mapping regarding location of jsp-s.

Filters are used to bypass or interrupt the requests , so use the filters to restrict the request , if it not contains .do in url. Below is the good tutorial for filters
Filters

I think the best option would be to put your web pages in the WEB-INF folder - that way they won't be directly accessible but then in your servlets you can have something like:
public class ControllerServlet extends HttpServlet {
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if category page is requested
if (userPath.equals("/category")) {
// TODO: Implement category request
// if cart page is requested
} else if (userPath.equals("/viewCart")) {
// TODO: Implement cart page request
userPath = "/cart";
// if checkout page is requested
} else if (userPath.equals("/checkout")) {
// TODO: Implement checkout page request
// if user switches language
} else if (userPath.equals("/chooseLanguage")) {
// TODO: Implement language request
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Taken from: http://netbeans.org/kb/docs/javaee/ecommerce/page-views-controller.html

You can use filters and restrict the request with url which ask for .jsp pages and only allow requests which ask for .do

Related

java: create and submit form from servlet and move to the target url

One of the webservices I am trying to connect requires me to submit a form to an url, lets say LINK_A.
I have a form view VIEW_A, I submit VIEW_A to my own servlet called SERVLET_A. Here in SERVLET_A from the form params, I generate a signature key, which is required by the webservice.
Then I need to submit to LINK_A programmaticaly from my servlet, BUT they told me that I need to submit it and redirects to LINK_A, so unlike what I've known so far (using httpclient httppost and getting the response data), I need to do something like a redirect with post data to their link.
So in summary:
1. from my view, submit a form
2. modify post data from servlet
3. submit the form to the webservice link and move to that link (as if the form from the view submit directly to the webservice link)
How can i do this?
If you need the form to be submitted from the browser (not from within your servlet using httpclient) your servlet needs to return a self-submitting form. E.g. use document.getElementById('myForm').submit() on documentReady.
If your form params can be submitted via GET you might also respond with a HTTP 302 redirect containing all params in the query string.
mean if you want collect request from previous form and check in servlet class and forward to new form den check this logic if its help
form code within servlet
rotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<html body=\"red\"> <center>");
pw.println("<form action=\"./NewFile.do\" method=\"get\">");
pw.println("<h2>enter the name </h2> <input type=\"text\" name=\"username\">");
pw.println("<h2>enter the password </h2> <input type=\"text\" name=\"passward\">");
pw.println("<input type=\"submit\" value=\"login\">");
pw.println("</form>");
pw.println("<center></body></html> ");
}
this below code to check and initialize path, before that you have to configure web.xml for this servlet class to behave as controller.
public class ServletControl extends HttpServlet {
#Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("inside the servlet");
String servletpath=request.getServletPath();
String path = null;
if(servletpath.equalsIgnoreCase("/NewFile.do")){
path="NewFile.jsp";
}
if(path!=null){
RequestDispatcher dis=request.getRequestDispatcher(path);
dis.forward(request, response);
}
}
}

How do I print something in Tomcat Servlet, sleep for 3 seconds and then forwarding to another servlet?

This is a project for my study.
I have a JSP with checkboxes which I will store into an Array in the Result.class (Result servlet) after clicking Submit on the JSP page. But before that, I have a PageProcessing (to show some processing text before showing the result of the Array) that will be shown before the Result servlet.
I want to let the PageProcessing servlet show some text and then sleep for 3 seconds before forwarding to the next servlet. The only thing that doesn't work is that it doesn't show the out.println(""); text before sleeping.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
out.println("<h1>Processing..."
+ "<br>"
+ "<h2>Please wait.</h2>");
} finally {
try {
Thread.sleep(3000);
request.getRequestDispatcher("Result").forward(request, response);
out.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Return a complete page to the user and close the connection. This will display a nice status page to the client. Then, let the client re-connect (META REFRESH, jQuery, raw AJAX, timed Javascript window.location='...', etc.) and fetch the follow-up resource.
EDIT 2020-09-08
Examples:
meta refresh
jQuery refresh
javascript (also includes other strategies)

Render HTML response from remote call to the client

I have a working servlet wich originates back from this template:
http://www.objectdb.com/tutorial/jpa/eclipse/web/servlet
So the basic rountrip works.
I added a new feature where I POST data to the servlet, construct a call/request out of the data to a remote http server, retrieve the response-html-string (the content of the website I requested) and want to show this HTML String now as response to my original POST call.
I tried it like this:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
boolean showDetails = Boolean.valueOf(request.getParameter("showDetails"));
if (showDetails) {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
return; // <----------------- if showDetails then this is the end of doPost
}
// Display the list of guests:
doGet(request, response);
}
When I press the link that creates the POST event I see in the logfile, that "loadDetails" has succesfully loaded the content from the remote server, but the browser window does not refresh. Why?
PS: a simple redirect to the other side is not possible for technical reasons.
Try making a ajax request to your servlet which gives to html content as string sent it back to ajax call and set it to innerHTML of a div element.
I changed to use GET instead of POST and I used a separate Servlet for this kind of call. This solved my problem.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
}

transfer data to a servlet from a jsf page

I have an input in my jsf page like this
<html:inputText id="ResponseOK" value="#{bean.ResponseOK}" binding="#{bean.ResponseOKInput}" />
I want to get the value in a servlet (by request.getParameter ("ResponseOK")) when i click on a command button
<html:commandButton value="Valider" action="#{bean.callServlet}"/>
which call a function
public void callServlet()
{
String url = "http://localhost:8080/TestOne/Timers"; //servlet
FacesContext context = FacesContext.getCurrentInstance();
try {
context.getExternalContext().redirect(url);
}catch (Exception e) {
e.printStackTrace();
}
finally{
context.responseComplete();
}
}
Unfortunately, in my servlet the variable Ok , return only null
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String Ok = request.getParameter("ResponseOK");// return null
System.out.println(timerOk);
}
thank you very much
In order for you to be able to get a property from the request, the input must have the name attribute:
<html:inputText id="ResponseOK" value="#{bean.ResponseOK}" binding="#{bean.ResponseOKInput}" name="ResponseOK"/>
UPDATE:
I'm not too familiar with the JSF framework but i think your problem is the action button.
This button is not a submit button so the value of the input is not being sent to the request.
When calling a GET request, you need to pass the parameter in URL itself, so you need the url to look like:
http://localhost:8080/TestOne/Timers?ResponseOK=value
So you need to transfer the value of the ResponseOK input to the callServlet method.
Hope that helps.

Reloading JSP page

I have an authorization frame displayed on every page and I want to keep that page displaying even if the user will choose to log in (using jstl tags i will simply put instead of this frame user info and link to shopping cart). How can i achieve that ? I have some ideas, but they all breaking out my controller design.
public class FrontController extends HttpServlet {
private ActionContainer actionContainer = ActionContainer.getInstance();
public FrontController() {
super();
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#SuppressWarnings("unchecked")
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page = null;
try {
Action action = actionContainer.getAction(request);
page = action.execute(request, response);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
dispatcher.forward(request, response);
} catch (ActionNotFoundException e) {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(PageNames.ERR_PAGE);
request.setAttribute(AttributeNames.ERR_MESSAGE_ATTRIBUTE, "Unknown Action command: " + e.getMessage());
dispatcher.forward(request, response);
} catch (Exception e) {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(PageNames.ERR_PAGE);
request.setAttribute(AttributeNames.ERR_MESSAGE_ATTRIBUTE, "Exception:\n" + e.getMessage());
dispatcher.forward(request, response);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Front Controller";
}
#Override
public void init() throws ServletException {
super.init();
Locale.setDefault(new Locale("ru","RU"));
}
}
I was thinking about of redirecting to especially written for this case page, which will redirect to the original page, or to check page string for null and reloading from controller the original page, but i cannot clearly understand how to do this.
Your question isn't clear enough. But I think you're asking how you can replace a certain component on a page (Login button) with an other (username, welcome message and shopping cart details) after the user logs in.
If I understand your requirements, then what I would do after the user logs in is set a cookie (or a value in localStorage). The cookie is added to the Set-Cookie response header by means of the addCookie method of HttpServletResponse. Here's an example:
Cookie userCookie = new Cookie("user", "uid1234");
response.addCookie(userCookie);
Then in your controller simply check if the "user" value is set or not and take the appropriate action. A tutorial on servlets with cookies.
If you need to handle the front-end component, and change values on the form without reloading the page, I would recommend using javascript to do this, you can find and remove the old DOM elements with new ones (User's name, Welcome message, shopping cart, whatever).
If your iFrame is doing the login, then on successful login, have it call a function in your top window that does the update after reading the updated values from the cookie.
If you want to handle this completely at the front-end, i.e. Javascript, then I would skip using cookies and use localStorage instead. There is plenty of help on Stackover and on the internet about what localStorage is, but I will suggest the YUI Storage Lite library which makes storing and loading data from localStorage very simple.
Regards,
Include the current URL as a hidden field of your authentication form. In the action handling the authentication, once the user is authenticated, redirect to this URL.
In the JSPs, test if the user is authenticated and include the authentication form or the shopping cart. This test can be done by just putting a boolean value in the HTTP session once the user is authenticated.

Categories