passing the object from one servlet to another - html

i have a HTML form(index.html) of three links which are login, logout and profile. After clicking on login link a HTML page is displayed with two fields named username and password. After entering correct username and password my servlet1 responses a message like "welcome user". my logout link is associated with a servlet2 which deletes cookies for current request and displays a message "successfully logout" when clicked. I would like to know all request and response objects associated with three links(login,logout,profile) in my index.html file
will be same for a user? i am also mentioning my code here:
login.java:
package loginandlogout;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Login extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
request.getRequestDispatcher("link.html").include(request,response);
String name=request.getParameter("username");
String password=request.getParameter("password");
if(password.equals("admin"))
{
out.println("you are successfully login...");
out.println("welcome "+name);
Cookie ck= new Cookie("name",name);
response.addCookie(ck);
}
else
{
out.println("Not authorized");
request.getRequestDispatcher("login.html").include(request, response);
}
}
}
logout.java:
package loginandlogout;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Logout extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
int j=0;
response.setContentType("text/html");
PrintWriter out= response.getWriter();
Cookie ck[]=request.getCookies();
if(ck==null||ck[0].equals(""))
{
request.getRequestDispatcher("link.html").include(request, response);
out.println("without login how can logout you..");
}
else
{
int i;
int size1=ck.length;
for(i=0; i<size1; i++)
{
String ckname=ck[i].getValue();
if(ckname.equals(request.getParameter("username")))
{
out.println("successfully logout when i am in loop");
j=i;
break;
}
}
ck[j]=new Cookie("name","");
ck[j].setMaxAge(0);
response.addCookie(ck[j]);
request.getRequestDispatcher("link.html").include(request, response);
out.println("successfully logout " +ck[j].getValue());
}
}
}
profile.java
package loginandlogout;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Profile extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
Cookie ck[]=request.getCookies();
if(ck !=null)
{
String name= ck[0].getValue();
if(!name.equals("")|| name!=null)
{
out.println("welcome "+name);
}
else
out.println("please loing first");
}
else
{
out.println("please loing first");
}
}
}
index.html:
<!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>home page</title>
</head>
<body>
<h1>welcome to my home page...</h1>
<br />
login|
logout|
profile
</body>
</html>

Related

Thymeleaf site doesn't read content of css file

I try to write my website with spring framework in back- and thymeleaf in frontend on tomcat local server. I try add css to my html file. Css file seems to be linked on server, but devtools shows that it is empty. Do you know what could i miss?
EDIST: sorry for posting pictures, I will know better next time. I left minimum i wanted to show.
index.css
h1{
color: red;
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleag.org">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/index.css" th:href="#{../css/index.css}"/>
</head>
<body>
<h1>Hello</h1>
Greeting
Registration
</body>
</html>
HomePageController.java
package com.krs.GreatBookOfDiet.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
#Controller
public class HomePageController {
#GetMapping("")
public String index(Map<String, Object> model){
return "index";
}
}
GreatBookOfDietConfiguration.java
package com.krs.GreatBookOfDiet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import java.util.Locale;
#Configuration
public class GreatBookOfDietConfiguration implements WebMvcConfigurer {
#Autowired
private ApplicationContext applicationContext;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**").addResourceLocations("/WEB-INF/pdf/");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
#Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US);
return slr;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
#Bean
public ViewResolver thymeleafResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(0);
return viewResolver;
}
#Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
}
file structure
devtools on server, index.css view
Your static resources in the /WEB-INF/css folder are not served by Spring, therefore a request for http://example.com/app/css/index.css returns a 404 error.
You need to modify your addResourceHandlers method:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("/WEB-INF/pdf/");
registry.addResourceHandler("/css/**")
.addResourceLocations("/WEB-INF/css/");
}
Remark: Given the popularity of Spring Boot, you might consider using the same locations for static resources (cf. documentation), which sums up to the following configuration:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/");
}

The path to a database with jee maven project

