I am writing an application with Google App Engine.
The app can receiver eMails now and I can see these in the console.
What I want is that the three variables (summary, addresses and text) are visible in the frontend (guestbook.jsp).
I tried to various options (see commented code) but none of them showed me the information in the frontend.
By now I only tried to pass one variable (summary).
Later on I want to store the information in a database.
Servlet:
package com.example.mail;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.*;
import javax.mail.Address;
public class MailHandlerServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try{
MimeMessage message = new MimeMessage(session, req.getInputStream());
String summary = message.getSubject();
Address[] addresses = message.getFrom();
String text = message.getContent().toString();
System.out.println("Subject: " + summary);
System.out.println("Sender: " + addresses);
System.out.println("Text: " + text);
req.setAttribute("summary",summary);
req.getRequestDispatcher("/mail.jsp").forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
mail.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="java.util.List" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css"/>
</head>
<body>
Hello World!
<p>E-Mail Summary '${summary}'.</p>
</body>
</html>
Web.xml:
<servlet>
<servlet-name>mailhandler</servlet-name>
<servlet-class>com.example.mail.MailHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mailhandler</servlet-name>
<url-pattern>/_ah/mail/string#appid.appspotmail.com</url-pattern>
</servlet-mapping>
Would be nice if someone could help me.
You need to use request.setAttribute("summary", summary); to add summary as a request attribute, and since a redirect isnt server side, it's client side, the attributes are no longer shown, you'll need to use req.getRequestDispatcher("mail.jsp").forward(req, resp);
Related
I want to edit an jsp file from textarea in browser. So i need to upload jsp content to textarea.
For example i have a readMe.jsp file like that:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>Read Me</h1>
<p> This is read me content</p>
I want this edit like that:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>Read Me</h1>
<p> This is read me content</p>
<hr>
<h2>Read Me Second Head</h2>
<p>This is read me content 2</p>
The way I think to be able to do this in the browser is to upload the jsp content to textarea and edit it from there. Does anyone know how I can do this?
If I have a way to edit a jsp file differently from the browser, it can also be.
Thanks.
This is just an example how a JSP page can be edited from a browser.
webapp/readme.jsp is a page to edit.
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>Read Me</title>
</head>
<body>
<h1>Read Me</h1>
<p> This is read me content</p>
<p>Edit this page</p>
</body>
</html>
webapp/edit/readme.jsp contains a form within that a content of a readme.jsp page can be edit.
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>Edit | Read Me</title>
</head>
<body>
<h1>'Read Me' edit page</h1>
<form method="post" action="${pageContext.request.contextPath}/edit/readme">
<label>
<textarea name="newContent" cols="96" rows="16">${content}</textarea>
</label>
<br><br>
<button type="submit">Save</button>
</form>
</body>
</html>
EditReadMe.java is a servlet.
The method doGet is triggered by the Edit this page link from the webapp/readme.jsp. It read content from the webapp/readme.jsp file and passes it to the webapp/edit/readme.jsp.
The method doPost is responsible for working with the form from the webapp/edit/readme.jsp and updating content for the webapp/readme.jsp file.
package com.example.editjsp;
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 java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
#WebServlet(name = "readMeEditor", value = "/edit/readme")
public class EditReadMe extends HttpServlet {
private static final String RESOURCE_PATH = "/readme.jsp";
private Path pathToFile;
#Override
public void init() {
pathToFile = Path.of(getServletContext().getRealPath(RESOURCE_PATH));
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String contentToEdit = Files.readString(pathToFile);
req.setAttribute("content", contentToEdit);
req.getRequestDispatcher("/edit/readme.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Files.writeString(pathToFile, req.getParameter("newContent"));
resp.sendRedirect(req.getContextPath() + RESOURCE_PATH);
}
}
I am trying to parse file from local drive (Windows 10) to server running on Linux box. The servlet is less than 3.0 version so I am using the Apache FileUpload and IO jars. I have 2 problems trying to parse the file.
The submit using <input type = "submit" value = "Upload File" > currently won't submit the data so I am using <button id="ok" onclick="document.forms[0].submit();return false;">Submit</button>.
Second and more serious problem is that I am not able to upload parsed data to List. After I submit the form, the List is empty. I have commented out every method in jsp form so I should not read and parse the request body before the Apache upload (but I am no sure how to verify the body is not empty before I try to read the file). I have also tried to upload the text instead of file (to check if the there is problem trying to access windows file system) but with no success.
Maybe I am missing something obvious. Can you please give me some hints how to troubleshoot this. Thank you
JSP (old file)
<%# page language="java" %>
<%# page contentType="text/html; charset=UTF-8" %>
<%# include file="upload_function.jspf" %>
<%String pageLanguage=getLanguage(request);%>
<%# MultipartConfig%>
<%#WebServlet("/upload")%>
<html>
<head>
<link rel="stylesheet" type="text/css" href="upload.css"></link>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" ></form>
<div>
<tr>
<h4>Uploaded File:</h4>
<%=getLocalImage(request)%>
</tr>
</div>
<div>
<tr>
<label for=""><h4>File Upload:</h4></label>
<input type="file" id="image" name="image" accept="image/png, image/jpeg" >
<input type = "submit" value = "Upload File" >
</tr>
</div>
<div>
<tr>
<p>
<button id="ok" onclick="document.forms[0].submit();return false;">Submit</button>
<button id="cancel" onclick="javascript:window.close();return false;">Ok</button>
</p>
</tr>
</div>
</form>
</body>
</html>
JSPF (old file)
<%# page import="java.io.*" %>
<%# page import="java.util.*" %>
<%# page import="javax.servlet.*" %>
<%# page import="org.apache.commons.fileupload.disk.*" %>
<%# page import="org.apache.commons.fileupload.servlet.*" %>
<%# page import="org.apache.commons.fileupload.*" %>
<%# page import="org.apache.commons.io.*" %>
<%!
public String getLocalImage(HttpServletRequest request) throws ServletException, IOException
{
String result = "null";
String UPLOAD_DIRECTORY = "/final/directory/for/file/upload/";
// Check the content
if(ServletFileUpload.isMultipartContent(request)){
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setSizeThreshold(40960);
factory.setRepository(repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(2000000);
// Parse the request
try {
List<FileItem> items = upload.parseRequest(request);
}
catch(Exception ex){
ex.printStackTrace();
}
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
File uploadedFile = new File(UPLOAD_DIRECTORY,"picture.png");
// List<FileItem> items is empty - error trying to use the iterator
FileItem item = iter.next();
item.write(uploadedFile);
result = "file upload successful";
}
catch (Exception t) {
t.printStackTrace();
return result;
}
return result;
}
else {
return "not multipart";
}
}
%>
Edit:
So I think main problem was, I did not connect the jsp file with the servlet through the action attribute in the form.
I have created the functional example of the upload servlet but I would need to import the UploadServlet class into JSP file without actually using the .java project file.
I have created the jar file of the UploadServlet class and add the jar file into the WEB-INF/lib folder of the web app. But when I try to create the instance of the UploadServlet class, IDE tells me it can't be resolved to the type.
Is it possible to import the user defined class into JSP like this? Do I e.g. need some more dependencies? I am not sure what about the tomcat servlet-api.jar, the UploadServlet jar is probably trying to use it but the servlet-api classes are outside of the web app. Hovewer it is not possible to include the servlet-api.jar directly under the WEB-INF/lib web app.
UploadServlet.java ---> UploadServlet.jar
package test.pkg;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
// constructor
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// doPost implementation
}
}
JSP with UploadServlet
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="test.pkg.UploadServlet" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload: <input type="file" name="uploadFile" />
<input type="submit" value="Upload" />
<%
UploadServlet servletUp = new UploadServlet();
servletUp.doPost(request, response);
%>
</form>
</body>
</html>
I'm answering with your previous commentary in mind where you asked if the Servlet could be defined in a JSP, as you were not sure you would have access to Java classes in this project.
You can, as you have access to the request and response inside any JSP, like any other servlet (JSP is a servlet). That said, you should separate the form from the handling of its values. A generally good pattern to use is POST-REDIRECT-GET.
I'm using JSTL for the form as this is better practice.
To handle the request in another JSP, I'm forced to resort to scriptlets, which is usually a sign of bad design, but considering you can't edit Java source, no other choice...
Page containing form: fileUploadForm.jsp
Set your form to POST to another page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My upload file test form</title>
</head>
<body>
<h1>My upload file test form</h1>
<!-- Display messages -->
<div class="messages">
<c:if test="${not empty sessionScope.uploadErrors}">
<c:forEach items="${sessionScope.uploadErrors}" var="err">
<p class="error"><c:out value="${err}" /></p>
</c:forEach>
</c:if>
<c:if test="${not empty sessionScope.uploadSuccess}">
<p class="success">File uploaded successfully: <c:out value="${sessionScope.uploadSuccess}" /></p>
</c:if>
</div>
<!-- Form with POST action pointing to uploadFormAction.jsp -->
<form name="upload-test" action="./uploadFormAction.jsp" method="POST" enctype="multipart/form-data">
<label for="upload">Upload file:</label>
<input type="file" name="uploaded" id="upload" accept="image/png" />
<div class="submits">
<input type="submit" value="Send" />
</div>
</form>
</body>
</html>
JSP with data handling code: fileUploadAction.jsp
Handle the POST request, record the result (errors or success), and then redirect back to your form to show them
<%#page import="org.apache.commons.fileupload.FileItem"%>
<%#page import="java.io.File"%>
<%#page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
<%#page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//Storage for error messages
List<String> errors = new ArrayList<>();
session.setAttribute("uploadErrors", errors);
session.setAttribute("uploadSuccess", null);
//Check for correct form encoding
if (!"POST".equalsIgnoreCase(request.getMethod())) {
errors.add("Form must have method=\"POST\"");
}
if (!ServletFileUpload.isMultipartContent(request)) {
errors.add("Form has no multipart data to read from");
}
if (errors.size() < 1) {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4L * 1024 * 1024);
// Parse the request
List<FileItem> items = upload.parseRequest(request);
String found = null;
for (FileItem item : items) {
if (item.isFormField()) {
//Process other fields in form
} else if ("uploaded".equals(item.getFieldName())) {
if (item.getSize() > 0) {
if (found != null) {
errors.add("Only one file allowed");
} else {
found = item.getName();
File uploadedFile = new File("./uploads/","picture.png");
if (uploadedFile.exists()) uploadedFile.delete();
item.write(uploadedFile);
}
}
} else { //Other file field
//Ignore it ? error ?
}
}
if (found == null) {
errors.add("No uploaded file !");
}
session.setAttribute("uploadSuccess", found);
} catch (Exception e) {
e.printStackTrace();
//Should log it and return it in a more readable form
errors.add(e.getMessage());
}
}
response.sendRedirect("uploadFormPage.jsp");
%>
Now considering your question edits, if you have your Servlet class already defined and want to call it from a JSP, then I suppose you could use the same principles as described here, and create a new intance of the servlet to call its doPost Method where you get the POST request, but that's supposing your servlet is stateless and doesn't use init parameters from web.xml...
How you should do it if you can write a Servlet
Keep the same form code, just change the destination of your <form> to action="<c:url value ="/uploadFile" />"
Create your Servlet with url pattern set to "/uploadFile" to handle the POST (e.g. using #WebServlet annotation), and same code as fileUploadAction.jsp
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#WebServlet("/uploadFile")
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//Storage for error messages
List<String> errors = new ArrayList<>();
session.setAttribute("uploadErrors", errors);
session.setAttribute("uploadSuccess", null);
//Check for correct form encoding
if (!"POST".equalsIgnoreCase(request.getMethod())) {
errors.add("Form must have method=\"POST\"");
}
if (!ServletFileUpload.isMultipartContent(request)) {
errors.add("Form has no multipart data to read from");
}
if (errors.size() < 1) {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4L * 1024 * 1024);
// Parse the request
List<FileItem> items = upload.parseRequest(request);
String found = null;
for (FileItem item : items) {
if (item.isFormField()) {
//Process other fields in form
} else if ("uploaded".equals(item.getFieldName())) {
if (item.getSize() > 0) {
if (found != null) {
errors.add("Only one file allowed");
} else {
found = item.getName();
File uploadedFile = new File("./uploads/","picture.png");
if (uploadedFile.exists()) uploadedFile.delete();
item.write(uploadedFile);
}
}
} else { //Other file field
//Ignore it ? error ?
}
}
if (found == null) {
errors.add("No uploaded file !");
}
session.setAttribute("uploadSuccess", found);
} catch (Exception e) {
e.printStackTrace();
//Should log it and return it in a more readable form
errors.add(e.getMessage());
}
}
response.sendRedirect("uploadFormPage.jsp");
}
}
This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 3 years ago.
I am trying to retrieve multiple images from database and display those images in another JSP page.
First, I tried single image to display in particular JSP page, I retrieved but the display is showing as file type,
I want to display that image in particular JSP page.
I am using MySQL database.
my servlet code:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
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("/Retrieve")
public class Retrieve extends HttpServlet {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{ Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vikas", "root", "root");
ps = con.prepareStatement("select * from rough");
rs=ps.executeQuery();
if (rs.next()) {
byte[] content = rs.getBytes("image");
response.setContentLength(content.length);
response.getOutputStream().write(content);
request.setAttribute("image", content);
RequestDispatcher rd=request.getRequestDispatcher("View.jsp");
rd.forward(request, response);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
}
} catch (SQLException e) {
throw new ServletException("Something failed at SQL/DB level.", e);
}
}
}
jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Display Image</title>
</head>
<body>
<div>THE DISPLAY</div>
<div style="width:25%; height:25%">
<%request.getAttribute("image"); %>
</div>
</body>
</html>
Try using Base64 encoding,
Use Apache Commons Codec to do Base64 encodings.
byte[] content = rs.getBytes("image");
String base64Encoded = new String(Base64.encodeBase64(content), "UTF-8");
request.setAttribute("imageBt", base64Encoded);
Retrieve it from JSP
<img src="data:image/png;base64,${requestScope['imageBt']}"/>
For multiple images you could try something like this, (i didnt try this)
List<String> images = new ArrayList<>();
if (rs.next()) {
byte[] content = rs.getBytes("image");
images.add(new String(Base64.encodeBase64(content), "UTF-8"));
}
request.setAttribute("imageBt", images);
In JSP
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:forEach var="img" items="${imageBt}">
<img src="data:image/png;base64, ${img}"/>
</c:forEach>
I'm creating a JSP/Servlet web application and I'd like to upload a file to a Servlet with progress bar.
This is an example of uploading file with jsp and servlet.
Its working but i want to add to it a progress bar.
The FileUploadHandler.java
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet to handle File upload request from Client
* #author Javin Paul
*/
public class FileUploadHandler extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "uploads";
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
String name = null;
//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
name = new File(item.getName()).getName();
item.write( new File(uploadPath+name));
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully "+uploadPath+ name);
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
The upload.jsp
<%#page contentType="text/html" 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>File Upload Example in JSP and Servlet - Java web application</title>
</head>
<body>
<div>
<h3> Choose File to Upload in Server </h3>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>
</div>
</body>
</html>
The result.jsp
<%#page contentType="text/html" 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>File Upload Example in JSP and Servlet - Java web application</title>
</head>
<body>
<div id="result">
<h3>${requestScope["message"]}</h3>
</div>
</body>
</html>
The web.xml
<servlet>
<servlet-name>FileUploadHandler</servlet-name>
<servlet-class>FileUploadHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadHandler</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Though late, try using following plugin, which makes your UI beautiful and super easy.
https://github.com/blueimp/jQuery-File-Upload
Java examples are as follows:
https://github.com/blueimp/jQuery-File-Upload/wiki
I need to include .jsp file in my servlet.
I have written simple jsp file, which i have put in dir WEB-INF/jsps/:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title> Galleries </title>
</head>
<body>
Test
</body>
</html>
and servlet:
package photoGallery;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
public class GalleriesServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
System.out.println("Test");
//get the request dispatcher
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsps/galleries.jsp");
//forward to the jsp file
if (dispatcher != null)
dispatcher.forward(request, response);
else
System.err.println("Error: dispathcer is null");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
in web.xml I have added next lines:
<servlet>
<display-name>Gallery Servlet</display-name>
<servlet-name>GalleryServlet</servlet-name>
<servlet-class>photoGallery.GalleriesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GalleryServlet</servlet-name>
<url-pattern>/galleries/*</url-pattern>
</servlet-mapping>
When I'm openning page
http://localhost:8080/PhotoGallery/galleries
then in console it prints "Test", but in browser I see "HTTP Status 404 - Not Found"
Where I have made mistake?
I have found my mistake.
There was other servlet which was mapped to "/*", and because of that appeared errors