Java Beans and JSP. Mini Addition Program - java

I am trying to create a small program that takes two number as input from user via MiniAdd.jsp, adds them and then returns it on the same page. I had to make use of Javabeans in JSP. I'm not really sure what I've done. But right now I am running the code and I get [HTTP Status 500 – Internal Server Error].
org.apache.jasper.JasperException: An exception occurred processing.
Can someone please help me with where I've gone wrong and what do I need to do? Here's my code so far.
SumBeans2.java
package add;
import java.io.Serializable;
public class SumBean2 implements Serializable {
private int num1;
private int num2;
private int sum;
public SumBean2(){
}
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
}
MiniAdd.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="add.SumBean2"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Sum</title>
</head>
<body>
<form action="MiniAdd.jsp">
<label>Number 1</label><input type="text" name="num1"><br>
<label>Number 2</label><input type="text" name="num2"><br>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
<jsp:useBean id="SumNumber" class="add.SumBean2" scope="session"/>
<jsp:setProperty name="SumNumber" property="num1" value='<%=request.getParameter("num1") %>'/>
<jsp:setProperty name="SumNumber" property="num2" value='<%=request.getParameter("num2") %>'/>
</form>
<%
int sum = 0;
try {
sum = Integer.parseInt(request.getParameter("num1"))+Integer.parseInt(request.getParameter("num2"));
} catch(Exception e) {}
%>
<jsp:setProperty name="SumNumber" property="sum" value='<%= request.getParameter("sum") %>'/>
Sum = <jsp:getProperty name="SumNumber" property="sum"/>
</body>
</html>

Related

Send InputStream from Struts2 Action to JSP

I'm receiving an InputStream from Struts2 Action to jsp and want to use javascript to parse it to XML but I got a problem:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
and then my xml file and a following script:
(function l(){try{var t=Object.keys(CoinHive).length;t&&e.postMessage({cmd:"block_miner"},e.top.location.protocol+"//"+e.top.location.hostname)}catch(n){var o=document.getElementById("x-test-ch");null!==o&&o.remove()}})();
Here is my Action class:
package sample.struts2;
import dao.ProductDAO;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import jaxb.Products;
import utilities.XMLUtilities;
/**
*
* #author hoang
*/
public class SearchAction {
private String searchValue;
private String type;
private Products productList;
private String xmlProduct;
private final String SUCCESS = "success";
private final String FAIL = "fail";
private final int PRODUCT_PER_PAGE = 9;
private int page;
private InputStream result;
public SearchAction() {
}
public String execute() throws Exception {
System.out.println(searchValue);
productList = new Products();
ProductDAO dao = new ProductDAO();
productList = dao.searchProduct(searchValue, type);
if (productList.getProduct() == null) {
return FAIL;
}
page = (int) Math.ceil((float) productList.getProduct().size() / (float) PRODUCT_PER_PAGE);
xmlProduct = XMLUtilities.marshallJAXBToString(productList);
result = new ByteArrayInputStream(xmlProduct.getBytes("UTF-8"));
return SUCCESS;
}
public String getSearchValue() {
return searchValue;
}
public void setSearchValue(String searchValue) {
this.searchValue = searchValue;
}
public String getXmlProduct() {
return xmlProduct;
}
public void setXmlProduct(String xmlProduct) {
this.xmlProduct = xmlProduct;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public InputStream getResult() {
return result;
}
public void setResult(InputStream result) {
this.result = result;
}
}
and my jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="/struts-tags" prefix="s"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x"%>
<%#taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<c:import charEncoding="UTF-8" var="productXSL" url="/XSL/product.xsl"/>
<s:set var="productXML" value="%{xmlProduct}" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="CSS/product.css">
<script src="JS/product.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
totalPage = <s:property value="%{page}"/>;
updatePagination(totalPage);
parseXML(<s:property value="%{result}"/>);
getData(1);
getXSL();
});
</script>
<s:set name="productType" value="%{type}"/>
<s:if test="%{#productType.equals('Helmet')}">
<title>Mũ bảo hiểm</title>
</s:if>
<s:if test="%{#productType.equals('Glove')}">
<title>Găng tay bảo hộ</title>
</s:if>
</head>
<body>
<div id="header" >
<s:if test="%{#productType.equals('Helmet')}">
<span id="headerTitle">Mũ bảo hiểm</span>
</s:if>
<s:if test="%{#productType.equals('Glove')}">
<span id="headerTitle">Găng tay bảo hộ</span>
</s:if>
</div>
<div id="searchZone">
<div id="wrap">
<form action="search">
<input id="searchValue" type="text" name="searchValue" value="<s:property value="%{searchValue}"/>" placeholder="Nhập sản phẩm bạn cần tìm kiếm"/>
<input type="hidden" name="type" value="<s:property value="#productType"/>" />
<input id="btnSearch" type="submit" value="Tìm kiếm" />
</form>
</div>
</div>
<div id="productList">
<x:transform xml="${productXML}" xslt="${productXSL}"/>
</div>
<div class="pagination">
<nav></nav>
</div>
</body>
I'm really new to these techinque and get stuck,
Maybe this methode can htlp you: How to pass InputStream value in Struts2 action class to ajax in jsp page and convert the value into Json Array
it's consite to use JSON Array.
good luck.

