Hey I am trying to create a voting app.
I have several counters in my servlets and I want to be able to display the value of those counters in my jsp file. How do I do it?
Please help me.
I want to display the total number of votes in each section and the winner after the election.
......................................................................................................................................................
servlet file
......................................................................................................................................................
import java.io.IOException;
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("/CastVote")
public class CastVote extends HttpServlet {
int javaCount, phpCount, pythonCount, othersCount;
public CastVote() {
super();
javaCount = 0;
phpCount = 0;
pythonCount = 0;
othersCount = 0;
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String choice = request.getParameter("language");
if("java".equals(choice))
{
javaCount++;
}
else if("php".equals(choice))
{
phpCount++;
}
else if("python".equals(choice))
{
pythonCount++;
}
else if("others".equals(choice))
{
othersCount++;
}
}
}
......................................................................................................................................................
Jsp File
......................................................................................................................................................
<%# 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>Vote now.</title>
</head>
<body>
<center>
<h2>Welcome to voting portal. Cast your vote.</h2>
</center>
<form action="CastVote" method="post">
Which of the following is the best language for backend programming? <br>
<input type="radio" name="language" value="java">1) Java <br>
<input type="radio" name="language" value="php">2) PHP <br>
<input type="radio" name="language" value="python">3) Python <br>
<input type="radio" name="language" value="others">4) Others <br>
<input type = "submit" value ="Vote">
</form>
</body>
</html>
Related
What I am trying to do is a blog page with jsp. For this purpose, I save the content of blogs in an html file. I am using a jsp file to update the content in the existing html file via the browser. I used the textarea tag in a jsp file to edit this html file through the browser. There is no encoding problem in the html content transferred to the textarea. But when I make changes to the html file and save it, the utf-8 characters turn out to be incorrect. For Example:
The html file is read and placed comfortably in the textarea without any encoding problems
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Üzerine Notlar</h1>
</body>
</html>
When i submit for save it:
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Ãzerine Notlar</h1>
</body>
</html>
There is the classes and jsp files:
setBlog.jsp (Html file is setting in this file)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<jsp:include page="navbar.jsp"/>
<form action="adminBlogProcess?meth=update" method="post">
id:<input type="text" readonly="readonly" value="${setMe.textId}" name="tid">
<label>Text Title</label>
<input type="text" name="name" class="form-control" value="${setMe.name}"/>
<label>File Path</label>
<input type="text" name="textPath" class="form-control" value="${setMe.textPath}"/>
<label>Kategori</label>
<select class="form-control" name="selectedCategory">
<c:forEach items="${loc}" var="val">
<option value="${val.categoryId}">${val.categoryName}</option>
</c:forEach>
</select>
<label>İçerik:</label>
<textarea class="form-control" name="content" rows="100">${contentOfDoc}</textarea>
<input type="submit" class="btn btn-primary" value="Save Changes">
</form>
</body>
</html>
AdminBlogProcess.java
package Controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
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 DataAccess.CategoryDao;
import DataAccess.TextDao;
import Model.Category;
import Model.Text;
#WebServlet("/adminBlogProcess")
public class AdminBlogProcess extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -7693704779591981580L;
private CategoryDao cd;
private TextDao td;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String meth = req.getParameter("meth");
String msg="";
if (meth.equalsIgnoreCase("update")) {
update(req);
msg="Yazı Güncellendi!";
} else if (meth.equalsIgnoreCase("add")) {
} else if (meth.equalsIgnoreCase("delete")) {
}
req.setAttribute("message", msg);
req.getRequestDispatcher("/admin/admin.jsp").forward(req, resp);
}
//This update method is write new content into the html file
private void update(HttpServletRequest req) {
String name=req.getParameter("name");
String textPath=req.getParameter("textPath");
int id=Integer.valueOf(req.getParameter("tid"));
Category ct=getCd().getCategoryById(Integer.valueOf(req.getParameter("selectedCategory")));
Text txt=new Text(name, textPath, ct, id);
getTd().update(txt);
String content=req.getParameter("content");
String path="C:\\Users\\90551\\Desktop\\Eclipse Projeler\\2022 Yaz-Haziran Arsiv\\JAVA SERVER PAGES\\004BlogSitesi\\src\\main\\webapp\\texts\\"+textPath;
try (FileWriter fw = new FileWriter(new File(path), StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(fw)){
bw.write("");
bw.append(content);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public CategoryDao getCd() {
if (cd == null) {
cd = new CategoryDao();
}
return cd;
}
public void setCd(CategoryDao cd) {
this.cd = cd;
}
public TextDao getTd() {
if (td == null) {
td = new TextDao();
}
return td;
}
public void setTd(TextDao td) {
this.td = td;
}
}
What should i do for fix that encodin problem?
I have to ask you because i'm stuck and can't go on. I'm trying to make response path like this:
DAO-> Servlet-> JSP
The process is: user fills the form on jsp, clicks "Submit" and gets response on the same JSP (user added or didn't)
adding data to DB is working fine but i got error from WebBrowser :
Type Exception Report
Message can't parse argument number: pageContext.request.contextPath
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
here is my jsp code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix ="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix ="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix ="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# page isELIgnored="false"%>
<script type="text/javascript" src="${pageContext.request.contextPath}/jQuery.js"/></script>
<!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>dodaj pracownika</title>
</head>
<body>
<f:view>
<section id = registration" class = "section">
<div class "container tagline">
<em>{0}</em>
</div>
<br>
<AdContentProvider
Name="MIME-type"
Provider="addUser.class"
Properties="optional-properties-for-your-class"
>
</AdContentProvider>
<form action="${pageContext.request.contextPath}/newuser" method = "post">
<form>
<label> Imie</label> <input type="text" name= "imie" id="imie"> <br/>
<label> Nazwisko</label> <input type="text" name= "nazwisko" id="nazwisko"> <br/>
<label> Stanowisko</label> <input type="text" name= "stanowisko" id="stanowisko"> <br/>
<label> Stawka</label> <input type="text" name= "stawka" id="stawka"> <br/>
<input type ="submit" value="Dodaj" id = "dodaj">
</form>
</f:view>
</body>
</html>
and servlet code:
package tk.jewsbar.servlets;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.MessageFormat;
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.transaction.Transactional;
import fasolki.Pracownik;
import tk.jewsbar.dao.Dao;
#WebServlet("/newuser")
public class addUser extends HttpServlet
{
#Override
#Transactional
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String imie = req.getParameter("imie");
String nazwisko = req.getParameter("nazwisko");
String stanowisko = req.getParameter("stanowisko");
double stawka = Double.valueOf(req.getParameter("stawka"));
Pracownik pracownik = new Pracownik (imie, nazwisko, stanowisko, stawka);
Dao dao = new Dao();
int rows = dao.dodajUzytkownika(pracownik);
String err = "null";
if (rows ==0)
{
err = "Niestety nie udalo sie dodac uzytkownika";
}
else {
err = "Dodano uzytkownika" + rows;
}
String pejcz = getHTMLString(req.getServletContext().getRealPath("html/newuser.jsp"), err);
resp.getWriter().write(pejcz);
}
public String getHTMLString(String sciezka, String message) throws IOException
{
BufferedReader czytaj = new BufferedReader (new FileReader(sciezka));
String linia = "";
StringBuffer bufor = new StringBuffer();
while((linia=czytaj.readLine())!= null)
{
bufor.append(linia);
}
czytaj.close();
String pejcz = bufor.toString();
pejcz = MessageFormat.format(pejcz, message);
return pejcz;
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String pejcz = getHTMLString(req.getServletContext().getRealPath("html/newuser.jsp"),"");
resp.getWriter().write(pejcz);
}
}
try like this
<script type="text/javascript" src="<c:out value="${contextPath}"/>/jQuery.js"></script>
or
<script type="text/javascript" src="<c:out value="${pageContext.request.contextPath}"/>/jQuery.js"></script>
Instead of
<script type="text/javascript" src="${contextPath}/jQuery.js"/></script>
You may read the suggestions on this link ,
expression-language-in-jsp-not-working
bookReg.jsp
<%#page import="classes.BooksDTO"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link type="text/css" href="css/mainStyle.css">
</head>
<body>
<%
//D:\Hayden\учеба\джава\JavaBigData\readers\WebContent\img - folder directory
%>
<form action="bookRegProc.jsp" method="post" enctype="multipart/form-data">
Title <input type="text" name="title"> <br>
Plot <textarea rows="30" cols="40" name="plot"></textarea> <br>
<input type="hidden" name="rating" value="0"> <br>
Author <input type="text" name="author"> <br>
Publisher <input type="text" name="publisher"> <br>
Genre <input type="text" name="genre"> <br>
Publication date <input type="text" name="date"> <br>
Cover <input type="file" name="cover" size="50"> <br>
<input type="submit" value="Register"> <br>
</form>
</body>
</html>
bookRegProc.jsp
<%#page import="classes.Uploader"%>
<%#page import="org.apache.commons.fileupload.FileItem"%>
<%#page import="java.util.Iterator"%>
<%#page import="java.util.List"%>
<%#page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%#page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%#page import="java.io.File"%>
<%#page import="classes.BooksDTO"%>
<%#page import="classes.BooksDAO"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Uploader upload = new Uploader();
upload.doPost(request, response);
%>
</body>
</html>
Uploader.java
package classes;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
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 javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class Uploader extends HttpServlet {
BooksDTO dto = null;
BooksDAO dao = new BooksDAO();
String title = null;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title"); // Retrieves <input type="text" name="description">
String plot = request.getParameter("plot");
String rating = request.getParameter("rating");
String author = request.getParameter("author");
String publisher = request.getParameter("publisher");
String genre = request.getParameter("genre");
String date = request.getParameter("date");
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
/*String fileName = title;
InputStream fileContent = filePart.getInputStream();*/
// ... (do your job here)
//DTO process
BooksDTO dto = new BooksDTO();
BooksDAO dao = new BooksDAO();
dto.setTitle(title);
dto.setAuthor(author);
dto.setDate(date);
dto.setGenre(genre);
dto.setPlot(plot);
dto.setPublisher(publisher);
dto.setRating(rating);
try {
dao.insert(dto);
//this inserts all the parameters into database
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//File process
File file;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
String filePath = "D:/Hayden/Eclipse workspace/bigdata/readers/WebContent/img/";
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new File("C:/temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
try {
FileItem fi = (FileItem) filePart;
if(!fi.isFormField()) {
file = new File(filePath + dto.getTitle() + ".jpg");
fi.write(file);
}
}catch(Exception ex) {
System.out.println(ex);
}
}
}
I want to pass text parameters from bookReg.jsp to register it in my database.
I checked the methods for inserting into database works totally fine.
but in doPost method, Uploader.java, request.getParameter passes null to each String.
I searched how to pass text to a servlet for days and I finally followed this instruction : How to upload files to server using JSP/Servlet? (first answer)
but it still passes null only.
what is the difference between passing parameter using request.getParameter in jsp and in a java class as I wrote?
and what is causing the same problem even if I followed the instruction of the first answer in the page that I followed?
(I am using tomcat 8.5 and eclipse oxygen)
Hello I know That this question has been asked before But unfortuanetly I didn t find among the answers proposed the one suitable for me
I m still new with J2ee lookin' forward for ur help
This is my code
login.jsp
<!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>Login page</title>
</head>
<body>
<form action="" method="post"/>
<br> UserId: <input type="text" name="userId"/>
<br> password<input type="password" name="password"/>
<br><input type="submit"/>
</form>
</body>
</html>
LoginServlet.java
package org.islem.login;
import java.io.IOException;
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 org.islem.login.service.LoginService;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userId,password;
userId= request.getParameter("userId");
System.out.println(userId);
password= request.getParameter("password");
LoginService loginService= new LoginService();
boolean result= loginService.authenticate(userId, password);
if (result)
{
response.sendRedirect("home.jsp");
return;
}
else
{
response.sendRedirect("login.jsp");
return;
}
}
}
LoginService.java
package org.islem.login.service;
public class LoginService {
public boolean authenticate (String userId,String password)
{
if (password ==null || password.trim() =="") {
return false;
}
else return true;
}
}
Your form action is empty, you should fill it your servlet name in your case it should be like:
<form action="LoginServlet" method="post"/>
I assume you already define your servlet name at your web.xml
You need to specify some controller name within the action:
<form action="LoginServlet " method="post"/>
<br> UserId: <input type="text" name="userId"/>
<br> password<input type="password" name="password"/>
<br> <input type="submit"/>
</form>
Remember: This action specifies where the data submitted by the form will be received.
I am uploading a file in a form, that form also contains some textfields I enter some values in the textfields. I want this value to remain when I click upload button. And there is also a save button, when I click this button uploaded file should get saved in database. Can any one help me out?
JSP file is here:
<body>
<form action="./upload" enctype="multipart/form-data" >ID: <input type="text" name="id" value="" />Name: <input type="text" name="name" value="" />
<input name="uploaded" type="file" />
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
I need the bussiness logic in a servlet..
Your options are:
Persist the data to your back-end and re-populate the form
Persist the data to the the in-browser Storage (http://www.w3schools.com/html/html5_webstorage.asp)
Put the upload form in an IFRAME
The easiest option is the IFRAME.
Hey you are saying the text field values should be there while clicking Upload button. You don't have to do this thing. By default it will be there. You should it will venish man? Please mention your exact requirement.
See there is no provision to keep the file field data using value attribute.
See this link
package comunity.stackoverflow.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestController
*/
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestController() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
private void process(HttpServletRequest request,
HttpServletResponse response) {
storeInRequest(request, "id");
storeInRequest(request, "name");
storeInRequest(request, "uploaded");
// write your upload logic here then navigate to the same page;
try {
request.getRequestDispatcher("/test.jsp").forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void storeInRequest(HttpServletRequest request,String param){
String val = request.getParameter(param);
if(param!=null && !param.isEmpty()){
System.out.println(val);
request.setAttribute(param, val);
}
}
}
Use standard.jat and jstl.jar
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>Insert title here</title>
</head>
<body>
<form action="upload.do" enctype="multipart/form-data" >
ID: <input type="text" name="id" value="${id}"/>
Name: <input type="text" name="name" value="${name}" />
<input name="uploaded" type="file" />
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
</html>
Use this JSP file. It might solve your problem.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>Insert title here</title>
</head>
<body>
<form action="upload.do" enctype="multipart/form-data" >
ID: <input type="text" name="id" value="${id}"/><br/>
Name: <input type="text" name="name" value="${name}" /><br/>
<input type="file" id="selectedFile" style="display: none;" />
<input type="text" name="uploaded" id="uploaded" value="${uploaded}" readonly="readonly" size="60">
<input type="button" value="Browse..." onclick="mymethod()" /><br/>
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
<script type="text/javascript">
function mymethod(){
document.getElementById('selectedFile').click();
var val = document.getElementById('selectedFile').value;
document.getElementById('uploaded').value = val;
}
</script>
</html>