Arabic value does not work in jsp servlet - java

I have one demo code where I have three jsp named arabic1.jsp, arabic2.jsp, arabic3.jsp and one servlet named ArabicServlet.
Inside arabic1.jsp I have one textbox where I entered arabic value and submitted the page by calling ArabicServlet servlet, which forward same content to arabic2.jsp, where I have displayed the same content inside textbox which is correctly displayed.
Now I have one link on arabic2.jsp to forward request on arabic3.jsp using same servlet and content, here on arabic3.jsp I have displayed same arabic content inside textbox but I got wrong characters.
I am entering value on first jsp as محمد , It is shown on third jsp as ÙØ­Ùد
arabic1.jsp
<%# page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<form action="/test/ArabicServlet" method="post">
<table name="tbl1" id="tbl1">
<tr>
<td>
<input type="hidden" id="page" name="page" value="1"/>
</td>
<td>
Name :
</td>
<td>
<input type="text" id="arabic" name="arabic">
</td>
<td>
<input type="submit" id="arabic" name="arabic">
</td>
</tr>
</table>
</form>
</body>
</html>
arabic2.jsp
<%# page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<%
Map map = (Hashtable)request.getAttribute("arabic");
String arabicvalue = (String)map.get("arabicmap");
System.out.println("Arabic Value on jsp = "+arabicvalue);
String url = "/test/ArabicServlet?page=2&arabicvalue="+arabicvalue;
%>
</head>
<body>
<form action="/test/ArabicServlet" method="post">
<table name="tbl1" id="tbl1">
<tr>
<td>
Name :
</td>
<td>
<input type="text" id="arabic" name="arabic" value="<%=arabicvalue%>">
</td>
<td>
Test
</td>
</tr>
</table>
</form>
</body>
</html>
arabic3.jsp
<%# page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<%
Map map = (Hashtable)request.getAttribute("arabic");
String arabicvalue = (String)map.get("arabicmap");
System.out.println("Arabic Value on jsp = "+arabicvalue);
String url = "/test/ArabicServlet?page=2&arabicvalue="+arabicvalue;
%>
</head>
<body>
<form action="/test/ArabicServlet" method="post">
<table name="tbl1" id="tbl1">
<tr>
<td>
Name :
</td>
<td>
<input type="text" id="arabic" name="arabic" value="<%=arabicvalue%>">
</td>
</tr>
</table>
</form>
</body>
</html>
ArabicServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
request.setCharacterEncoding("UTF-8");
String page = request.getParameter("page");
System.out.println("Page Number = "+page);
if(page.equals("1")){
String arabic = (String)request.getParameter("arabic");
System.out.println("Arabic Value from first page = "+arabic);
Map map = new java.util.Hashtable();
map.put("arabicmap",arabic);
request.setAttribute("arabic",map);
request.getRequestDispatcher("arabic2.jsp").forward(request,response);
}else{
String arabic = (String)request.getParameter("arabicvalue");
Map map = new java.util.Hashtable();
map.put("arabicmap",arabic);
request.setAttribute("arabic",map);
System.out.println("Arabic Value from first page = "+arabic);
request.getRequestDispatcher("arabic3.jsp").forward(request,response);
}
}

I resolve similar problem by putting these lines in my code:
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

Related

Problem with sending id from one jsp to another (update link)

