This question already has answers here:
How to get UTF-8 working in Java webapps?
(14 answers)
Closed 2 years ago.
Help fix the encoding in the servlet, it does not display Russian characters in the output.I will be very grateful for answers.
That is servlet code
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public static List<String> getFileNames(File directory, String extension) {
List<String> list = new ArrayList<String>();
File[] total = directory.listFiles();
for (File file : total) {
if (file.getName().endsWith(extension)) {
list.add(file.getName());
}
if (file.isDirectory()) {
List<String> tempList = getFileNames(file, extension);
list.addAll(tempList);
}
}
return list;
}
#SuppressWarnings("resource")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
request.setCharacterEncoding("utf8");
response.setContentType("text/html; charset=UTF-8");
String myName = request.getParameter("text");
List<String> files = getFileNames(new File("C:\\Users\\vany\\Desktop\\test"), "txt");
for (String string : files) {
if (myName.equals(string)) {
try {
File file = new File("C:\\Users\\vany\\Desktop\\test\\" + string);
FileReader reader = new FileReader(file);
int b;
PrintWriter writer = response.getWriter();
writer.print("<html>");
writer.print("<head>");
writer.print("<title>HelloWorld</title>");
writer.print("<body>");
writer.write("<div>");
while((b = reader.read()) != -1) {
writer.write((char) b);
}
writer.write("</div>");
writer.print("</body>");
writer.print("</html>");
}
catch (Exception ex) {
}
}
}
}
}
Here is what I have displayed instead of letters
п»ї ршншнщ олрршшш ошгншщ шгшг РѕСЂРѕСЂРіСЂРіСЂ Рто хрень работает СѓСЂР°
You're setting the character encoding on the request instead of the response. Change request.setCharacterEncoding("utf8"); to response.setCharacterEncoding("UTF-8");
Also: if the default character encoding of your system isn't UTF-8, you should explicitly set the encoding when reading from the file. To do that, you'd need to use an FileInputStream
pRes.setContentType("text/html; charset=UTF-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(pRes.getOutputStream(), "UTF8"), true);
use this one i got the exact result :)
Related
hello everyone i have created one Servlet file. it is downloading as a excel file but not containing any data in it while the code is made build for writing a data in excel file. Basically i have done this steps :-
1. access the data from the database
2.print that data to excel file.
now up to this working as per the expectation but now at time of excel file gets downloaded. that time it is a blank excel file no data contains in that file. Why it is so Please Shed some light i have just started learning JAVA and SERVLET really new to this.
package servletProject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/ExcelFile")
public class CSVServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
String emails = "xyz#gmail.com";
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
FileWriter writer =null;
ResultSet rs=null;
Connection con=null;
PreparedStatement ps=null;
try {
String fileName = emails+"data.csv";
System.out.println(fileName);
ServletContext context = getServletContext();
String mimeType = context.getMimeType(fileName);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
ConnectionClass cn = new ConnectionClass();
con = cn.connectDb();
System.out.println("fileName"+fileName);
writer = new FileWriter(fileName);
//Write the CSV file header
CSVUtils.writeLine(writer,Arrays.asList("NAME","email"));
ps = con.prepareStatement("select firstName,email from employees");
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("firstName"));
CSVUtils.writeLine(writer,Arrays.asList(rs.getString("firstName"),rs.getString("email")));
}
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
try{ rs.close();ps.close();con.close();}catch (Exception e) {}
}
}
}
// DB connection File
public class ConnectionClass {
public Connection connectDb() {
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels","root","root");
}catch (Exception e) {
con=null;
}
if(con!=null)
System.out.println("connected");
else
System.out.println("not connected");
return con;
}
}
//CSVUtil Files
package servletProject;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class CSVUtils {
private static final char DEFAULT_SEPARATOR = ',';
public static void writeLine(Writer w, List<String> values) throws IOException {
writeLine(w, values, DEFAULT_SEPARATOR, ' ');
}
public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
writeLine(w, values, separators, ' ');
}
// https://tools.ietf.org/html/rfc4180
private static String followCVSformat(String value) {
String result = value;
if (result.contains("\"")) {
result = result.replace("\"", "\"\"");
}
return result;
}
public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {
boolean first = true;
// default customQuote is empty
if (separators == ' ') {
separators = DEFAULT_SEPARATOR;
}
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (!first) {
sb.append(separators);
}
if (customQuote == ' ') {
sb.append(followCVSformat(value));
} else {
sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
}
first = false;
}
sb.append("\n");
w.append(sb.toString());
}
}
Here is a version that writes to the response's outputstream.
Note that I changed 'writer' to be an OutputStream instead of a FileWriter, as that is what you get from response.getOutputStream().
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
OutputStream writer = response.getOutputStream();
:
//Write the CSV file header
//(no change from your code here.)
CSVUtils.writeLine(writer,Arrays.asList("NAME","email"));
This requires you to alter your CSVUtils class to accept an OutputStream instead of a Writer object, but there isn't much difference there...
public static void writeLine(OutputStream w, etc...) throws IOException {
:
sb.append("\n");
String str = sb.toString();
byte[] bytes = str.getBytes(Charset.forName("UTF-8"));
w.write(bytes);
}
I highly recommend using a library for CSV files, such as http://opencsv.sourceforge.net/ as they provide lots of great functionality.
My problem is, that after uploading the content of file is [object Object].
How can I upload a file properly?
Server:
package com.turbulence6th.servlets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet("/saveFile")
#MultipartConfig
public class SaveFile extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String webAppPath = getServletContext().getRealPath("/");
Part file = request.getPart("file");
String filename = getFileName(file);
InputStream is = file.getInputStream();
String directoryPath = webAppPath + File.separator + "files";
File directory = new File(directoryPath);
if(!directory.exists()){
directory.mkdir();
}
String filePath = directoryPath + File.separator + filename;
FileOutputStream fos = new FileOutputStream(filePath);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
fos.close();
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
}
Client:
using (var wb = new WebClient())
{
wb.UploadFile("http://" + host + ":8080/saveFile", "POST", path);
}
I don't see any manipulations with response. Inside doPost you copy file content to the request. Is it what you want?
By the way - I don't see any reason to not use copy().
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 7 years ago.
I'm learning about servlets in java and I'm trying to capture a URL content and store it into a string array. Bellow is my code that I put together following some tutorials that does not seem to work servlet environment (This is the first part of an exercise that I'm trying to do).
I'm getting the error at this line:
cookies.add(line);
Here is the complete code:
//package fortune;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static java.util.Arrays.*;
#WebServlet(name = "FortuneServlet", urlPatterns = {"/"})
public class FortuneServlet extends HttpServlet {
private String [] cookies = null;
//ArrayList<String[]> cookies = new ArrayList<String[]>();
public void geturl(String[] args) {
try
{
URL url = new URL(" http://fortunes.cat-v.org/openbsd/");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = in.readLine();
while((line = in.readLine()) != null)
{
cookies.add(line);
line = in.readLine();
}
in.close();
}
catch (java.net.MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
}
public void init() throws ServletException {
// Add your own code here!
// 1) Open the URL
// 2) Get the contents
// 3) Extract the cookie texts to an array
}
#Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
if (cookies != null) {
response.getWriter().println(
cookies[new Random().nextInt(cookies.length)]
);
} else {
response.getWriter().println("No luck!");
}
}
}
private String [] cookies = null;
Here you initialize an array of strings and set it to null.
cookies.add(line);
Here you assume that there is an add() method for the array, which it doesn't have.
You should go with the commented out solution, using a List, which has the add() method. You shouldn't use a list of arrays, but a list of strings:
List<String> cookies = new ArrayList<>();
Then you can add the cookies in the way you already do:
cookies.add(line);
You cant add() method on an array. You have to use List. So instead of
private String [] cookies = null;
use
private List<String> cookies = new ArrayList<String>();
This question already has answers here:
How to extract file extension from byte array
(3 answers)
Closed 7 years ago.
I am developing a web app, which has the functionality of displaying images obtained from a server. I learned that I can do it by returning byte array in response.
It seems that I am able to do it through:
#RequestMapping(value = "url/img", method = RequestMethod.POST)
#ResponseBody
public MyDto proceedDocumentFromUrl(#RequestParam final String url) throws IOException {
return somethingDoer.do(toByteArray(new URL(url).openStream());
}
somethingDoer.do returns Dto object which contains byte[] In field named image. For test purposes I would like to determine the image extension (it is always .jpg).
How can I do that? I was looking in Wiki and W3 documents for some clue(I suppose it is about first few bytes) but was unable to find a solution.
Please check this getFormatName(file) method and check Class ImageReader
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("image.gif");
System.out.println(getFormatName(file));
InputStream is = new FileInputStream(file);
is.close();
System.out.println(getFormatName(is));
}
private static String getFormatName(Object o) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(o);
Iterator iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
return null;
}
ImageReader reader = (ImageReader) iter.next();
iis.close();
return reader.getFormatName();
} catch (IOException e) {
}
return null;
}
}
Please check https://github.com/arimus/jmimemagic to get extension from byte[]
byte[] data = someData
MagicMatch match = Magic.getMagicMatch(data);
System.out.println( match.getMimeType());
I have a problem with the servlet that I'm making. You have to log into a system and you also need to log out, I use a file register the users. Login works fine, it reads the user from the file, but for some reason logout doesn't. I get an error when I press the logout-button:
Here is the code for the class LogoutServlet
package nl.hu.sp.lesson1.dynamicexample;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
RequestDispatcher rd = null;
try {
String data = null;
File file = new File(
"C:/apache-tomcat-8.0.5/webapps/LoginAssignment/loggedusers.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while ((data = br.readLine()) != null) {
String[] de = data.split(" ");
if (de[0].equals("vimal")) {
data.trim();
rd = req.getRequestDispatcher("testpage.html");
}
}
rd.forward(req, resp);
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You are reading a text file and searching for "vimal", if it is found you are initializing rd; if it is not found rd is null. It cannot find "vimal" in text file and rd becomes null so it throws null pointer exception.
Add null check
if (rd != null) {
rd.forward(req, resp);
}