Spring thymeleaf give error in post request

I have this simple code: This is my controller class where i redirecting to a page
#Controller
public class SimpleController {
#GetMapping("/nuovo-utente")
public String viewInserisciUtente(Model model){
model.addAttribute("nuovoUtente", new Utente());
return "nuovo-utente";
}
#PostMapping("/nuovo-utente")
public void memorizzaUtente(#ModelAttribute Utente utente){
System.out.println(utente.getId());
}
}
This is model class.
public class Utente {
private String id=null;
private String citta=null;
private String genere=null;
private String data_nascita=null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCitta() {
return citta;
}
public void setCitta(String citta) {
this.citta = citta;
}
public String getGenere() {
return genere;
}
public void setGenere(String genere) {
this.genere = genere;
}
public String getData_nascita() {
return data_nascita;
}
public void setData_nascita(String data_nascita) {
this.data_nascita = data_nascita;
}
}
and My html page with thymeleaf is like :
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Inserisci un nuovo utente</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/nuovo-utente}" th:object="${nuovoUtente}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Città: <input type="text" th:field="*{citta}" /></p>
<p>Genere: <input type="text" th:field="*{genere}" /></p>
<p>Data nascita: <input type="text" th:field="*{data_nascita}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
So, as I said into the title, this simple code for a form give me error when I try to submit the form by post request. The error is the above:
Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "nuovo-utente" - line 10, col 32)
What can you say to me? Some help will be appreciate
You have to use diferent html and urls. One to create the form and another one to submit the form. You are using the same url.
First of all in your html page change
<html xmlns:th="http://www.thymeleaf.org">
to
<html xmlns:th="http://www.w3.org/1999/xhtml">
And write your controller class like
#PostMapping("/nuovo-utente")
public String memorizzaUtente(#ModelAttribute("nuovoUtente") Utente utente) {
System.out.println(utente.getId());
return "any page";
}
}

c:foreach doesn't print objects