I have a problm with update link for updating my transaction. At one jsp I have a list with transactions, and after pressing Update" which is link i wanted to pass transactionId, update it, save and get back to list. I've used c:param hidden and it doesnt work. I have no idea why it doesnt pass id and autofill forms. It seems like values are passed in session when ive clicked testing transaction:
http://localhost:8080/transaction/addTransaction?transactionId=64&userId=1
Here is transaction Controller:
#Controller
#RequestMapping("/transaction")
public class TransactionController {
#Autowired
TransactionService transactionService;
#Autowired
CategoryService categoryService;
#Autowired
UserService userService;
#GetMapping("/addTransaction")
public String transactionsList(Model theModel){
Transaction transaction = new Transaction();
theModel.addAttribute("user",userService.getAllUsers());
theModel.addAttribute("category", categoryService.getAllCategories());
theModel.addAttribute("newTransaction", transaction);
return "addTransaction";
}
#PostMapping("/saveTransaction")
public String saveTransaction(#ModelAttribute("newTransaction") Transaction
newTransaction,
BindingResult theBindingResult,
HttpServletRequest request) throws
ParseException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String date = request.getParameter("transactionDate");
LocalDate localDate = LocalDate.parse(date, formatter);
Date formatedDate =
Date.from(localDate.atStartOfDay().toInstant(ZoneOffset.ofHours(-3)));
newTransaction.setTransactionDate(formatedDate);
transactionService.saveTransaction(newTransaction);
return "redirect:/user/userPage";
}
#GetMapping("/deleteTransaction")
public String deleteUser(#RequestParam("transactionId") int idFromTransactionToDelete,
#RequestParam("userId") int loggedUserId,
RedirectAttributes redirectAttributes){
transactionService.deleteTransactionById(idFromTransactionToDelete);
User loggedUser = userService.getUserById(loggedUserId);
redirectAttributes.addFlashAttribute("loggedUser", loggedUser);
return "redirect:/user/userPage";
}
#GetMapping("/updateTransaction")
public String updateUser(#RequestParam("transactionId") int
idFromTransactionToUpdate,
#RequestParam("userId") int loggedUserId,
RedirectAttributes redirectAttributes,
Model theModel){
Transaction transactionToUpdate = transactionService.getSingleTransactionById(idFromTransactionToUpdate);
transactionToUpdate.setUser(userService.getUserById(loggedUserId));
theModel.addAttribute("newTransaction",transactionToUpdate);
theModel.addAttribute("category", categoryService.getAllCategories());
User loggedUser = userService.getUserById(loggedUserId);
redirectAttributes.addFlashAttribute("loggedUser", loggedUser);
redirectAttributes.addFlashAttribute("newTransaction",
transactionToUpdate);
return "addTransaction";
}
}
Transactions list page:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<html>
<head>
<title>User page</title>
</head>
<body>
<c:url var="addTransactionLink" value="/transaction/addTransaction"/>
<c:url var="addFixedTransactionLink"
value="/fixedTransaction/addFixedTransaction"/>
<h1>Welcome ${loggedUser.login} !</h1>
<br>
<h2>Here are your latest transactions:</h2>
<br>
<a href=${addTransactionLink}>
<input type="button" value="Add Transaction"/>
</a>
<a href=${addFixedTransactionLink}>
<input type="button" value="Add Fixed Transaction"/>
</a>
<table>
<tr>
<th>Category</th>
<th>Price</th>
<th>Description</th>
<th>Date</th>
</tr>
<c:forEach var="transaction" items="${userTransactions}">
<c:url var="deleteTransactionLink"
value="/transaction/deleteTransaction">
<c:param name="transactionId"
value="${transaction.transactionId}"/>
<c:param name="userId" value="${loggedUser.id}"/>
</c:url>
<c:url var="updateTransactionLink"
value="/transaction/addTransaction">
<c:param name="transactionId"
value="${transaction.transactionId}"/>
<c:param name="userId" value="${loggedUser.id}"/>
</c:url>
<tr>
<td>${transaction.category.categoryName}</td>
<td>${transaction.moneyAmount}</td>
<td>${transaction.description}</td>
<td>${transaction.transactionDate}</td>
<td>Delete </td>
<td>Update </td>
<td>${transaction.transactionId}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
And add transaction formular:
<%# taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Add Transaction Form</title>
<link rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/style.css"/>
</head>
<body>
<h1>Add transaction to database:</h1>
<form:form action="saveTransaction" modelAttribute="newTransaction"
method="post">
<form:hidden path="transactionId"/>
${newTransaction.toString()}
${newTransaction.transactionId}
<table>
<tr>
<td><label>Choose category:</label></td>
<td><form:select name="category.id" path="category.id">
<c:forEach items="${category}" var="category">
<form:option value="${category.id}">${category.categoryName}
</form:option>
</c:forEach>
</form:select>
</tr>
<tr>
<td><label>Choose user:</label></td>
<td><form:select name="user.id" path="user.id">
<c:forEach items="${user}" var="user">
<form:option value="${user.id}">${user.login}
</form:option>
</c:forEach>
</form:select>
</tr>
<tr>
<td><label>Amount:</label></td>
<td><form:input path="moneyAmount" />
</td>
</tr>
<tr>
<td><label>Transaction date:</label></td>
<td><form:input type = "date" path="transactionDate"/>
</td>
</tr>
<tr>
<td><label>Description:</label></td>
<td><form:input path="description" />
</td>
</tr>
<tr>
<label></label>
<td><input type="submit" value="Submit" class="save"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Problem seems to be in your code. You have defined in jsp:
<c:url var="updateTransactionLink"
value="/transaction/addTransaction">
while in java code:
#GetMapping("/updateTransaction")
public String updateUser(#RequestParam("transactionId") int
In JSP Change it to :
<c:url var="updateTransactionLink"
value="/transaction/updateTransaction">

I am trying to insert data in to a SQL database in my local computer using Java jsp

I am creating a web application in java jsp using Eclipse and Tomcat.but I am stock unable to insert the data in to my local SQL server. The Form of the page is coded in HTML then I want the Java code part to get the data entered and insert the data in to the database but when I click the submit button absolutely nothing happens, no error message, no warning so far I am only able to type and clear the form. I am very new in Java. I just pick up this codding language recently but I am determine to learn it.
Help please here is my full code.
<%# page import="java.text.*,java.util.*" session="false"%>
<%# page import="java.sql.*" %>
<%#page import="javax.swing.JOptionPane" %>
<%#page import="java.util.Date" %>
<%#page import ="java.io.IOException" %>
<%#page import ="javax.servlet.ServletException" %>
<%#page import ="javax.servlet.http.HttpServlet" %>
<%#page import ="javax.servlet.http.HttpServletRequest" %>
<%#page import ="javax.servlet.http.HttpServletResponse" %>
<% Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); %>
<%# 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 Laptops Data</title>
<link rel="stylesheet" href="Style.css" type="text/css">
</head>
<body>
<%!public class Insert extends HttpServlet {
String dbURL = "jdbc:sqlserver://localhost\\SQLYRSIN";
String user = "pass";
String pass = "pass";
Connection conn = null;
PreparedStatement InsertLaptops = null;
ResultSet resultSet = null;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String LaptopMake, LaptopModel, LaptopServicetag, LaptopDatein, LaptopNotes, LaptopType;
LaptopMake = req.getParameter("iMake");
LaptopModel = req.getParameter("iModel");
LaptopServicetag = req.getParameter("iServiceTag");
LaptopDatein = req.getParameter("iDatein");
LaptopNotes = req.getParameter("iNotes");
LaptopType = req.getParameter("iType");
try {
conn = DriverManager.getConnection(dbURL, user, pass);
Statement st = conn. createStatement();
st.executeUpdate("INSERT INTO LaptopsTable (Make, Model, [Service Tag], Datein, Notes, Type)"
+ " VALUES ('"+LaptopMake+"','"+LaptopModel+"','"+LaptopServicetag+"','"+LaptopDatein +"','"+LaptopNotes+"','"+LaptopType+"')");
JOptionPane.showConfirmDialog(null, "Your Data Has been Inserted", "Result", JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE);
st.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}%>
<div id="header">
<div class="logo">
<span> Resident Screening</span> Jinventory
</div>
</div>
<div id="container">
<div class="content">
<h1>Add New Laptop</h1>
<p>Make sure all Service Tag Enter in here are Laptops</p>
<div id="box">
<form name="LaptopsForm" method="get" class="contentfonts"
action="LaptopsInsert2.jsp" method="Post">
<table>
<tbody>
<tr>
<td>Service Tag</td>
<td><input type="text" name="iServiceTag" size="40"></td>
</tr>
<tr>
<td>Make</td>
<td><input type="text" name="iMake" size="40"></td>
</tr>
<tr>
<td>Model</td>
<td><input type="text" name="iModel"></td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="iDate"></td>
</tr>
<tr>
<td>Type</td>
<td><input type="text" name="iTyped" Value="Laptop"
disabled="disabled"></td>
</tr>
<tr>
<td>Notes</td>
<td><input Type="text" name="iNotes" size="30" height="40"></td>
</tr>
<tr>
<td><input type="reset" name="Reset"></td>
<td><input type="submit" name="submit"></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
Here's a draft which you could use as a starting point.
As mentioned before, you should seriously consider some changes to your design:
Separate View (.jsp) from Business-Logic (SQL-Statements etc.)
Don't use scriptlets ( <% and so on )
Creating a Servlet within JSP is overkill - a JSP is compiled into a servlet by the servlet container.
Don't create Connections one-by-one. Use a connection pool. This will pay off quickly.
In the code you'll see some changes to your setup:
form is submitted per POST
instead of subclass, JSP checks for methods POST and only then tries the insert.
never ever use Swing inside Webapps. If that JOptionPane was opened, your webapp would block at that point, while the Dialog was shown somewhere on your server.
Use of PreparedStatement instead of Statement this prevents SQL injection. You'll still want to check against Cross-Site-Scripting if you plan on displaying the inserted values in your webapp again.
Disclaimer: I haven't tested or even tried to compile this code. Edit was done only to point you in the right direction.
Here it goes
<%#page import="java.text.*,java.util.*" session="false"%>
<%#page import="java.sql.*" %>
<%#page import="java.util.Date" %>
<%#page import ="java.io.IOException" %>
<%#page import ="javax.servlet.ServletException" %>
<%#page import ="javax.servlet.http.HttpServlet" %>
<%#page import ="javax.servlet.http.HttpServletRequest" %>
<%#page import ="javax.servlet.http.HttpServletResponse" %>
<% Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); %>
<%# 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 Laptops Data</title>
<link rel="stylesheet" href="Style.css" type="text/css">
</head>
<body>
<%
if("POST".equals(request.getMethod()) {
String dbURL = "jdbc:sqlserver://localhost\\SQLYRSIN";
String user = "pass";
String pass = "pass";
Connection conn = null;
PreparedStatement InsertLaptops = null;
ResultSet resultSet = null;
String LaptopMake, LaptopModel, LaptopServicetag, LaptopDatein, LaptopNotes, LaptopType;
LaptopMake = req.getParameter("iMake");
LaptopModel = req.getParameter("iModel");
LaptopServicetag = req.getParameter("iServiceTag");
LaptopDatein = req.getParameter("iDatein");
LaptopNotes = req.getParameter("iNotes");
LaptopType = req.getParameter("iType");
try {
conn = DriverManager.getConnection(dbURL, user, pass);
PreparedStatement st = conn.prepareStatement("INSERT INTO LaptopsTable (Make, Model, [Service Tag], Datein, Notes, Type) VALUES (?,?,?,?,?,?)");
st.setString(1, LaptopMake);
st.setString(2, LaptopModel);
st.setString(3, LaptopServicetag);
st.setString(4, LaptopDatein);
st.setString(5, LaptopNotes);
st.setString(6, LaptopType);
st.executeUpdate();
//This is SWING - and would at best popup a Dialog ON YOUR SERVER
//JOptionPane.showConfirmDialog(null, "Your Data Has been Inserted", "Result", JOptionPane.DEFAULT_OPTION,
// JOptionPane.PLAIN_MESSAGE);
//Alternative: Show some HTML.
%>
<h1>Your Data has been inserted.</h1>
<%
st.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
} //END of Method.equals("POST")
%>
<div id="header">
<div class="logo">
<span> Resident Screening</span> Jinventory
</div>
</div>
<div id="container">
<div class="content">
<h1>Add New Laptop</h1>
<p>Make sure all Service Tag Enter in here are Laptops</p>
<div id="box">
<form name="LaptopsForm" method="POST" class="contentfonts"
action="" method="POST">
<table>
<tbody>
<tr>
<td>Service Tag</td>
<td><input type="text" name="iServiceTag" size="40"></td>
</tr>
<tr>
<td>Make</td>
<td><input type="text" name="iMake" size="40"></td>
</tr>
<tr>
<td>Model</td>
<td><input type="text" name="iModel"></td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="iDate"></td>
</tr>
<tr>
<td>Type</td>
<td><input type="text" name="iTyped" Value="Laptop"
disabled="disabled"></td>
</tr>
<tr>
<td>Notes</td>
<td><input Type="text" name="iNotes" size="30" height="40"></td>
</tr>
<tr>
<td><input type="reset" name="Reset"></td>
<td><input type="submit" name="submit"></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</body>
</html>

How can a execute a query in JSP on text change of input box

Now i am doing this code which is working on submit button click.
<%#page import="java.sql.CallableStatement"%>
<%#page import="javax.imageio.ImageIO"%>
<%#page import="java.io.ByteArrayOutputStream"%>
<%#page import="java.awt.image.BufferedImage"%>
<%#page import="java.io.InputStream"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="connectionss.Connectionss"%>
<%# 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>
<form action="ShowUSerInfo.jsp" method="post">
<input type="text" name="tagID">
<input type="submit" value="Search" name="submit" >
</form>
<%
String TAGID="";
String y=request.getParameter("submit");
if("Search".equals(y))
{
TAGID = request.getParameter("tagID");
out.println(TAGID);
String GetUserpass = "{call sp_USerInfoByTagID(?)}";
//Connection conn = Connection.GetConnection();
CallableStatement cs;
cs = Connectionss.GetConnection().prepareCall(GetUserpass);
cs.setString(1,TAGID);
%>
<table border="1">
<th>First Name</th>
<th>last Name Name</th>
<th>Student ID</th>
<th>Address</th>
<th>NIC</th>
<%
ResultSet rs1;
rs1=cs.executeQuery();
while(rs1.next()){
String UserName=rs1.getString("fId_FirstName");
String UserID= rs1.getString("fId_User_UniversityID");
String Adress = rs1.getString("fId_Address");
String NIC = rs1.getString("fId_NIC");
String lastName = rs1.getString("fId_LastName");
%>
<tr >
<td><span style="color:red;"><%= UserName %></span></td>
<td> <span style="color:red;"><%= lastName %></span></td>
<td><span style="color:red;"><%= UserID %></span></td>
<td><span style="color:red;"><%= Adress %></span></td>
<td><span style="color:red;"><%= NIC %></span></td>
</tr>
</table>
<%}} %>
</body>
</html>
But i want to execute this code when text changes on input box. Basically text box is getting value from NFC cards. so when i tap my NFC card on Reader value is transfer to text box and at this time i want to execute my sql query that will take the user information against TAGID.
since jsp is server side you'll need to collect the input on client and make a ajax call.
<form action="ShowUSerInfo.jsp" method="post">
<input type="text" id="text" name="tagID">
<input type="submit" value="Search" name="submit" >
</form>
<div id="#res></div>
javascript :
$('#text').change(function(e){
$.ajax({url: "someurl", success: function(result){
$("#res").html(result);
}});
});
});
this will perfectly work in your case,
Let's say our HTML looks something like,
<form>
<input id="txt" type="text" name="name"/>
<input id="btn" type="button" value="change"/>
</form>
Java-Script like,
$(document).ready(function(){
$('#txt').keypress(function(e){
ontextchange();
});
$('#txt').keyup(function(e){
if(e.keyCode == 8)
{
//if user erase from text-box then comes here...
}
});
function ontextchange(){
//do whatever while text change, i.e. ajax call or something else...
}
});