I'm currently making a website with Java EE, using maven, thymeleaf, and hosting it on heroku (database addon is JawsDBMySQL).
I've created a simple html page in order to check the good working of it.
Of course it works perfectly for a local upload : the file goes to a folder I've designed.
In my data base the path to my local storage is stored as a string.
I've also add a longblob column, but I did not really understood how to use it.
Now I want to store files into my database when my application is online.
I didn't found solution that perfectly match with my issue, but I'm quite sure it is pretty simple.
Hoping I have been clear enough,
thanks for your help.
Servlet that display a page on /home2 with the list of the pictures
package marquise.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import marquise.services.InformationLibrary;
#WebServlet("/home2")
public class HomeServlet extends AbstractGenericServlet2 {
private static final long serialVersionUID = 5402133218271984030L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
TemplateEngine templateEngine = this.createTemplateEngine(req);
WebContext context = new WebContext(req, resp, getServletContext());
//Country countryFilter = (Country) req.getSession().getAttribute("countryFilter");
context.setVariable("images", InformationLibrary.getInstance().listAllImages());
//context.setVariable("cities", CityService.getInstance().listAllCities(countryFilter));
//context.setVariable("countries", Country.values());
//context.setVariable("countryFilterSelected", countryFilter);
templateEngine.process("home", context, resp.getWriter());
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String countryString = req.getParameter("countryFilter");
resp.sendRedirect("home2");
}
}
Servlet for the path
#WebServlet("/imagepicture")
public class CityPictureServlet extends AbstractGenericServlet2 {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Integer imageId = Integer.parseInt(req.getParameter("id"));
Path picturePath = InformationLibrary.getInstance().getPicturePatch(imageId);
Files.copy(picturePath, resp.getOutputStream());
}
}
servlet that print image details (not important right now)
package marquise.servlets;
#WebServlet("/detail")
public class CityDetailServlet extends AbstractGenericServlet2 {
private static final long serialVersionUID = 8559083626521311046L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
TemplateEngine templateEngine = this.createTemplateEngine(req);
WebContext context = new WebContext(req, resp, getServletContext());
Integer idImage = Integer.parseInt(req.getParameter("id"));
context.setVariable("image", InformationLibrary.getInstance().getImage(idImage));
//context.setVariable("comments", InformationLibrary.getInstance().listCommentsByCity(idCity));
context.setVariable("comments", InformationLibrary.getInstance().listAllImages());
templateEngine.process("imagedetail", context, resp.getWriter());
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Integer cityId = Integer.parseInt(req.getParameter("id"));
resp.sendRedirect(String.format("detail?id=%d", cityId));
resp.sendRedirect("home2");
}
}
HTML page displaying the list of my images
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>City Explorer</title>
<link rel="stylesheet" href="bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="fontawesome/css/font-awesome.min.css">
<link rel="stylesheet" href="css/custom.css">
</head>
<body>
<header th:replace="~{common::header}"></header>
<div id="mainContent" class="container-fluid">
<section class="cityfilters">
<h3>Filters</h3>
<form class="form-inline" method="post">
<div class="form-group">
<label for="countryInput">Country</label>
<select class="form-control" id="countryInput" name="countryFilter">
<option value="">All countries</option>
<option th:each="country : ${countries}" th:value="${country}" th:selected="${countryFilterSelected} == ${country}">[[${country.label}]]</option>
</select>
</div>
<input type="submit" class="btn btn-default" value="Filter">
</form>
</section>
<section class="citylist">
<article class="citybox" th:each="image : ${images}">
<h3>
[[${image.name}]]
<a th:href="'deleteimage?id='+${image.id}" class="btn btn-xs btn-danger pull-right">
<i class="fa fa-times" aria-hidden="true"></i>
</a>
</h3>
<p th:text="${image.summary}" class="summary"></p>
<div class="btn-toolbar actionbar" role="toolbar">
<div class="btn-group" role="group">
<a th:href="'detail?id='+${image.id}" class="btn btn-primary"><i
class="fa fa-eye" aria-hidden="true"></i> See details</a>
</div>
</div>
<aside class="cityPhoto">
<img th:src="'imagepicture?id='+${image.id}" th:alt="'Vignette '+${image.name}">
</aside>
</article>
</section>
</div>
</body>
</html>
My Library Class with the path to my computer
public class InformationLibrary {
private static class InformationLibraryHolder{
private final static InformationLibrary instance = new InformationLibrary();
}
public static InformationLibrary getInstance(){
return InformationLibraryHolder.instance;
}
private InformationDao informationDao = new InformationDaoImpl();
private UtilisateurDao utilisateurDao = new UtilisateurDaoImpl();
private CommentaireDao commentaireDao = new CommentaireDaoImpl();
private ArticleDao articleDao = new ArticleDaoImpl();
private IdentifiantDao identifiantDao = new IdentifiantDaoImpl();
private ImageDao imageDao = new ImageDao();
private static final String PICTURE_MAIN_DIRECTORY = "/Users/louiscauvray/git/projet/src/main/resources";
private ElementsSiteDao elementsSiteDao = new ElementsSiteDao();
private InformationLibrary() {
}
//Recuperer les informations sur les utilisateurs
public List<Information> listFilms() {
return informationDao.listInformations();
}
public Information getInformation(Integer id) {
return informationDao.getInformation(id);
}
public Information addInformation(Information information) {
return informationDao.addInformation(information);
}
public List<Utilisateur> listUtilisateurs() {
return utilisateurDao.listUtilisateurs();
}
public Utilisateur getUtilisateur(Integer id) {
return utilisateurDao.getUtilisateur(id);
}
public Utilisateur getUtilisateurByNom(String nom){
return utilisateurDao.getUtilisateurByNom(nom);
}
public Utilisateur addUtilisateur(String nom, String prenom) {
return utilisateurDao.addUtilisateur(nom, prenom);
}
//Gerer les commentaires visible en backoffice
public List<Commentaire> listCommentaires(){
return commentaireDao.listCommentaires();
}
public Commentaire addCommentaire(String email ,String commentaire){
return commentaireDao.addCommentaire(email, commentaire);
}
public List<Article> listArticles(){
return articleDao.listArticles();
}
public Article addArticle(String title, String texte, LocalDate datePublication, String auteur) {
return articleDao.addArticle(title, texte, datePublication, auteur);
}
public Identifiant getIdentifiant(String login, String motDePasse){
return identifiantDao.getIdentifiant(login, motDePasse);
}
//Methode pour appeler les image et les chemins des images
public List<Image> listAllImages() {
return imageDao.listImages();
}
public Image getImage(Integer id) {
if(id == null) {
throw new IllegalArgumentException("Image id must be provided.");
}
return imageDao.getImage(id);
}
public void addImage(Image newImage, Part picture) throws IOException {
if(newImage == null){
throw new IllegalArgumentException("An image must be provided.");
}
if(newImage.getName() == null || "".equals(newImage.getName())) {
throw new IllegalArgumentException("An image must have a name.");
}
if(newImage.getSummary() == null || "".equals(newImage.getSummary())) {
throw new IllegalArgumentException("An image must have a summary.");
}
if(picture == null){
throw new IllegalArgumentException("An image must contain a picture.");
}
Path picturePath = Paths.get(PICTURE_MAIN_DIRECTORY, picture.getSubmittedFileName());
imageDao.addImage(newImage, picturePath.toString());
Files.copy(picture.getInputStream(), picturePath);
}
public Path getPicturePatch(Integer imageId) {
String picturePathString = imageDao.getPicturePath(imageId);
if(picturePathString == null) {
return getDefaultPicturePath();
} else {
Path picturePath = Paths.get(imageDao.getPicturePath(imageId));
if(Files.exists(picturePath)) {
return picturePath;
} else {
return getDefaultPicturePath();
}
}
}
private Path getDefaultPicturePath() {
try {
return Paths.get(this.getClass().getClassLoader().getResource("city-no-photo.png").toURI());
} catch (URISyntaxException e) {
return null;
}
}
// ElementsSite Dao
public void modifierElementTexte(String idElement, String contenuElement) {
elementsSiteDao.modifierElementTexte(idElement, contenuElement);
}
public void modifierElementImage(String idElement, String contenuElement, String cheminElement) {
elementsSiteDao.modifierElementImage(idElement, contenuElement, cheminElement);
}
public ElementsSite getElementById(String id) {
return elementsSiteDao.getElementById(id) ;
}
}
My Dao Class where methods to display images are defined
import marquise.daos.impl.DataSourceProvider;
import marquise.exceptions.CityExplorerRuntimeException;
import marquise.projos.Image;
public class ImageDao {
public List<Image> listImages() {
List<Image> images = new ArrayList<Image>();
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM image ORDER BY name")) {
while (resultSet.next()) {
images.add(
new Image(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("summary")));
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return images;
}
public Image getImage(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return new Image(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("summary"));
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}
public void addImage(Image newImage, String picturePath) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("INSERT INTO image(name, summary, picture) VALUES (?, ?, ?)")) {
statement.setString(1, newImage.getName());
statement.setString(2, newImage.getSummary());
statement.setString(3, picturePath);
statement.executeUpdate();
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
}
public String getPicturePath(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT picture FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getString("picture");
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}
}
Finally I found a solution to my problem :
I added a longblob column into my data base table, and changed a bit my method.
Here is my final code if you need it :
The DaoClass :
package marquise.daos;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import marquise.daos.impl.DataSourceProvider;
import marquise.exceptions.CityExplorerRuntimeException;
import marquise.projos.Image;
public class ImageDao {
public List<Image> listImages() {
List<Image> images = new ArrayList<Image>();
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM image ORDER BY name")) {
while (resultSet.next()) {
images.add(
new Image(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("summary")));
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return images;
}
public Image getImage(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return new Image(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("summary"));
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}
public void addImage(Image newImage, String picturePath) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("INSERT INTO image(name, summary, picture) VALUES (?, ?, ?)")) {
statement.setString(1, newImage.getName());
statement.setString(2, newImage.getSummary());
statement.setString(3, picturePath);
statement.executeUpdate();
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
}
public void addImage(Image img, InputStream is){
try(Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("INSERT INTO image(name, summary, image) VALUES (?, ?, ?)")) {
statement.setString(1, img.getName());
statement.setString(2, img.getSummary());
statement.setBinaryStream(3, is);
statement.executeUpdate();
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
}
public String getPicturePath(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT picture FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getString("picture");
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}
public InputStream getPicture(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT image FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getBinaryStream("image");
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}
/*public InputStream getPicture(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT image FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getBlob("image") == null ? null : resultSet.getBlob("image").getBinaryStream();
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}*/
}
the addimage servlet :
package marquise.servlets;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import marquise.projos.Image;
import marquise.services.InformationLibrary;
#WebServlet("/addimage")
#MultipartConfig
public class ImageAddServlet extends AbstractGenericServlet2 {
private static final long serialVersionUID = -3497793006266174453L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
TemplateEngine templateEngine = this.createTemplateEngine(req);
WebContext context = new WebContext(req, resp, getServletContext());
if(req.getSession().getAttribute("imageCreationError") != null) {
context.setVariable("errorMessage", req.getSession().getAttribute("imageCreationError"));
context.setVariable("image", (Image) req.getSession().getAttribute("imageCreationData"));
req.getSession().removeAttribute("imageCreationError");
req.getSession().removeAttribute("imageCreationData");
} else {
context.setVariable("image", new Image(null, null, null));
}
context.setVariable("countries", context);
templateEngine.process("connectedUsers/imageadd", context, resp.getWriter());
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String summary = req.getParameter("summary");
Part imagePicture = req.getPart("picture");
Image newImage = new Image(null, name, summary);
InputStream is = imagePicture.getInputStream();
try {
InformationLibrary.getInstance().addImage(newImage, is);
resp.sendRedirect("certificatsAdmin");
} catch (IllegalArgumentException|IOException e) {
req.getSession().setAttribute("imageCreationError", e.getMessage());
req.getSession().setAttribute("imageCreationData", newImage);
resp.sendRedirect("addimage");
}
}
}
The listImage servlet :
package marquise.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import marquise.services.InformationLibrary;
#WebServlet("/certificatsAdmin")
public class listeCertifServlet extends AbstractGenericServlet2 {
private static final long serialVersionUID = 5402133218271984030L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
HttpSession session=req.getSession(false);
if(session != null){}
else{
resp.sendRedirect("connexion");
out.println("Veuillez entre un mot de passe correct");
}
TemplateEngine templateEngine = this.createTemplateEngine(req);
WebContext context = new WebContext(req, resp, getServletContext());
//Country countryFilter = (Country) req.getSession().getAttribute("countryFilter");
context.setVariable("images", InformationLibrary.getInstance().listAllImages());
//context.setVariable("cities", CityService.getInstance().listAllCities(countryFilter));
//context.setVariable("countries", Country.values());
//context.setVariable("countryFilterSelected", countryFilter);
templateEngine.process("admin/certificatsAdmin", context, resp.getWriter());
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String countryString = req.getParameter("countryFilter");
resp.sendRedirect("certificatsAdmin");
}
}

