Why URL is changing - java

I have a simple servlet like this:
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "root";
private final String password = "root";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
rd.include(request, response);
}
}
Also I have login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
In browser I start my app http://localhost:8080/LoginCookie/ and browser shows login.html. Then I click "Login" button and URL is changing to http://localhost:8080/LoginCookie/LoginServlet.
How do I disable it?

Instead of including your HTML, you could instead redirect to your login.html
Consider using
response.sendRedirect("login.html");
instead of rd.include()
Redirecting has the nice side-effect that reloading the page will reload login.html instead of triggering your servlet again.

If you want to stay on the same page, leave the action attribute empty into your form tag
<form action="" method="post">
But then, you have to make sure that your Servlet will receive your form. LoginServlet will not receive the form request anymore, it will be sent to Servlet mappend with the URL of your current position. So you'll have to make a Servlet receiving this info.

Related

Redirect to new page

I I have a form in my "login.html" and after I click the "login" button, this form will be submitted to my java back-end code. However, I don't know how to redirect my login page to the new page.
In the following code:
<script>
$(function() {
$('#ff').form({
url: "LoginServlet",
success:function(data){
$.messager.alert(data);
}
});
});
</script>
In the success part, my redirected page will show in this message window. But I want it jump to the page returned by the servlet.
This is my login.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
$(function() {
$('#ff').form({
url: "LoginServlet",
success:function(data){
$.messager.alert(data);
}
});
});
</script>
</head>
<body>
<form id="ff" role="form" method="post">
<div>
<h1>User Login</h1>
</div>
<div>
<input id="username" name="username" class="easyui-textbox" data-options="iconCls:'icon-man',iconWidth:30,iconAlign:'left',prompt:'Username'" style="width:100%;height:35px;" />
</div>
<div>
<input id="password" name="password" class="easyui-passwordbox" data-options="iconWidth:30,iconAlign:'left',prompt:'Password'" style="width:100%;height:35px;" />
</div>
<div>
Submit
</div>
<div>
<div style="display:inline;">
Register
</div>
</div>
</form>
</body>
</html>
This is my java servlet code:
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
IUserService userService = new UserServiceImpl();
User user = userService.login(username, password).get(0);
if (user != null) {
response.sendRedirect(request.getContextPath() + "/index.jsp");
} else {
}
}
}
You could try removing the Javascript function and calling directly the jsp using the form action.
So I would remove the following part
<script>
$(function() {
$('#ff').form({
url: "LoginServlet",
success:function(data){
$.messager.alert(data);
}
});
});
</script>
This part here needs to be removed because of the structure that you have. Most projects with JSP have this structure that you have.
You want in first step to take all the form parameters and to visit the url .../LoginServlet.
Then as you have structured your servlet it makes the authentication and if successful it sends a message to your browser and says: Please browser keep these headers in the http message but please visit another URL (index.jsp) to see what you wait for.
As you can see it's up to the client (aka browser) to move between different URL in order to be served.
That is why that simple Javascript function does not work as expected.
So a simple solution would be to make the call directly in the form action
<body>
<form id="ff" role="form" method="post" action="/LoginServlet">
....
If the authentication was not successful then I would serve an error page from my servlet.
if (user != null) {
response.sendRedirect(request.getContextPath() + "/index.jsp");
} else {
response.sendRedirect(request.getContextPath() + "/error.html");
}

Display error message from Servlet to JSP page without reloading the page

I have an HTML form for user login on a JSP document and I send the input of the user to a Servlet, check the password against a database then redirect the user to a new page if it's correct or show an error message on the page "Incorrect Password" of incorrect.
I want the error message to appear on the same page as the form just below the Password input field. I have tried the code below but it still redirects me to a new page where it displays only the "Incorrect Password" message.
Is there any other way on how to do it?
Thank you in advance.
//SERVLET CODE
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Some code to check if the password matches the one in the DB and redirects to another page.
} else {
String text = "Incorrect Password!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(text);
}
}
}
//JSP PAGE
<!DOCTYPE html>
<html>
<head>
<script>
$('#sButton').click(function() {
$.post('UserServlet', function(responseText) {
$('#msg').text(responseText);
});
});
</script>
<title>User Log in</title>
<%# include file="PageHeader.html" %>
</head>
<body>
<form action = "SomeServlet" method="POST">
<h3 >Enter detailsto Sign In</h3><br>
Email: <input type="text" name="email" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" name="submit" value="Sign in">
<div style="color:red" id="msg"></div>
</form>
</body>
</html>
The error message should appear on this same page as I understand but it just opens a new page showing only the message and not the html form.

Java Spring - servlets - Uplading file post request does not work for me

