break line in jsp page by using a string on session - java

I have doPost in a servlet -
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("sysMsg","now we gonna to break line \n");
// forward to printLine.jsp page
dispather.forward(request, response) ;
}
And jsp page (says , printLine.jsp) -
<html>
<head>
<title></title>
</head>
<body>
<font size="30" color="Red">${sysMsg} </font>
</body>
</html>
I want that in printLine.jsp the printing of sysMsg finally break line ... For that in put \n in the end of sysMsg when set him in the servlet , but this way didn't work .

Try <br/> instead
request.getSession().setAttribute("sysMsg","now we gonna to break line <br/>");

Related

Submitting a post method doesn't redirect to target page using Servlets

I have followed many tutorials.
the login page (index.jsp) opens, but when I submit it doesn't redirect (go to welcome page (welcome.jsp)) and gives error 404
im new to using servlets as you can see, any help will be appreciated
login class
#WebServlet(name = "login" ,urlPatterns = "/login")
public class Login extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("index.jsp");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String password = req.getParameter("password");
if (name.equalsIgnoreCase("ahmad") && password.equalsIgnoreCase("ahmad")) {
resp.sendRedirect("welcome.jsp");
} else {
resp.sendRedirect("index.jsp");
}
}
}
index.jsp
<html>
<head>
<title>login</title>
</head>
<body>
<form action = "/login" method = "post">
Name : <input name = "name" type = "text" />
Password : <input name = "password" type = "password" />
<input type = "submit" />
</form>
</body>
</html>
welcome.jsp
<html>
<head>
<title>welcome</title>
</head>
<body>
<p><font color="red">welcome</font></p>
</body>
</html>
Error Description:
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

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.

Request a variable defined in jsp from servlet? [duplicate]

This question already has an answer here:
Authentication filter and servlet for login
(1 answer)
Closed 6 years ago.
The username of the person who logs in is present on the index page and the code works fine. But trying to access the variable username from the servlet is proving hard. Any ideas?
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><%=request.getParameter("username")%> - Cloud</title>
<link rel="stylesheet" href="css/bootstrap.css">
</head>
<header class="page-header">
<% String username = request.getParameter("username");%> // How can i get this variable?
<h1 align="center" class="inline"><%=username%> - Files</h1>
</header>
<body>
Servlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
}
?
You have to call the servlet through the jsp page
How to call servlet through a JSP page
This is an official example from oracle of how to do that:
Jsp2Servlet.jsp
<HTML>
<HEAD> <TITLE> JSP Calling Servlet Demo </TITLE> </HEAD>
<BODY>
<!-- Forward processing to a servlet -->
<% request.setAttribute("empid", "1234"); %>
<jsp:include page="/servlet/MyServlet?user=Smith" flush="true"/>
</BODY>
</HTML>
MyServlet.java
public class MyServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out= response.getWriter();
out.println("<B><BR>User:" + request.getParameter("user"));
out.println(", Employee number:" + request.getAttribute("empid") + "</B>");
this.getServletContext().getRequestDispatcher("/jsp/welcome.jsp").
include(request, response);
}
}
welcome.jsp
<HTML>
<HEAD> <TITLE> The Welcome JSP </TITLE> </HEAD>
<BODY>
<H3> Welcome! </H3>
<P><B> Today is <%= new java.util.Date() %>. Have a nice day! </B></P>
</BODY>
</HTML>
The key is in the line:
<jsp:include page="/servlet/MyServlet?user=Smith" flush="true"/>
In this example a jsp call a servlet a that servlet call another jsp. The example is from this page:
https://docs.oracle.com/cd/A87860_01/doc/java.817/a83726/basics4.htm

How to reference an attribute in loop in servlet

I have the following line of code in my jsp:
<body>
These are the names of the companies you have searched for:
<c:forEach items="${cname}" var="company">
<br>
${company}
<br>
</c:forEach>
</body>
It gives me the following output on the web page:
company1
company2
company3
I want to click on company1 and want "company 1" displayed on console, however it is just null.
I used the following method in the servlet:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
dispatcher=req.getRequestDispatcher("/shareinfo.jsp");
System.out.println(getServletContext().getAttribute("company"));
dispatcher.forward(req, resp);
}
What is the problem?

Jsp page doesn't updated after forward

I have the following problem. First of all, I'm send request from jsp to servlet, then I'm doing some operation, and put some data to request, and forward to the same page for rendering new data. But after forwarding, my jsp page doesn't update. Can anyone say me, what I'm doing wrong?
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>File Viewer</title>
<link href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
<script src="${pageContext.request.contextPath}/resources/js/bootstrap.min.js"> </script>
<script src="${pageContext.request.contextPath}/resources/js/jquery-1.8.0.min.js"> </script>
<script type="text/javascript">
function showFolderRequest(fileName) {
$.post( "ftp?fileName="+fileName, function( data ) {
});
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="col-md-9 list-group" style="float: none; margin: 20px auto;">
<div class="list-group-item active" style="background-color: darkcyan;">
Ftp server: /
</div>
<c:forEach items="${requestScope.files}" var="fileEntity">
<p class="list-group-item" onclick="showFolderRequest('${fileEntity.name}')">
${fileEntity.name}
</p>
</c:forEach>
</div>
</div>
</body>
</html>
This is my servlet
#WebServlet("/ftp")
public class FileServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
FileManager fileManager = FileManager.getInstance();
String requestedFileName = req.getParameter("fileName");
req.setAttribute("files", fileManager.getAllFilesByPath(requestedFileName));
getServletContext().getRequestDispatcher("/test.jsp").forward(req, resp);
}
}
The problem is that you're firing an ajax request. When handling ajax requests, you need to be aware of some things:
You cannot forward not redirect from your servlet. This is an asynchronous request from the browser and it won't get any content from a forwarding or redirection from the server.
Expression Language (those things inside ${}) and JSP tags like JSTL run on server side when processing the JSP and rendering the HTML. Any ajax request wont update any EL nor any JSP tag content since this code it is not run on server. So, any new attribute you set here won't matter until you fire a non-ajax request.
The only way you can get any data from the server is by writing a response that contains the desired data. Usually, you would write a JSON response, but you can even write an XML or a plain text response, it will depend on your design. Then, in the browser side (Javascript), you handle the data from the response and display some text, update values in your current HTML, and on.
From this case, you can write a list of the desired files into a JSON string and write that string in the server response, then manage it accordingly in client side. This is just a bare example of how to achieve it using Jackson library to convert Java code into JSON string.
In servlet:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
FileManager fileManager = FileManager.getInstance();
String requestedFileName = req.getParameter("fileName");
//not really sure what retrieves, I'm assuming it is a Lis<FileEntity>
//edit this accordingly to your case
List<FileEntity> files = fileManager.getAllFilesByPath(requestedFileName);
String json = new ObjectMapper().writeValueAsString(files);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
In JavaScript:
<script type="text/javascript">
function showFolderRequest(fileName) {
$.post( "ftp?fileName="+fileName, function( data ) {
//logs the whole JSON string response into browser console
//supported in Chrome and Firefox+Firebug
console.log(data);
//parsing the JSON response
var files = JSON && JSON.parse(data) || $.parseJSON(data);
//since it is an array, you need to traverse the values
for (var fileEntity in files) {
//just logging the files names
console.log(fileEntity.name);
}
});
}
</script>

Categories

Resources