This question already has answers here:
How to pass Unicode characters as JSP/Servlet request.getParameter?
(5 answers)
Closed 7 years ago.
I was working normally on my netbeans project. I sent post parameters from html forms to servlets and then capture them with request.getParameter... and all worked fine. But some hours ago, I don't know what happened with netbeans because all new servlets that I create, the requested post parameters are not encoded well. I mean that if I send "tílde" or "ñ" it will be received as "tÃlde" or "ñ". The old servlets still work fine, receiving well the post parameters.
With GET parameters works fine, but with POST parameters always the same with new servlets. Old servlets work fine post parameters.
I tested receiving parameters with php and they are correctly formated, so I discart the posibility of being the jsp encoding.
I think may be netbeans error, but I really dont know.
Here some code and images:
The servlet
public class TestParameters extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
System.out.println("> Ñ,ñ, tílde. Parámetros: " + request.getParameter("name"));
}
The JSP:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="post" action="/TestParameters">
<input type="text" name="name">
<button type="submit">Enviar</button>
</form>
</body>
</html>
Html input:
NetBeans console with POST parámeters:
Netbeans console with GET parámeters:
And receiving with php, works well:
echo $_POST['name'];
Php html echo:
Finally I have resolved my problem. I have implemented a filter that encode all requests. But this only work for POST parameters that is what I need. That's because for POST parameters Tomcat's default encoding is iso-8859-1 and I was ignoring that. For GET parameters the way is
Encoding filter for java web application
Related
This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
Closed 3 years ago.
I'm trying to make a web application using Java Servlets, Tomcat and HTML on Eclipse. My problem is that after I created my Dynamic Web Project, along with my web.xml and my index.html files, the index.html page doesn't show anything.
Servlet:
#WebServlet("/index.html")
public class AppServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String HTML_START = "<html><body>";
private static final String HTML_END = "</body></html>";
public AppServlet() {
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" type="text/css" href="styling.css">
<title>Test page</title>
</head>
<body>
<h1 style="text-align:center;">Example text</h1>
<div align="center">
<textarea rows="12" cols="120" style="border-radius: 5px"></textarea>
</div>
</body>
</html>
The html page shows up just fine when I open it directly (when I double click on the file in a directory), but when I start up the server from Eclipse and it redirects me to localhost:8080/MyProject/index.html, nothing shows up.
Each URL can be processed by a single component: Either your URL is resolved to the file index.html or to a servlet. In your case servlet has higher priority and this servlet (not the file index.html) creates the result. Your servlet doesn't create any contents in the doGet method. SO it is naturally that the response is empty.
If you want that this URL is resolved to the file index.html, then use some other URL mapping in the servlet, like #WebServlet("/bla"). Then when you call .../MyProject/index.html, you will get the contents of the file index.html.
You grab that PrintWriter but you don't do anything with it. With the first line of your snippet, you've told the Server that you are going to manage /index.html with code, and therefore it shouldn't go get it from the static content. Then your code produces nothing, so you are correctly seeing what your code produces.
Try adding this after PrintWriter out = response.getWriter();
out.println(HTML_START);
out.println("Hello World!");
out.println(HTML_END);
This question already has answers here:
Value passed with request.setAttribute() is not available by request.getParameter()
(2 answers)
Difference between getAttribute() and getParameter()
(10 answers)
Closed 4 years ago.
I am trying a simple example of sending values from a servlet Servlet1.java to client-side JSP page client1.jsp.
But I am getting null
Here is the code Server1.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.util.*;
#WebServlet("/server1")
public class Server1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String name="Rahul";
request.setAttribute("myname",name);
//Servlet JSP communication
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/client1.jsp");
reqDispatcher.forward(request,response);
}
}
Code for client1.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% String s=request.getParameter("myname");%>
Hello friends <%=s%>
</body>
</html>
What you do is bad.
First you are mixing attributes and parameters. They are different animals. Parameters is what comes from the client and are set once by the servlet container. Attributes are objects that are used by cooperating elements (filters, servlets and JSP pages) for passing data.
So you should at least read the attributes in JSP:
<% String (String) s=request.getAttribute("myname");%>
You must cast the attribute to String because getAttribute returns an Object.
But that's not all. Scriptlets are deprecated for decades, and should only be used for very special use cases, if any. Here, assuming you have a decent servlet container, you could simply use the ${} JSTL automatic attribute:
<body>
Hello friends ${myname}
</body>
It is shorter, cleaner and less error prone.
After your comments, there is another possible problem. You only show the override of doPost in your servlet code, when common requests (unless you post from a form) are GET requests and are processed in doGet. If you use a GET request and only set the attribute in doPost your JSP will not find it...
"myname" you are setting to request.setAttribute
so, you can retrieve as below:
<% String s=(String) request.getAttribute("myname");%>
This question already has answers here:
Calling a servlet from JSP file on page load
(4 answers)
Closed 6 years ago.
I didn't have trouble with this before, and I actually have a working implementation with a different class. But for some reason, this example fails.
I have a class called InfoServlet.java:
#WebServlet("/info_servlet")
public class InfoServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("test", "hello world.");
request.getRequestDispatcher("info_servlet.jsp").forward(request, response);
}
}
And my jsp page info_servlet.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
<h1>HELLO</h1>
<p><c:out value="${test}" /></p>
</body>
</html>
Now when I go to localhost:8080/MySite/info_servlet.jsp my output is only
HELLO
For reference, I'm using tomcat 7 and servlet 3.0 in java. I didn't have trouble passing in an object so I'm unsure why all the sudden it won't let me display the value in info_servlet.jsp
Everything works as expected. You are setting the "test" attribute within the servlet: if you go directly to the .jsp, bypassing the servlet, the attribute simply won't be set. Its value therefore will be null and the expression language will silently ignore it.
Background:
I have a servlet in which I am dynamically generating javascript and putting into a variable script. Then I set the response content type as text/javascript and send the script over to the client:
resp.setContentType("text/javascript");
resp.getWriter().println(script);
Problem:
The browser does download the javascript file but it doesn't recognize the functions inside the file. If I create a static javascript file and use it instead, it works fine.
Question:
What should be done so that browser treats response from the servlet as a regular javascript file?
Thank you for help.
It should work fine. I suspect that you're just including it the wrong way or calling the function too early or that the response content is malformed.
I just did a quick test:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 6156155</title>
<script src="javaScriptServlet"></script>
<script>test()</script>
</head>
<body>
</body>
</html>
with
#WebServlet(urlPatterns={"/javaScriptServlet"})
public class JavaScriptServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/javascript");
response.getWriter().write("function test() { alert('peek-a-boo'); }");
}
}
and I get
How do you refer to this servlet from your browser ?
If you want to include this with a HTML page (existing one), you should refer to it from the tag of your page.
Ex.
<html>
<head>
<script type='text/javascript' src='URL_TO_YOUR_SERVLET'></script>
</head>
</html>
Or if you want it to be executed as part of a Ajax call, just pass the response to eval function.
Or else, if you just want to send the output and get it executed in browser, you need to send the HTML segment as well. Then include your JS with in the body tags, as a script tag.
ex. Your servlet sends the following, using content type 'text/html' :
<html>
<body>
<script type='text/javascript'>
<!-- write your generated JS here -->
</script>
</body>
</html>
You could always write the script 'in-line' to the web page.
I think this way is better.
<%# page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
alert('Pure JavaScript right here!');
Set content type in JSP:
contentType="text/javascript; charset=UTF-8"
I'm attempting to upload a file into a jsp and then use the file in some other code. My problem is that it comes into the servlet as an Object via the request.getAttribute() call so I don't know what to cast it to.
I have this code so far to try and test what it is but I'm getting a NullPointerException.
test.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Input Test</title>
</head>
<body>
<form action="InputServlet" method="POST">
<input type="file" name="file1">
<input type="submit" value="submit">
</form>
</body>
</html>
inputservlet.java
public class InputServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(request.getAttribute("file1").getClass());
}
}
Is my understanding of whats going on flawed or am I just coding it up wrong?
Also I'm expecting the type to be Object so if anyone knows what I should cast it too that would be very helpful as well.
It's likely null because it concerns a brand new and different request. You probably have sent a redirect to the servlet instead of a forward?
Regardless, you should not process the file upload in a JSP file, but in a real servlet class. It's otherwise recipe for trouble since it's a view technology.
See also:
How to retrieve uploaded image and save to a file with JSP?
Apache Commons FileUpload user guide
Update: as per your code update, this won't work. You need to set form's enctype to multipart/form-data and use Commons FileUpload to process it in servlet. Also see the given links.
To the point, the multipart/form-data encoding is not supported by the Servlet API prior to 3.0 and the input values are not available by request.getParameter() and consorts. The use of request.getAttribute() here is a misconception. There it is not for. You would need to parse the request.getInputStream() yourself as per RFC2388. You would however like to use Apache Commons FileUpload for this instead of reinventing and maintaining a wheel for years. Apache Commons already did it for you, take benefit of it.
If you're already on Servlet 3.0 (Glassfish v3), then you can use the builtin request.getParts() to gather the items. Most servletcontainers will use Commons FileUpload under the hoods, you only don't see it in the /WEB-INF/lib or the imports, if that disturbs you for some reason.
See also:
How to get the file name for <input type="file"> in jsp
How to upload an image using JSP -Servlet and EJB 3.0