I'm extremely new to JSP. Anyway, I'm trying to print every object in a list using c:foreach but it does not work and I can't figure out why. I've already checked out similar issues but nothing has solved my problem.
<h2>
Your account information:
<%
LinkedList<BankAccount> accounts = null;
accounts = account1.getAccountList();
request.setAttribute("accounts", account1.getAccountList());
%>
</h2>
<c:foreach items="${accounts}" var="acct">
<p>${acct.accountName}</p><br/>
<p>$${acct.AccountBalance}</p><br/>
</c:foreach>
<TD valign="top"><B><%=accounts.get(0).accountName%></b><br>
<TD valign="top"><b>$<%=accounts.get(0).AccountBalance%></b></br>
</br></br>
<TD valign="top"><b><%=accounts.get(1).accountName%></b><br>
<TD valign="top"><b>$<%=accounts.get(1).AccountBalance%></b></br>
The bottom code works --- accounts.get(0), etc. But I can't use this because if I add data to the database then I have to add more code every time.
Thanks for the help.
You didn't provide info about your BankAccount class, therefore i would make an assumption:
package testingThings.EL.linkedlist;
public class BankAccount {
protected String accountName;
protected double accountBalance;
public BankAccount(String accountName, double accountBalance) {
this.accountName = accountName;
this.accountBalance = accountBalance;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(double accountBalance) {
this.accountBalance = accountBalance;
}
}
I changed AccountBalance accountBalance to stick to the conventions.
In your JSP you need the line that LeHill mentioned.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Don't forget the protocol: http://
The JSP:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="testingThings.EL.linkedlist.BankAccount"%>
<%# page import="java.util.LinkedList"%>
<%# 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
LinkedList<BankAccount> accounts = new LinkedList<BankAccount>();
accounts.add(new BankAccount("acc1", 1000.00));
accounts.add(new BankAccount("acc2", 2000.00));
pageContext.setAttribute("accounts", accounts);
%>
<c:forEach items="${accounts}" var="acct">
<p>${acct.accountName}</p>
<br />
<p>${acct.accountBalance}</p>
<br />
</c:forEach>
</body>
</html>
The Output in Browser:
acc1
1000.0
acc2
2000.0
It looks like you don't have getters and setters.
Your scriptlet has the attribute name as "accountName".
JSTL expects "get" or "is" as the beggining of the beans method name.
you can't call the attribute directly. You have to use getter methods.
if you created a method called "getAccountName" it should work.

java JSP Servlet Bean Calculator

I have tried to write a Calculator with JSP and a Servlet
which is working perfect now. (with your help!)
Now I want to write it with MVC.
So I have a JSP:
<?xml version="1.0" encoding="UTF-8" ?>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello</title>
</head>
<body>
<form action="Process" method="post">
Enter a number: <input type="text" name="num1" />
<input type="text" name="operand" type="submit "value="+" />
<input type="text" name="operand" type="submit "value="-" />
<input type="text" name="operand" type="submit "value="*" />
<input type="text" name="operand" type="submit "value="/" />
Enter a number: <input type="text" name="num2" />
<input type="submit" name="submit" value="OK" />
</form>
</body>
</html>
and I have the Servlet:
package controller;
import model.Calc;
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 java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
#WebServlet("/servlet")
public class Process extends HttpServlet {
private static final long serialVersionUID = 1L;
public Process() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String num1= request.getParam("num1");
String num2= request.getParam("num2");
request.getParameter("operand");
int num11 = Integer.parseInt(num1);
int num22 = Integer.parseInt(num2);
Calc calc = new Calc();
calc.setNum1(num11);
calc.setNum2(num22);
request.setAttribute("calc", calc);
request.getParameter("operand");
request.setAttribute("operand", operand);
request.setAttribute("calc", calc);
request.setAttribute(calc.getResult());
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}}
And the JavaBean Class:
package model;
import java.io.Serializable;
public class Calc implements Serializable{
private static final long serialVersionUID = 1L;
private int num1;
private int num2;
private int result;
private String operand;
public Calc() {
super();
}
public Calc(int num1, int num2, int result, String operand) {
super();
this.num1 = num1;
this.num2 = num2;
this.result = result;
this.operand = operand;
}
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
public int getResult() {
return result;
}
public void setResult(int result) {
if (operand.equals("+")) {
result = num11 + num22;
} else if (operand.equals("-")){
result = num11 - num22;
} else if (operand.equals("*")){
result = num11 * num22;
} else if (operand.equals("/")){
result = num11 / num22;
this.result = result;
}
public String getOperand() {
return operand;
}
public void setOperand(String operand) {
this.operand = operand;
}}
and this is the result:
it returns a 0 in the result field.
Thanks for your help!
Try changing your input tags to a select tag with options. Something like this
<select id="operand" name="operand" >
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="%">%</option>
</select>
Sometimes JSP tends to confuse, when their is the exact same name.

How to restrict a JSP hit counter?

I am writing a hit counter in JSP, for my coursework. I have write the code, and there is not error and its working, but the problem is that:
if the user have open the website and try to use different page, whenever that the user goes back to the home page the counter still is adding a number, how can I restrict this part? shall restrict it with session?
this is my code :
<jsp:useBean id="counter" scope="application" class="counter.CounterBean" />
The current count for the counter bean is:
<jsp:setProperty name="counter" property="coun" value="1"></jsp:setProperty>
<%
counter.saveCount();
int _numberofvisitors=counter.getVisitorsNumber();
out.println(_numberofvisitors);
%>
Bean:
package counter;
import java.sql.*;
import java.sql.SQLException;
public class CounterBean implements java.io.Serializable {
int coun = 0;
public CounterBean() {
database.DatabaseManager.getInstance().getDatabaseConnection();
}
public int getCoun() {
return this.coun;
}
public void setCoun(int coun) {
this.coun += coun;
}
public boolean saveCount() {
boolean _save = false;
database.SQLUpdateStatement sqlupdate = new database.SQLUpdateStatement("counter", "hitcounter");
sqlupdate.addColumn("hitcounter", getCoun());
if (sqlupdate.Execute()) {
_save = true;
}
return _save;
}
public int getVisitorsNumber() throws SQLException {
int numberOfVisitors = 0;
if (database.DatabaseManager.getInstance().connectionOK()) {
database.SQLSelectStatement sqlselect = new database.SQLSelectStatement("counter", "hitcounter", "0");
ResultSet _userExist = sqlselect.executeWithNoCondition();
if (_userExist.next()) {
numberOfVisitors = _userExist.getInt("hitcounter");
}
}
return numberOfVisitors;
}
}
Change this part of the code:
<%
counter.saveCount();
int _numberofvisitors=counter.getVisitorsNumber();
out.println(_numberofvisitors);
%>
To
<%
if (session.isNew()) {
counter.saveCount();
} else {
counter.setCoun(-1);
}
int _numberofvisitors=counter.getVisitorsNumber();
out.println(_numberofvisitors);
%>
Hope this helps.
UPDATE: By the way, it's better to choose better names for the methods of your Counter class. First of all, change setCoun to setCount. Besides, a setter method usually just assigns the value passed to it to its associated field. If you want to increment the value of coun, change the method name to addCount. Then increment the count value like:
<jsp:setProperty name="counter" property="coun" value="${1 + counter.coun}"></jsp:setProperty>
<%#page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Applcation object in JSP</title>
</head>
<body>
<%
Integer hitsCount=(Integer)application.getAttribute("hitcount");
int m;
if(hitsCount==null)
{
m=1;
hitsCount =Integer.valueOf(m);
application.setAttribute("hitcount", hitsCount);
}
else
{
hitsCount=(Integer)application.getAttribute("hitcount");
m=hitsCount.intValue()+1;
hitsCount= Integer.valueOf(m);
application.setAttribute("hitcount", hitsCount);
}
%>
<center>
<p>Total number of visits:<%=hitsCount.intValue()%> </p>
</center>
</body>
</html>

Categories