I have a Java Application using Spring frame work. I am a new learner in this concept. My apologies for making a question which might be very simple.
From the web page user can browse a an excel file and after hitting submit, the excel file should be uploaded to the server and given as an input to a java function in the back end to process it and create a json object.
here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta content="width=device-width, initial-scale=1.0" name="viewport"></meta>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"></meta>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link href="resource/css/main.css" rel="stylesheet"></link>
<title>My App</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/uploadServlet" method="post" enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" name="submit"/>
</form>
<button id="processData" type="button" class="btn btn-primary">ProcessData</button>
<br></br>
<br></br>
<script src="js/mainJs.js"></script>
</body>
</html>
Then I have define my Servlet file as following:
/**
* Servlet implementation class UploadServlet
*/
#WebServlet("/UploadServlet")
#MultipartConfig
#Named //we can use dependacy injection
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void init(ServletConfig config) throws ServletException {
//this is an initialization method that servlet calls when the application starts up
super.init(config);
// this sets up our dependancy injection
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
//String fileName = Paths.get(filePart.get).getFileName().toString(); // MSIE fix.
InputStream fileContent = filePart.getInputStream();
TestingPost tp = new TestingPost();
if(request.getParameter("submit") != null) {
tp.method1(fileContent);//in this method I will process the received excel file
}
}
}
and here is my java file that plays as controller
public class ProcessFile {
public void method1(InputStream out) {
//doing some processing }
}
but when I run the application, browse a file and hit submit I get 404 -
Do I need to do some thing in my web.xml ?

Variables not making it from one JSP to the other when using HttpSession

I am having trouble retrieving any type of parameter from one jsp page to the other using doPost, and a form where my method is post. Note below is a minimal example.
First, I have two pages:
Here is search.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<title>search</title>
<body>
<form name="search" method="post" action="search_results.jsp">
<p>
<input type="text" class="inputTitle" id="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
<button type="submit">Search</button>
<p>
</form>
</body>
</html>
And my search_results.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<title>search results</title>
<body>
<p>Title: ${movie.title}</p>
</body>
</html>
Now I have a class called SearchServlet.java:
#WebServlet("/search")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
request.getRequestDispatcher("search.jsp").forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
String title = request.getParameter("inputTitle");
String searchTitle;
try {
if(title != null && !title.isEmpty()) {
searchTitle = "hello";
} else {
searchTitle = "world";
}
session.setAttribute("movie.title", searchTitle);
request.getRequestDispatcher("search_results.jsp").forward(request, response);
} catch(ServletException e) { e.printStackTrace(); }
}
}
No matter what I enter the result (movie.title) always ends up being empty and so I get world on search_results.jsp. Why is my parameter not being passed to search_results.jsp?
It will not happen if you bypass the servlet
Look at your form action
<form name="search" method="post" action="search_results.jsp">
You are sending the post request directly to the search_results.jsp: you should send it to the servlet instead (mapped # /search)
<form name="search" method="post" action="search">
Then from the servlet you should forward the request to the search_result.jsp, which you actually did.
In addition to that when you call request.getParameter you have to keep in mind that what counts is the name of the input field, not the id. You should change the id attribute to name
<input type="text" class="inputTitle" name="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
Lastly, hopefully :) the '.' (dot) might cause issues:
session.setAttribute("movie.title", searchTitle);
When you retrieve the attribute the dot notation indicates that you are accessing a field in a object called movie
<p>Title: ${movie.title}</p> <!-- you are accessing the title property of a movie object !-->
but you do not have that...you have a movietitle, a String presumably. Change the attribute name to something like movietitle without the dot and retrieve it in the jsp the same way. the above lines will become:
session.setAttribute("movietitle", searchTitle);
<p>Title: ${movietitle}</p>
That should solve the issue.

Reload a jsp page from servlet when form data is involved

I have a jsp that calls a servlet. This servlet does some tasks and then I want to return to the page I was just at and reload it. This would be simple if I knew the exact url it would be each time using the redirectUrl. However, I can't hard code a value in this as it is dynamically created. Is there a way to do this when the previous url is Not known to me?
I am not sure if I understood you correctly, do you need move from jsp to servlet, and return to the same jsp? If this is what you need, I would put some hidden input in jsp form with path
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
So full solution is below:
page1.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${requestScope.dataFromServlet }
<form action="${pageContext.request.contextPath}/HelloWorldServlet " method="POST">
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
<input type="hidden" name="param1" value="value1"/>
<input type="submit" value="Submit">
</form>
</body>
</html>
HelloWorldServlet.java
public class HelloWorldServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String jspPath = request.getParameter("jspPath");
if(jspPath == null || "".equals(jspPath))
jspPath = "errorPage.jsp";
request.setAttribute("dataFromServlet", "Hello World");
RequestDispatcher rd = request.getRequestDispatcher(jspPath);
rd.forward(request, response);
}
}

Categories

Resources