Servlet and html form for calculator - html

I want to make calculator which basically add, subtract, multiply and divide two numbers. For achieving this first of all i have designed a form in HTML and feel desire to calculate the answer on server so i have written a code on servlet but when i hit the submit button of my form it will do nothing.
Note: i am working eclipse so you are requested to answer my question with respect to eclipse.
Calculator.java:
package mypackage;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Calculator extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
int a1= Integer.parseInt(request.getParameter("n1"));
int a2= Integer.parseInt(request.getParameter("n2"));
if(request.getParameter("r1")!=null)
{
out.println("<h1>Addition</h1>"+(a1+a2));
}
if(request.getParameter("r2")!=null)
{
out.println("<h1>Substraction</h1>"+(a1-a2));
}
if(request.getParameter("r3")!=null)
{
out.println("<h1>Multiplication</h1>"+(a1*a2));
}if(request.getParameter("r1")!=null)
{
out.println("<h1>Division</h1>"+(a1/a2));
}
}
catch(Exception e)
{
}
}
}
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>Calculator</title>
</head>
<body>
<h1 style="text_align=center">Calculator</h1>
<form method="get" action="/Servlet">
<label>first number:</label>
<input type="text" name="n1" />
<br />
<label>Second number : </label>
<input type="text" name="n2" />
<br />
<div>
<label>
<input type="radio" name="r1" value="add" />addition
<br />
</label>
<input type="radio" name="r2" value="sub" />subtraction
<br />
<input type="radio" name="r3" value="mul" />multiplication
<br />
<input type="radio" name="r4" value="div" />division
<br />
</div>
<input type="button" value="submit" />
</form>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Servlet</display-name>
<servlet>
<servlet-name>Servlet</servlet-name>
<servlet-class>mypackage.Calculator</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<url-pattern>/firstHomePage</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

You have written url-pattern 'firstHomePage' in web.xml for servlet name Calculator
<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<url-pattern>/firstHomePage</url-pattern>
</servlet-mapping>
so that what you should write in form action i.e.
<form action="firstHomePage" method="get">
(you don't write / in form action)
whatever you write inside form action is checked in the url-pattern of all servlets mappings when a match is found the respective servlet name and the corresponding servlet class is searched for. That's how it works.
Hope you got your answer :)
UPDATE: write
<input type="submit">
NOT BUTTON else your form won't submit.
If you are using button then you will have to write some javascript.

Related

i am unable to see the login page on the web browser

