I'm currently trying to complete a simple Web project using Activiti. I doing it in Eclipse using a Tomcat 7.0 server. I have a servlet that should display a tasks info but even if there's a problem there surely it should still display something.
I'm only starting to learn JSP so I apologise for any stupid mistakes I may have made in the code.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Main Page</title>
</head>
<body>
<h1>Welcome.</h1>
<br />
<h3>Go to:</h3>
<ul>
<li>Request Loan</li>
<li>Management Tasks</li>
</ul>
</body>
</html>
My servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
/**
* Servlet implementation class ManagementTasks
*/
#WebServlet("/ManagementTasks")
public class ManagementTasks extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ManagementTasks() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Management Tasks</title</head><body>");
ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
TaskService taskService = processEngine.getTaskService();
List<Task> tasks = taskService.createTaskQuery()
.taskCandidateGroup("management").list();
if (tasks.size() > 0) {
out.println("<h1>You have " + tasks.size() + " task(s) to complete.</h1>");
Task t = tasks.get(0);
out.println("<br /><br /><h2>" + t.getDescription() + "</h2>");
out.println("<br />Do you want to approve this request?</h2><br />");
out.println("<form method=\"POST\" action=\"ManagementApproval\">");
out.println("<label for=\"approve\">Do you approve?</label>");
out.println("<select name=\"approve\">");
out.println("<option value=\"true\">Yes</option>");
out.println("<option value=\"false\">No</option>");
out.println("</select><br />");
out.println("<input type=\"hidden\" id=\"taskId\" name=\"taskId\" " + "value=\"" + t.getId() + "\" /><br/>");
out.println("<input type=\"submit\" value=\"Submit Form\" />");
out.println("<input type=\"reset\" value=\"Reset Form\" />");
out.println("</form>");
} else {
out.println("<h1>There are no tasks for you. </h1>");
}
out.println(" HOME ");
out.println("</body></html>");
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Related
I would like to print out my current variable value on my HTML page. I cannot seem to figure it out. On my HTML page, I want to print out the current Exchange rate.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Calculator</title>
</head>
<body>
<form action="Converter" method="get" name="frm">
Amount:
<input name="amount" type="text" />
Rate:
<input name="conversionRate" type="text" />
<input type="submit" value="Convert!" />
<br>Current Rate:
</form>
</body>
</html>
My Java Code
import java.io.IOException;
import java.io.PrintWriter;
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 Converter
*/
#WebServlet("/Converter")
public class Converter extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Converter() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
String n2 = "1.0";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String n1 = request.getParameter("amount");
String tempStr;
tempStr = request.getParameter("conversionRate");
if(!tempStr.isBlank()) {
n2 = tempStr;
}
if(n2.equals("tempStr")){
out.println((Integer.parseInt(n1) / Double.parseDouble(n2)));
}
else if(n2.equals(n2)){
out.println("test");
out.println((Integer.parseInt(n1) / Double.parseDouble(n2)));
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
How can I print out the current rate. Which in this case is n2 on my HTML page? I want it to update on each load of the website. But I cannot figure out how to print out the variable value through the HTML page.
You can use your PrintWriter instance to print the whole HTML into the response object, example:
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Bla</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>");
out.println("Your current rate is: ");
//Your Java code here
String n1 = request.getParameter("amount");
String tempStr;
tempStr = request.getParameter("conversionRate");
if(!tempStr.isBlank()) {
n2 = tempStr;
}
out.println(n2);
out.println("</h1>");
out.println("</body>");
out.println("</html>");
}
Hope that helps.
I was following the tutorial on:
https://www.javahelps.com/2015/04/java-web-application-hello-world.html
The Tomcat server is running well on:
http://localhost:8080/
This page is displayed correctly:
http://localhost:8080/Hello_World/
However, when I press "Click here" and go to this link:
http://localhost:8080/Hello_World/saytime
The above error is displayed.
Here is my code:
package help;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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 HelloWorldServlet
*/
#WebServlet("/saytime")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloWorldServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("<html><body><h1 align='center'>" +
new Date().toString() + "</h1></body></html>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}`
I noticed that I don't have web.xml file
Any help is appreciated
Thanks in advance,
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
Click Here
</body>
</html>
Good afternoon!
In an example I did in class, when I debug the servlet comes in front of the filter.
On the system I'm doing the filter is called first that the servlet ... and this is causing problems.
I'm doing the login part of the system.
I am using version 3.0 of the servlet.
In class I did not need to use xml, but in some sites indicate to do this ... which also did not work.
Index
<%# 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>Insert title here</title>
</head>
<body>
<div>
<form action="template/inicio.html" method="post">
<label for="login">Login </label>
<input type="text" name="login">
<br>
<label for="senha">Senha </label>
<input type="text" name="senha">
<br>
<input type="submit" value="Entrar">
</form>
</div>
${msg}
</body>
</html>
FiltroLogin
package filtro;
import java.io.IOException;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet Filter implementation class FiltroLogin
*/
#WebFilter(
dispatcherTypes = {
DispatcherType.REQUEST,
DispatcherType.FORWARD,
DispatcherType.INCLUDE,
DispatcherType.ERROR
}
,
urlPatterns = {
"/FiltroLogin",
"/template/*"
})
public class FiltroLogin implements Filter {
/**
* Default constructor.
*/
public FiltroLogin() {
// TODO Auto-generated constructor stub
}
/**
* #see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* #see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if(session.getAttribute("login") != null ){
//Se estiver logado, deixa a pagina ser exibida
chain.doFilter(request, response);
}else{
//mandar embora
res.sendRedirect( req.getContextPath() );
}
}
/**
* #see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
ControleLogin
package control;
import java.io.IOException;
import java.util.List;
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.firebirdsql.jdbc.parser.JaybirdSqlParser.function_return;
import model.Funcionario;
import persistence.FuncionarioDao;
import persistence.LoginDao;
/**
* Servlet implementation class ControleLogin
*/
#WebServlet({"/ControleLogin","/template/inicio.html", "/template/logout.html"})
public class ControleLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ControleLogin() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
execute(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
execute(request, response);
}
protected void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String url = request.getServletPath();
if(url.equalsIgnoreCase("/template/inicio.html")){
String login = request.getParameter("login");
String senha = request.getParameter("senha");
if(new LoginDao().logar(login, senha).booleanValue() == true){
Funcionario func = new LoginDao().buscarUsuario(login);
HttpSession session = request.getSession();
session.setAttribute("nomeP", func.getNome());
response.sendRedirect("template/indCadastro.jsp");
}else{
request.setAttribute("msg", "<div class = 'alert alert-info'>"+ "Email ou senha Incorretos!"+"</div>");
request.getRequestDispatcher("../index.jsp").forward(request, response);
}
}else if(url.equalsIgnoreCase("/template/logout.html")){
HttpSession session = request.getSession();
session.removeAttribute("nomeP");
session.invalidate();
response.sendRedirect( request.getContextPath() + "/");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
I solved The index, was with the "Action =" template / Logar "", when I switched to "Action =" Logar "", it worked.
Silly mistake.
I have a HTML page where new users are added to the Database,I have done MS-Access connection through JDBC-ODBC and Servlets.I have no errors but the values aren't getting saved in the Database.
*******HTML FILE*****
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<center><h1>login page</h1></center>
<form action="Serve" method="get">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<button> Login</button>
</form>
</div>
</body>
</html>
***JDBC-ODBC FILE****
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class base {
Connection con;
Statement st;
ResultSet rs;
String s;
public base() throws SQLException {
connect();
}
private void connect() throws SQLException {
try {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =DriverManager.getConnection("jdbc:odbc:db","","");
st=con.createStatement();
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
}
*****SERVLETS***
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
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.swing.JOptionPane;
#WebServlet(name = "Serve", urlPatterns = {"/Serve"})
public class Serve extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
base s = new base();
s.s="insert into Table1 values("+request.getParameter("name")+","+request.getParameter("pass")+")";
s.st.executeQuery(s.s);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
The problem is that you get the wrong parameters from the request Object.
Try this:
s.s="insert into Table1 values("+request.getParameter("username")+","+request.getParameter("password")+")";
facing problem to manage session in servlet program. this is my servlet code.
//`SessionUsingHttpSession .java
package suprio.servlets.examples;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.catalina.Session;
/**
* Servlet implementation class SessionUsingHttpSession
*/
public class SessionUsingHttpSession extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SessionUsingHttpSession() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("<html/text");
String name = request.getParameter("txtName4");
String pass = request.getParameter("txtPassword4");
if(pass.equals("12345"))
{
HttpSession session = request.getSession();
session.setAttribute("user", name);
//response.sendRedirect("SessionUsingHttpSessionRedirected");
RequestDispatcher rd = request.getRequestDispatcher("SessionUsingHttpSessionRedirected");
}
}
}
and the following code is the redirected from SessionUsingHttpSession.java
//SessionUsingHttpSessionRedirected.java
package suprio.servlets.examples;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class SessionUsingHttpSessionRedirected
*/
public class SessionUsingHttpSessionRedirected extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SessionUsingHttpSessionRedirected() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("html/text");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String) request.getAttribute("user");
out.print("Hello"+user);
}
}
and this is for view part
// UsingHttpSession.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>Insert title here</title>
</head>
<body>
<form method="get" action="SessionUsingHttpSession">
Enter Name:<input type="text" name="txtName4"/><br/>
Password: <input type="text" name="txtPassword4"/><br/>
<input type="Submit" value="Enter">
</form>
</body>
</html>
while i am trying to run it through apache tomcat server my web browsers(mozila,chrome,IE) showing this message:
if i save and open it it is giving "hello null" as output. Now my question is that why its showing such message as i am just trying to forward this page to another.
Thank you in advance.
The content type is wrong in both servlets. It should be text/html.
Moreover is you are using SessionUsingHttpSession servlet just for redirection then there is no need for specifying the content type at all.
Your content type appears reversed, you have it as html/text, instead of text/html.
Also it's a good habbit to flush/close stream after you write.
out.print("Hello"+user);
out.flush();
out.close();