how to pass values jsp page into java using spring mvc? - java

I am using spring mvc with hibernate database connction,now how to pass values in jsp page into java page without call controller ,i am getting Error how to pass values jsp to java??
Jsp page
In this page i am using java code but unable to pass values in another java page
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%#page import="com.sample.utility.AutoIncrement" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>check page</title>
</head>
<body>
<div id="login_form">
<form:form action="check" method="post">
<table>
<tr>
<%String val=AutoIncrement.auto("ShopInfo"); System.out.println(" val : "+val);%>
<td class="f1_label">Shop code :</td>
<td>
<input type="text" name="shopcode" value="<%=val%>" />
</td>
</tr>
<tr>
<td class="f1_label">name :</td><td><input type="text" name="name" value="" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="login" value="Submit" style="font-size:18px; " />
</td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
Java Page :
This below code is java here unable to return values in jsp page
public static String auto(String value)
{
String reVal="";
System.out.println("Inc val : "+value);
Session session = sessionFactory.openSession();
try
{
session.beginTransaction().begin();
String SQL_QUERY = "{CALL pro_autoincrement('"+value+"') }";
query = session.createSQLQuery(SQL_QUERY);
reVal=query.toString();
System.out.println("Inc val : "+reVal);
session.getTransaction().commit();
}
catch(Exception ex)
{
if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE
|| session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK ) {
session.getTransaction().rollback();
}
}
finally
{
session.close();
}
return reVal;
}
Error:
SEVERE: Servlet.service() for servlet [jsp] in context with path [/annotation-based] threw exception [An exception occurred processing JSP page /welcome.jsp at line 18
15: <table>
16:
17: <tr>
18: <%String val=AutoIncrement.auto("ShopInfo"); System.out.println(" val : "+val);%>
19: <td class="f1_label">Shop code :</td>
20: <td>
21: <input type="text" name="shopcode" value="<%=val%>" />
Stacktrace:] with root cause
java.lang.NullPointerException
at com.sample.utility.AutoIncrement.auto(AutoIncrement.java:26)
at org.apache.jsp.welcome_jsp._jspService(welcome_jsp.java:81)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)

Insted of this.
reVal=query.toString();
you can do like this
reVal=(String)session.createQuery(queryString).UniqueResult();
Above Method Return Object.So we need to type Cast into String Format.

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>

Spring MVC JSP Form using multiple objects needs drop-down list

My Spring JSP Form uses 2 classes that I put in a wrapper class. The employee name part works. But now I need to create a drop-down list of Clients to choose from. I'm updating someone else's code, I believe "resultBoard.getFilteredResultsClients()" will return a List of Clients. Any tips or sample code of a Spring JSP Form that uses a drop-down to select from a List?
Java wrapper class with employee and client classes inside:
public class EmployeeFormWrapper {
private NewEmployeeVM employee = new NewEmployeeVM();
private ClientVM client = new ClientVM();
public NewEmployeeVM getEmployee(){
return this.employee;
}
public ClientVM getClient(){
return this.client;
}
}
My Controller class:
#Controller
#SessionAttributes({"resultBoard", "filterBoard"})
public class NewEmployeeController {
#Autowired
NewEmpDAO newEmpDAO;
#RequestMapping(value = "NewEmpInput", method = RequestMethod.GET)
public String promptEmployee(Model model)
{
model.addAttribute("myForm", new EmployeeFormWrapper());
return "NewEmpInput";
}
#RequestMapping(value = "NewEmpInput", method = RequestMethod.POST)
public String newEmployee(#ModelAttribute("myForm") EmployeeFormWrapper myForm)
{
NewEmployeeVM employee = myForm.getEmployee();
ClientVM client = myForm.getClient();
System.out.println("Employee = " + employee.getFirstName() + " " + employee.getLastName());
System.out.println("Client = " + client.getText());
try{newEmpDAO.writeNewEmployee(employee);}
catch (Exception e){
e.printStackTrace();
}
return "ConfirmNewEmp";
}
}
My JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page session="false"%>
<%# page import="com.model.FilterBoard"%>
<!DOCTYPE html>
<!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -->
<html>
<head>
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href="assets/css/bootstrap.css" rel="stylesheet">
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<link rel="stylesheet"
href="<c:url value='/resources/css/mainStyle.css'/>">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<style type="text/css">
body {
color:#000000;
// background-color:#FFFFFF;
background-color:tan;
background-image:url('Background Image');
background-repeat:no-repeat;
}
a { color:#0000FF; }
a:visited { color:#800080; }
a:hover { color:#008000; }
a:active { color:#FF0000; }
</style>
<title>New Employee Proposed To Project</title>
</head>
<body class="NewEmpBody">
<p>New Employee</p>
<form:form commandName="myForm" modelAttribute="myForm">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="employee.firstName" /></td>
<td>Middle Initial:</td>
<td><form:input path="employee.middleInitial" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="employee.lastName" /></td>
</tr>
<tr>
<td>Clients:</td>
<td>
<ul>
<c:forEach items="${resultBoard.getFilteredResultsClients()}"
var="filteredResultsClient">
<li><form:button name="toggleClient" class="btn btn-link"
value='${filteredResultsClient.toJSON()}'>
${filteredResultsClient.getText()}
</form:button></li>
</c:forEach>
</ul>
</td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
I got it, I changed my JSP to look like this and it gave me a nice drop-down list:
<body class="NewEmpBody">
<p>New Employee Proposed To Project Before Entered Into OpenAir</p>
<form:form commandName="myForm" modelAttribute="myForm">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="employee.firstName" /></td>
<td>Middle Initial:</td>
<td><form:input path="employee.middleInitial" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="employee.lastName" /></td>
</tr>
<tr>
<td>Client :</td>
<td><form:select path="client.text">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${resultBoard.getFilteredResultsClients()}" />
</form:select>
</td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>

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()) );

Arabic value does not work in jsp servlet

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");

Categories

Resources