this is the java code:i am not getting any error indication but the output of the code is not displayed on the web server.it is showing the web address as:(http://localhost:6027/HttpSearchBar/Example). Tell me whether the local host 6027 is a valid address?
package search.com;
import java.io.IO Exception;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Example extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 102831973239L;
public void dopost (HttpServletRequest hreq, HttpServletResponse hres)throws ServletException, IOException{
System.out.println("hello");
try {
hres.setContentType("text/html");
String s1 = hreq.getParameter("username");
String s2 = hreq.getParameter("password");
ServletContext sc = getServletContext();
if ((s1.equals("abc"))&&(s2.equals("xyz"))) {
hres.sendRedirect("welcome");
}else {
PrintWriter pw = hres.getWriter();
pw.print("invalid username/password");
RequestDispatcher rd = sc.getRequestDispatcher("login.html");
rd.include(hreq, hres);
}
} catch (Exception e) {
// TODO: handle exception
System.err.print(e);
}
} }
this is html code:
<!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>Example Html</title>
</head>
<body bgcolor=yellow text=blue>
<center>
<h1>
<u>LoginForm</u>
</h1>
<form action="Example" method="post">
UserName<input type="text" name="username">
Password<input type="text" name="Password">
<input type="submit" value="login" /><input type="reset">
</form>
</center>
</body>
</html>
this is web.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>HttpSearchBar</display-name>
<servlet>
<servlet-name>Example</servlet-name>
<servlet-class>Example</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Example</servlet-name>
<url-pattern>/Example</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/Example</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/Example</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/Example</location>
</error-page>
<error-page>
<exception-type>java.io.IOException</exception-type>
<location>/Example</location>
</error-page>
<error-page>
<exception-type>java.lang. Throw able </exception-type>
<location>/search.com.Example</location>
</error-page>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
<welcome-file>login.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
this is displayed when server is started:
Oct 22, 2018 6:41:52 PM org.apache.catalina.core.ApplicationDispatcher
invoke
WARNING: Servlet Example is currently unavailable
Send a request to http://localhost:6027/ from your browser. If you can see the default Apache Tomcat page the localhost:6027 is a valid address.
There are a couple of reasons that you might not see any response.
Java is case sensitive. Your do post method is incorrect. Replace with doPost
public void doPost(HttpServletRequest hreq, HttpServletResponse hres)
throws ServletException, IOException {
Your html password input name is name="Password", and you are getting it with lowercase p.
String s2 = hreq.getParameter("Password"); //uppercase P
Finally don't use RequestDispatcher, just redirect the page. Replace everything in your else statement.
hres.sendRedirect("login.html");
By referring to the server log that has attached, it seems that you are trying to run your servlet project on apache tomcat server. Default Tomcat port is 8080. That is you should try to access your running app on:
http://localhost:8080
if you want to customize the running port you have to do it using the server.xml file.

Primefaces fileUpload Listener does not invoked on wildfly server

I have added primeFaces fileUpload in my code and it worked fine on webLogic 12.2 server But when I changed the server to wildFly 10.0.1 the fileUpload Listener does not invoked anymore I wondered what is the reason and searched for this issue without avail.
That is the filters in web.xml
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
And that is my xhtml code
<p:column headerText="#{msgs.label_uploadFile}" >
<p:fileUpload id="upload" label="#{msgs.label_uploadFile}"
fileUploadListener="#{attachmentsInquiryBean.handleFileUpload}"
mode="advanced" auto="true"/>
</p:column>
That is the Listener function
public void handleFileUpload(FileUploadEvent event) {
// do something
}
Also I added two jars in my wWEB-INF/lib folder called:
commons-fileupload-1.3.jar
commons-io-2.4.jar
Here is an example of how to upload a file using primefaces and you do not need commons-fileupload-1.3.1.jar and commons-io-2.4.jar; and also you do not need to change web.xml , for more information see this How to upload file in primefaces
java code:
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.primefaces.model.UploadedFile;
#ManagedBean
public class FileUploadView {
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public void upload() {
if(file.getSize() > 0) {
FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
else{
FacesMessage message = new FacesMessage("Not Succesful", "file is not uploaded");
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
}
xhtml code:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data">
<p:growl id="messages" showDetail="true" />
<p:fileUpload value="#{fileUploadView.file}" mode="simple" skinSimple="true"/>
<p:commandButton value="Submit" ajax="false" actionListener="#{fileUploadView.upload}" />
</h:form>
</h:body>
</html>
I've seen the same in Wildfly 10.x with PF 6.1.
The method expression for fileUpload.getFileUploadListener() is null on Wildfly.
My workaround is to use a binding on the FileUpload component and manually setting a valid method expression.
I had the same problem on tomcat and solved it by adding allowCasualMultipartParsing="true" in META-INF/context.xml :
<Context allowCasualMultipartParsing="true">
</Context>
Hope it helps.

404 error on form submission in Java [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I'm developing simple web application. I've created Dynamic Web Project in Eclipse Mars and I'm using Java 1.8 and Tomcat v8.0.36.
I've created a simple form:
<!DOCTYPE html>
<html>
<head>
<title>Coffee Advice Page</title>
</head>
<body>
<form action=”SelectCoffee.do”>
Select Coffee characteristics<p>
Color:
<select name=”color” size=”1”>
<option value=”light”> light </option>
<option value=”amber”> amber </option>
<option value=”brown”> brown </option>
<option value=”dark”> dark </option>
</select>
</br></br>
<input type="submit" value="Submit">
</form>
</body>
</html>
A Servlet:
package com.example.web;
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;
#SuppressWarnings("serial")
public class CoffeeSelectionServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Inside doGet()");
PrintWriter printWriter = response.getWriter();
printWriter.println("doGet() is working fine!");
}
}
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>CoffeeAdvice</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<!-- <welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file> -->
</welcome-file-list>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>com.example.web.CoffeeSelectionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/SelectCoffee.do</url-pattern>
</servlet-mapping>
</web-app>
But when I start Tomcat server and submit this form, I get 404 Error with query string:
http://localhost:8080/CoffeeAdvice/%C3%A2%E2%82%AC%C2%9DSelectCoffee.do%C3%A2%E2%82%AC%C2%9D?%E2%80%9Dcolor%E2%80%9D=%E2%80%9Dlight%E2%80%9D
which is not I intended.
If I make GET request directly from browser bar:
http://localhost:8080/CoffeeAdvice/SelectCoffee.do?color=light
It works absolutely fine!
Please let me know why this query string is generated distorted like this and what I'd have to change.
Any help would be much appreciated!
The double quote sign which you are using in form action is not proper
I unescaped your url which is now
"http://localhost:8080/CoffeeAdvice/ââ¬ÂSelectCoffee.doââ¬Â?âcolorâ=âlightâ"
Fix your double quote.

HTML(5) Friendly Markup in JSF 2.2 Not working

I tried to reproduce the same example in this question using JSF 2.2.6 and Tomcat 7.0: JSF navigation rule doesn't work on form submit, I also read the JSF returns blank/unparsed page with plain/raw XHTML/XML/EL source instead of rendered HTML output and respected all the recommandations provided by BalusC's answer, then I also consulted this question JSF 2 with HTML pages instead of XHTML because I want to use only .html files (I know i can use .xhtml but i need to understand the reason why this is not working).
I tried to make it simple as much as possible so any one could reproduce that:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>facesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>facesServlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>faces/index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.html</param-value>
</context-param>
</web-app>
faces-config.xml (Navigation rules are not needed as it's provided dynamicly):
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<navigation-rule>
<display-name>index.html</display-name>
<from-view-id>/index.html</from-view-id>
<navigation-case>
<from-outcome>welcomePage</from-outcome>
<to-view-id>/welcome.html</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
BeanFilm.java:
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class BeanFilm implements Serializable {
private String recherche = new String();
public String getRecherche() {
return recherche;
}
public void setRecherche(String recherche) {
this.recherche = recherche;
}
public String doRecherche() {
return "welcomePage";
}
}
index.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:jsf="http://xmlns.jcp.org/jsf">
<head>
<title>Accueil</title>
</head>
<body jsf:id="body" >
<h1>Plain HTML5 with JSF</h1>
<form jsf:id="form">
<input type="text" jsf:id="recherche" jsf:value="#{beanFilm.recherche}"/>
<input type="submit" jsf:value="Submit" jsf:id="searchButton" jsf:action="#{beanFilm.doRecherche}"/>
</form>
<ui:debug/>
</body>
</html>
welcome.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsf="http://xmlns.jcp.org/jsf">
<head>
<title>Accueil</title>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>
The issue:
The exact problem is that when i click on the submit the method BeanFilm#doRecherch() is never called (using a breakpoint) and i can't really understand why? another information wich may be useful, is that in HTML code source attributes are still like jsf:id="searchButton"does this mean that the HTML wasn't generated?

Problems with web.xml

first of all i want to apologize for my bad English. Ok, i have a problem. I am building application that uses jdbcrealm and web.xml for security. Login is done by web form. Application is running on Apache Tomcat 7 and i am using Primefaces 4.0. In web.xml I have defined some roles and some security constraints. When I log in into application httpservlet request.login(username,password) do the job fine, and request.isUserInrole("role") also do do job, Faces.getExternalContext.redirect redirects page to correct folder on which security constraint is applied, in browser I see correct URL .....but the page is Blank!!! If I check page source I see page source of login page.....I will put some screen shots bellow. Please help me...I am trying solve problem for 2 weeks now!
/*
*/
this is web.xml
<param-name>primefaces.THEME</param-name>
<param-value>afterdark</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<security-role>
<description>Administrator A</description>
<role-name>1</role-name>
</security-role>
<security-constraint>
<display-name>Administrator A</display-name>
<web-resource-collection>
<web-resource-name>Administratorske datoteke</web-resource-name>
<description/>
<url-pattern>/a1/*</url-pattern> -->
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description>Administrator A</description>
<role-name>1</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>JDBCRealm</realm-name>
<form-login-config>
<form-login-page>/prijava.xhtml</form-login-page>
<form-error-page>/pogreska.xhtml</form-error-page>
</form-login-config>
</login-config>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>prijava.xhtml</welcome-file>
</welcome-file-list>
*this is login page(prijava.xhtml)*
<div class="slika_za_prijavu">
<h:outputLink id="loginLink" value="javascript:void(0)" onclick="PF('prozor_za_unos').show()" title="prijava">
<p:graphicImage value="/slike/prijava.png" />
</h:outputLink>
</div>
<p:growl id="growl" showDetail="true" life="3000" />
<p:dialog id="prozor_za_prijavu" header="Prijava" widgetVar="prozor_za_unos" resizable="false">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="k_ime" value="Korisničko ime:" />
<p:inputText value="#{provjera_prijave.k_ime}"
id="k_ime" required="true" label="korisnicko_ime"
requiredMessage="Potrebno je upisati korisničko ime!"/>
<h:outputLabel for="zaporka" value="Zaporka:" />
<h:inputSecret value="#{provjera_prijave.zaporka}"
id="zaporka" required="true" label="zaporka"
requiredMessage="Potrebno je upisati zaporku!"/>
<f:facet name="footer">
<p:commandButton id="gumb_za_prijavu" value="Prijavi se" update="growl"
actionListener="#{provjera_prijave.prijava(actionEvent)}"
oncomplete="obrada_zahtjeva_za_prijavu(xhr, status, args)"/>
</f:facet>
</h:panelGrid>
</p:dialog>
</h:form>
this is login controller (provjera_prijave)
public void prijava(ActionEvent actionEvent) throws IOException {
FacesMessage poruka = null;
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest zahtjev = (HttpServletRequest) fc.getExternalContext().getRequest();
try {
String pocetna_stranica;
zahtjev.login(k_ime, zaporka);
HttpSession sesija = zahtjev.getSession();
if (!sesija.isNew()) {
sesija.invalidate();
sesija = zahtjev.getSession();
}
if (zahtjev.isUserInRole("1")) {
sesija.setAttribute("trenutni_korisnik",k_ime);
pocetna_stranica = "/a1/pocetna_a1.xhtml";
poruka = new FacesMessage(FacesMessage.SEVERITY_INFO, "Dobro došao", k_ime);
try {
fc.getExternalContext().getFlash().setKeepMessages(true);
fc.getExternalContext().redirect(zahtjev.getContextPath()+pocetna_stranica);
}
catch (IOException ex) {
fc.addMessage(null, new FacesMessage("UPOZORENJE!", "Pogreška u izvođenju programa. Nije moguće preusmjeriti stranicu."));
}
}
else if (zahtjev.isUserInRole("2")) {
and this is url which is in my browser when user with role "1" log in. Before this goes localhost and port...ERMP is the neme of application....
"ERMP/a1/pocetna_a1.xhtml"
here is blank page with page source of login page
I hope that question is understandable.
When comment web resource in web.xml everything works
Please help!!Thank you
As you want to use the tomcat's built in (Realm) authentication and authorization, there's a couple of things you should attend to.
First, your login form needs to be something like this:
<form action="j_security_check" method="post">
<input type="text" name="j_username" placeholder="Login"/>
<input type="password" name="j_password" placeholder="Password"/>
<input type="submit" value="Sign In" />
</form>
You could use primefaces components to preserve the layout. In that case you will need to do some "javascripting" in order to define the action of the form rednered by the JSF h:form component.
...
<script>
jQuery("#form").submit(function() {
jQuery(this).attr("action", "j_security_check");
jQuery(loginVar.jqId).attr("name", "j_username");
....
});
</script>
The second detail is that you won't need to worry about the login part as described in your login controller. Once you send j_username and j_password to j_security_check, everything will run just fine.