Clear Cart button in Java

Hi I'm trying to make a "Clear Cart" button in my java code but i'm having difficulty.
I've been trying for a couple of hours but i can't get it to work
I think it has something to do mostly with the first part that has all the strings and variables.
Here's the code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%# page errorPage="errorpage.jsp" %>
<jsp:useBean id="cart" scope="session" class="beans.ShoppingCart" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>the Game Store</title>
</head>
<body>
<%
String id = request.getParameter("id");
if ( id != null ) {
String desc = request.getParameter("desc");
Float price = new Float(request.getParameter("price"));
cart.addItem(id, desc, price.floatValue(), 1);
}
%>
Shopping Cart Quantity:
<%=cart.getNumOfItems() %>
<hr>
<center><h3>Games</h3></center>
<table border="1" width="300" cellspacing="0"
cellpadding="2" align="center">
<tr><th>Description</th><th>Price</th></tr>
<tr>
<form action="AddToShoppingCart.jsp" method="post">
<td>Goat Simulator</td>
<td>$11.95</td>
<td><input type="submit" name="Submit" value="Add"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="Goat Simulator">
<input type="hidden" name="price" value="11.95">
</form>
</tr>
<tr>
<form action="AddToShoppingCart.jsp" method="post">
<td>Metal Gear Solid V</td>
<td>$59.99</td>
<td><input type="submit" name="Submit" value="Add"></td>
<input type="hidden" name="id" value="2">
<input type="hidden" name="desc" value="Metal Gear Solid V">
<input type="hidden" name="price" value="59.99">
</form>
</tr>
<tr>
<form action="AddToShoppingCart.jsp" method="post">
<input type ="submit" name="empty" id="empty-button" value="Empty Cart"/>
</form>
Clear
</tr>
</table>
</body>
</html>
Here's the second page for the entire page
<%# page errorPage="errorpage.jsp" %>
<%# page import="java.util.*" %>
<jsp:useBean id="cart" scope="session" class="beans.ShoppingCart" />
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Contents</title>
</head>
<body>
<center>
<table width="300" border="1" cellspacing="0"
cellpadding="2" border="0">
<caption><b>Shopping Cart Contents</b></caption>
<tr>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<%
Enumeration e = cart.getEnumeration();
String[] tmpItem;
// Iterate over the cart
while (e.hasMoreElements()) {
tmpItem = (String[])e.nextElement();
%>
<tr>
<td><%=tmpItem[1] %></td>
<td align="center">$<%=tmpItem[2] %></td>
<td align="center"><%=tmpItem[3] %></td>
</tr>
<%
}
%>
</table>
</center>
Back to Catalog
</body>
</html>