Unable to print many results in a loop in jsp page

I have inserted many records in table while displaying the record last inserted record is displaying for a particular ID.But all the records are inserted in database.Though it is not showing? Please see the code and tell where have I done wrong?
DAO CODE
package org.fproject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
public class StudyDAO {
private String driver="com.mysql.jdbc.Driver";
private String url="jdbc:mysql://localhost:3306/mydb";
private String dbuser="root";
private String dbpassword="root123";
private String commdetSQL="select cid,fname,lname,email,comment from comment where qid=?";
private Connection con;
private PreparedStatement pstmtcommdisplay;
public StudyDAO()throws ClassNotFoundException,SQLException{
Class.forName(driver);
con=DriverManager.getConnection(url,dbuser,dbpassword);
pstmtcommdisplay=con.prepareStatement(commdetSQL);
}
public Collection<Comment> getComment(int qid)throws SQLException{
pstmtcommdisplay.setInt(1, qid);
ResultSet rs=pstmtcommdisplay.executeQuery();
ArrayList<Comment>list4=null;
while(rs.next()){
list4=new ArrayList<Comment>();
Comment c=new Comment(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5));
list4.add(c);
}
return list4;
}
}
Servlet Code
package org.fproject;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
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;
/**
* Servlet implementation class DisCommServlet
*/
#WebServlet("/DisCommServlet")
public class DisCommServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DisCommServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
String strqid=req.getParameter("qid");
int qid=Integer.parseInt(strqid);
try{
StudyDAO dao=new StudyDAO();
Collection<Comment> list4=dao.getComment(qid);
//req.setAttribute("LIST4", list4);
//req.setAttribute("QID", qid);
HttpSession s=req.getSession(true);
s.setAttribute("LIST4", list4);
s.setAttribute("QID", qid);
res.sendRedirect("DisComm.jsp");
}catch(ClassNotFoundException e){
e.printStackTrace();
res.sendError(9999,"Error in classloading");
}catch(SQLException e){
e.printStackTrace();
res.sendError(9998,"Error in sql:"+e.getMessage()+"Error code:"+e.getErrorCode()+e.getSQLState());
}catch(Exception e){
res.sendError(8000,"Unknown Error"+e.getMessage());
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*,org.fproject.*"%>
<!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>Answers</title>
</head>
<body>
<%
int qid=(Integer)session.getAttribute("QID");
Collection<Comment> list4=(Collection<Comment>)session.getAttribute("LIST4");
%>
<%if(list4!=null){ %>
<% for(Comment c:list4){ %>
<br><hr><%=c.getFname() %> <%=c.getLname() %><br><%=c.getEmail() %><br><p><b><%=c.getComment() %></b></p>
<% } %>
<%} else { %>
<h3>No answers are added</h3>
<% }%>
</body>
</html>
Only one record is displaying but all records are inserting in database.
in your studyDAO.java
while(rs.next()){
list4=new ArrayList<Comment>();
the above code should be
list4=new ArrayList<Comment>();
while(rs.next()){
now it will work.

Data show on servlet, not on jsp?

Hi there,
My task is displaying a list of object from database to JSP. But i don't know why it only show when i run servlet class,while not show anything when i run JSP. First I used setAttribute method to pass the list to JSP and at JSP i use JSTL tags for retriving data. I think everything is ok but don't why it happend like that. Here's my code
Asiakas.java
package Luokat;
public class Asiakas {
private int asiakas_id;
private String nimi;
private int puhelinnumero;
private String spostiosoite;
/**
*
*/
public Asiakas() {
asiakas_id = 0;
nimi= null;
puhelinnumero =0;
spostiosoite = null;
}
/**
* #param asiakas_id
* #param nimi
* #param puhelinnumero
* #param spostiosoite
*/
public Asiakas(int asiakas_id, String nimi, int puhelinnumero,
String spostiosoite) {
super();
this.asiakas_id = asiakas_id;
this.nimi = nimi;
this.puhelinnumero = puhelinnumero;
this.spostiosoite = spostiosoite;
}
public int getAsiakas_id() {
return asiakas_id;
}
public void setAsiakas_id(int asiakas_id) {
this.asiakas_id = asiakas_id;
}
public String getNimi() {
return nimi;
}
public void setNimi(String nimi) {
this.nimi = nimi;
}
public int getPuhelinnumero() {
return puhelinnumero;
}
public void setPuhelinnumero(int puhelinnumero) {
this.puhelinnumero = puhelinnumero;
}
public String getSpostiosoite() {
return spostiosoite;
}
public void setSpostiosoite(String spostiosoite) {
this.spostiosoite = spostiosoite;
}
#Override
public String toString() {
return "Asiakas [asiakas_id=" + asiakas_id + ", nimi=" + nimi
+ ", puhelinnumero=" + puhelinnumero + ", spostiosoite="
+ spostiosoite + "]";
}
}
NaytaAsiakasServlet
package Servletit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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;
import javax.servlet.http.HttpSession;
import DBHoitaja.DBHoitaja;
import Luokat.Asiakas;
/**
* Servlet implementation class NaytaAsiakasServlet
*/
#WebServlet("/NaytaAsiakasServlet")
public class NaytaAsiakasServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NaytaAsiakasServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
NaytaAsiakasServlet nayta = new NaytaAsiakasServlet();
request.setAttribute("asiakasLista", nayta.findAll());
request.getRequestDispatcher("admin_page.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public List<Asiakas> findAll(){
List<Asiakas> list = new ArrayList<Asiakas>();
try {
list.add(new Asiakas(0, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
list.add(new Asiakas(1, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
list.add(new Asiakas(3, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
} catch(Exception e){
list =null;
}
return list;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
admin_page.jsp
<%# 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 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>Ylläpito Sivu</title>
</head>
<body>
<table border="1" cellpadding="2" cellspacing="2" width="500">
<tr>
<th>Id</th>
<th>Nimi</th>
<th>Puhelin</th>
<th>Sähköposti</th>
</tr>
<c:forEach var="asiakas" items="${asiakasLista}" >
<tr>
<td><c:out value="${asiakas.asiakas_id}" /></td>
<td><c:out value="${asiakas.nimi}" /></td>
<td><c:out value="${asiakas.puhelinnumero}" /></td>
<td><c:out value="${asiakas.spostiosoite}" /></td>
</tr>
</c:forEach>
</table>
</body>
</html>
From your question I can understand that you are totally new to J2EE!! And also you are trying to run the servlet class and JSP, which is not going to work anyway.
Please read the below specified tutorials and have some idea on how run a simple web application.
how to write hello world servlet Example
Sample Code for Hello World:

How to use Jackson to parse a json in http servlet?

I send a json from page to server with YUI and how to get data from json in servlet. I use jackson lib 2.4. Thanks!!!
var user = {
userName: username,
password: password,
customerId: customerId
};
new Y.IO().send("http://localhost:7778/MyController", {
method: 'POST',
data: user
});
actually, when you make a request like this
<html>
<body>
<script src="http://yui.yahooapis.com/3.14.1/build/yui/yui-min.js"></script>
<script>
var user = {
userName: 'x1',
password: 'y2',
customerId: 'z3'
};
YUI().use('io-form', function (Y) {
new Y.IO().send("http://localhost:8080/web/MyController", {
method: 'POST',
data: user
});
});
</script>
</body>
</html>
you're not sending a JSON object to the servlet. Instead, you're creating a http request where each property of your javascript object (which is represented in the JSON format) is sent as an http POST property, so you can retrieve these values like this
package mine;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MyController
*/
#WebServlet("/MyController")
public class MyController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MyController() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String[]> map = request.getParameterMap();
for(Entry<String,String[]> entry:map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue()[0]);
}
}
}
which in turn prints this
userName
x1
password
y2
customerId
z3
so you don't need jackson to parse the data you retrieve from your page.