Error with google app engine:Unable to compile class for JSP

I encountered this error while working on a web application for google app engine,through this tutorial.http://www.vogella.com/tutorials/GoogleAppEngineJava/article.html. Would like to hear more advice from you. Thank you.
HTTP ERROR 500
Problem accessing /. Reason:
Unable to compile class for JSP:
An error occurred at line: 34 in the jsp file: /TodoApplication.jsp
Type mismatch: cannot convert from List<Todo> to List<Todo>
31: if (user != null){
32: url = userService.createLogoutURL(request.getRequestURI());
33: urlLinktext = "Logout";
34: todos = dao.getTodos(user.getUserId());
35: }
36:
37: %>
Stacktrace:
Caused by:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 34 in the jsp file: /TodoApplication.jsp
Type mismatch: cannot convert from List<Todo> to List<Todo>
31: if (user != null){
32: url = userService.createLogoutURL(request.getRequestURI());
33: urlLinktext = "Logout";
34: todos = dao.getTodos(user.getUserId());
35: }
36:
37: %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="java.util.List" %>
<%# page import="com.google.appengine.api.users.User" %>
<%# page import="com.google.appengine.api.users.UserService" %>
<%# page import="com.google.appengine.api.users.UserServiceFactory" %>
<%# page import="de.vogella.gae.java.todo.model.Todo" %>
<%# page import="de.vogella.gae.java.todo.dao.Dao" %>
TodoApplication.jsp
<!DOCTYPE html>
<%#page import="java.util.ArrayList"%>
<html>
<head>
<title>Todos</title>
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<meta charset="utf-8">
</head>
<body>
<%
Dao dao = Dao.INSTANCE;
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String url = userService.createLoginURL(request.getRequestURI());
String urlLinktext = "Login";
List<Todo> todos = new ArrayList<Todo>();
if (user != null){
url = userService.createLogoutURL(request.getRequestURI());
urlLinktext = "Logout";
todos = dao.getTodos(user.getUserId());
}
%>
<div style="width: 100%;">
<div class="line"></div>
<div class="topLine">
<div style="float: left;"><img src="images/todo.png" /></div>
<div style="float: left;" class="headline">Todos</div>
<div style="float: right;"><%=urlLinktext%> <%=(user==null? "" : user.getNickname())%></div>
</div>
</div>
<div style="clear: both;"/>
You have a total number of <%= todos.size() %> Todos.
<table>
<tr>
<th>Short description </th>
<th>Long Description</th>
<th>URL</th>
<th>Done</th>
</tr>
<% for (Todo todo : todos) {%>
<tr>
<td>
<%=todo.getShortDescription()%>
</td>
<td>
<%=todo.getLongDescription()%>
</td>
<td>
<%=todo.getUrl()%>
</td>
<td>
<a class="done" href="/done?id=<%=todo.getId()%>" >Done</a>
</td>
</tr>
<%}
%>
</table>
<hr />
<div class="main">
<div class="headline">New todo</div>
<% if (user != null){ %>
<form action="/new" method="post" accept-charset="utf-8">
<table>
<tr>
<td><label for="summary">Summary</label></td>
<td><input type="text" name="summary" id="summary" size="65"/></td>
</tr>
<tr>
<td valign="description"><label for="description">Description</label></td>
<td><textarea rows="4" cols="50" name="description" id="description"></textarea></td>
</tr>
<tr>
<td valign="top"><label for="url">URL</label></td>
<td><input type="url" name="url" id="url" size="65" /></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" value="Create"/></td>
</tr>
</table>
</form>
<% }else{ %>
Please login with your Google account
<% } %>
</div>
</body>
</html>
I built and ran the very good Google App Engine Tutorial for Java (Todo list with JPA) with no problems at all. The platform was GAE SDK 1.8.9, Eclipse 3.8, OpenJDK 7u21 and Debian Testing (jessie). This result verifies the correctness of all the tutorial source code. Your problem is somewhere in your local installation.
Probably, the instance returned by your dao.getTodos method, is not from a class that implements java.util.List interface.
The line
34: todos = dao.getTodos(user.getUserId());
clobbers the reference to ArrayList assigned earlier to todos. Instead try
todos.addAll( dao.getTodos(user.getUserId()) );

Categories

Resources