completing read CRUD sql in jsp servlet - java

I asked this questions last night, and was kind of foolish not to ask how to complete the coding on it. I now have a dropdown box in a JSP populated with some data from an SQL database. I am trying to get the selected data to direct to the final viewing page, but again am running into some difficulty with this.
When I run the program, it either populates the page with all the data from the list database, or will give me an unfriendly error.
My current coding is as such:
the Bean:
package com.login.read;
public class ReadBean {
protected int id;
protected String title;
protected String author;
protected String text;
public int getId(){
return id;
}
public void setId(int newID){
id = newID;
}
public String getTitle(){
return title;
}
public void setTitle(String newTitle){
title = newTitle;
}
public String getAuthor(){
return author;
}
public void setAuthor(String newAuthor){
author = newAuthor;
}
public String getText(){
return text;
}
public void setText(String newText){
text = newText;
}
}
The Controller:
package com.login.read;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet (urlPatterns={"/com/defaultValidate/ReadController"})
public class ReadController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String address;
List<ReadBean> myList = new ArrayList<ReadBean>();
if(request.getParameter("ReadConfirm") != null){
try {
Connection connect = ConnectionManager.getConnection();
String SQL = "SELECT * FROM prayers ORDER BY prayerTitle DESC";
PreparedStatement ps = connect.prepareStatement(SQL);
ResultSet rs = ps.executeQuery();
while(rs.next()){
ReadBean reader = new ReadBean();
reader.setTitle(rs.getString("prayerTitle"));
reader.setAuthor(rs.getString("author"));
reader.setText(rs.getString("text"));
myList.add(reader);
}
request.getSession().setAttribute("ref", myList);
rs.close();
ps.close();
connect.close();
} catch (Exception e) {
}
address = "ReadConfirm.jsp";
} else if(request.getParameter("ReadView") != null){
address = "ReadView.jsp";
} else{
address = null;
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
And my jsp pages that link the drop-down box to the selected material:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%#include file="MenuHeader.jsp"%>
</div>
<div id="mainBorder"> </div>
<div id="mainBody">
<table id="mainTable">
<tr>
<td id="sidebar">
<h2>Options</h2>
<ul>
</ul>
</td>
<td id="mainContent">
<h2 id="contentHeader">Select a prayer</h2>
<form action="ReadController">
<table border="1" width="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><select name="prayer_id">
<c:forEach var="view" items="${ref}">
<h2>${view.title}</h2>
<h3>${view.author}</h3>
<p>${view.text}</p>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td><input type="submit" name="ReadView" value="View"> </td>
</tr>
</tbody>
</table>
</form>
<td id="imageBar">
</td>
</table>
<%# include file="../menuHeaderAndFooter/MenuFooter.jsp" %>
and the final viewing page:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%#include file="MenuHeader.jsp"%>
</div>
<div id="mainBorder"> </div>
<div id="mainBody">
<table id="mainTable">
<tr>
<td id="sidebar">
<h2>Options</h2>
<ul>
</ul>
</td>
<td id="mainContent">
<c:forEach var="view" items="${res}">
<h2>${view.title}</h2>
<h3>${view.author}</h3>
<p>${view.text}</p>
</c:forEach>
<form action="../Read.jsp">
<p>Click on the return button to return to the main menu</p>
<input type="submit" name="return" value="Return">
</form>
<td id="imageBar">
</td>
</table>
<%# include file="../menuHeaderAndFooter/MenuFooter.jsp" %>
As always, any and all assistance in this regard is incredibly helpful. I am a relative newbie to the world of jsp and servlets.
If one needs any reference as to the continuation of this sequence, kindly view the previous question I posted regarding dynamically displaying data in a jsp combo-box.
Thank you for your time and help.

By reading above code, I can just ask you that where you have stored your session attribute in variable "var", which is being used in c:foreach loop ?

Related

Cannot pass data from mysql using servlet to jsp/html table

I'm trying to create Java web application using tomcat 8 server in eclipse.
I've created servlet which forwards request to jsp page and initialize table inside this page with data from two tables. I've been following several examples on the internet on how to fill html table with recoreds from MySQL DB but failed. I'm using MainServlet's doGet method to get data from my local database into list and set it as attribute in request. But when i'm launching servlet there are no records in jsp table. Servlet connects to db and recieves records from it (i've already debugged app). So what is wrong with my code? I'm new to html and css,servlet and jsp technology. Maybe problem is with css framework i'm using (Materialize CSS).
Here is my MainServlet.java code:
package redirect;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import util.Book;
#WebServlet(name="Libbook",urlPatterns={"/libbook"})
public class MainServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static String url = "jdbc:mysql://localhost:3306/Test";
private static String user = "user",password = "password";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
List<Book> books = new ArrayList<>();
Connection connection = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url,user,password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(
"SELECT IDBook,Title,AddDate,ISBN,Name,Sirname "
+ "FROM Book INNER JOIN Author "
+ "ON Book.IDAuthor = Author.IDAuthor;");
while (resultSet.next())
{
Book b = new Book();
b.setId(resultSet.getInt(1));
b.setTitle(resultSet.getString(2));
b.setIsbn(resultSet.getLong(4));
b.setDate(resultSet.getDate(3).toString());
b.setName(resultSet.getString(5));
b.setSirname(resultSet.getString(6));
books.add(b);
}
}
catch (SQLException | ClassNotFoundException e)
{
e.printStackTrace();
}
finally {
try {if(connection != null)connection.close();}catch (SQLException e) {e.printStackTrace();}
}
request.setAttribute("books", books);
request.getRequestDispatcher("pages/libbook.jsp").forward(request, response);
}
}
libbook.jsp page:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8"/>
<title>LibBook</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<style type="text/css">
.logo{
color: #444;
text-transform: uppercase;
letter-spacing: 0.3em;
font-size: 2em;
}
.logo img{
width: 5%;
margin: 0.5%;
vertical-align: middle;
margin-right: 0.5em;
}
</style>
</head>
<body>
<nav class="white">
<div class="navbar-wrapper container">
<a id="logo-container" href="#" class="logo">
LIBBOOK
<img src="assets/book.svg" alt="LibBooklogo">
</a>
<ul class="right">
<li><a class="waves-effect waves-light btn" href="pages/new_author.jsp"><i class="material-icons left">perm_identity</i>NEW AUTHOR</a></li>
<li><a class="waves-effect waves-light btn" href="pages/new_book.jsp"><i class="material-icons left">class</i>NEW BOOK</a></li>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="card-panel">
<form action="test">
<div class="input-field">
<input placeholder="Type here (title,author) and press enter.." id="search_bar" type="text">
<label for="search_bar">Search</label>
</div>
</form>
</div>
</div>
<div class="row">
<div class="card-panel">
<table>
<thead>
<tr>
<th>ISBN</th>
<th>Title</th>
<th>Author</th>
<th>Info/Edit</th>
<th>Remove</th>
</tr>
</thead>
<c:forEach var="book" items="${books}">
<tr>
<td><c:out value="${book.isbn}"/></td>
<td><c:out value="${book.title}"/></td>
<td><c:out value="${book.name}"/></td>
<td>
<i class="material-icons">mode_edit</i>
</td>
<td>
<i class="material-icons">delete</i>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
</body>
</html>
Book class:
package util;
import java.io.Serializable;
public class Book implements Serializable
{
private Integer id;
private String title;
private String date;
private Long isbn;
private String name;
private String sirname;
public Book(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Long getIsbn() {
return isbn;
}
public void setIsbn(Long isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSirname() {
return sirname;
}
public void setSirname(String sirname) {
this.sirname = sirname;
}
}
Found solution. Problem was in jsp file, i did not include imports related to c tag scriplet:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%# taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
And didn't add jstl-1.2.jar library to my project
Java looks for a getter method in a bean class to read the data.
As you bean class(Book) getter method names are like getISBN(), getTitle() , getAName() etc. You should use code in jsp like
<td><c:out value="${book.iSBN}"/></td>
<td><c:out value="${book.title}"/></td>
<td><c:out value="${book.aName}"/></td>

Glassfish 4 URL mapping

Please help me, I cann't do this for 3rd day((
Here is my web.xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>ebookshopservlet</servlet-name>
<servlet-class>
ebookshop.ShoppingServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ebookshopservlet</servlet-name>
<url-pattern>/eshop</url-pattern>
</servlet-mapping>
</web-app>
I have jsp project, and there is an issue with /ebookshop/eshop url, it constantly writes 404 error - not found. What is my mistake in configuring this web server and application?
there is my servlet
package ebookshop;
import java.util.Vector;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import ebookshop.Book;
import javax.servlet.annotation.WebServlet;
/**
*
* #author Ilqar
*/
public class ShoppingServlet extends HttpServlet{
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
doPost(req,res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
// #WebServlet(name = "ShoppingServlet", urlPatterns = {"/eshop"})
HttpSession session;
session = req.getSession();
#SuppressWarnings("unchecked")
Vector<Book> shoplist=(Vector<Book>) session.getAttribute("ebookshop.cart");
String do_this=req.getParameter("do_this");
if (do_this==null)
{
Vector<String> blist=new Vector<String>();
blist.addElement("Learn HTML5 and JavaScript for iOS. Scott Preston $39.99");
blist.addElement("Java 7 for Absolute Beginners. Jay Bryant $39.99");
blist.addElement("Beginning Android 4. Livingston $39.99");
blist.addElement("Pro Spatial with SQL Server 2012. Alastair Aitchinson $59.99");
blist.addElement("Beginning Database Design. Clare Churcher $34.99");
session.setAttribute("ebookshop.list", blist);
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/");
rd.forward(req, res);
}
else {
if (do_this.equals("checkout"))
{
float dollars=0;
int books=0;
for (Book abook: shoplist)
{
dollars+=abook.getPrice()*abook.getQuantity();
books+=abook.getQuantity();
}
req.setAttribute("dollars", new Float(dollars).toString());
req.setAttribute("books", new Integer(books).toString());
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/Checkout.jsp");
rd.forward(req, res);
} // end if (do_this.equals("checkout"))
else {
if (do_this.equals("remove")){
String pos=req.getParameter("position");
shoplist.removeElementAt((new Integer(pos)));
}
else if (do_this.equals("add"))
{
boolean found=false;
Book abook=getBook(req);
if (shoplist==null)
{
shoplist=new Vector<Book>();
shoplist.addElement(abook);
}
else
{
for (int i=0;i<shoplist.size() && !found;i++)
{
Book b= (Book) shoplist.elementAt(i);
if (b.getTitle().equals(abook.getTitle()))
{
b.setQuantity(b.getQuantity()+abook.getQuantity());
shoplist.setElementAt(b, i);
found=true;
}
}
if (!found)
{
shoplist.addElement(abook);
}
}
}
session.setAttribute("ebookshop.cart", shoplist);
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/");
rd.forward(req, res);
}
}
}
public Book getBook(HttpServletRequest req){
String myBook=req.getParameter("book");
int n=myBook.indexOf("$");
String name=myBook.substring(0, n);
String price=myBook.substring(n+1);
String qty=req.getParameter("qty");
return new Book(name,Float.parseFloat(price),Integer.parseInt(qty));
}
}
and my index.jsp file
<%--
Document : ebookshop_index
Created on : 22.07.2015, 21:33:24
Author : Ilqar
--%>
<%#page contentType="text/html" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%#page session="true" import="java.util.*,ebookshop.Book" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>E-bookshop</title>
<style type="text/css">
body {background-color: gray; font-size: 10pt;}
h1 {font-size: 20pt}
table {background-color: white;}
</style>
</head>
<body>
<h1>Your online Bookshop!</h1>
<% //Scriplet 1 checks whether the booklist is ready
Vector<ebookshop.Book> booklist=(Vector<ebookshop.Book>)session.getAttribute("ebookshop.list");
if (booklist==null)
{
response.sendRedirect("/ebookshop/eshop");
}
else {
%>
<form name="addForm" method="POST" action="eshop">
<input type="hidden" name="do_this" value="add">
Book:
<select name="book">
<% //Scriplet the booklist to the selection control
for (int i=0;i<booklist.size();i++)
{
out.println("<option>"+booklist.elementAt(i).getTitle()+"</option>");
}
%>
</select>
Quantity: <input type="text" name="qty" value="1" size="3">
<input type="submit" value="Add to Cart">
</form>
<p/>
<% //Scriplet 3 check whether the shopping cart is empty
Vector shoplist=
(Vector<ebookshop.Book>)session.getAttribute("ebookshop.cart");
if ((shoplist!=null) && (shoplist.size()>0)){
%>
<table style="border: 1px; padding: 2px">
<tr>
<td>TITLE</td>
<td>PRICE</td>
<td>QUANTITY</td>
<td></td>
</tr>
<% //Scriplet show the books in shopping cart
for (int i=0;i<shoplist.size();i++)
{
Book aBook=(Book)shoplist.elementAt(i);
%>
<tr>
<form name="removeForm" action="eshop" method="POST">
<input type="hidden" name="position" value="<%=i%>">
<input type="hidden" name="do_this" value="remove">
<td>
<%=aBook.getTitle()%>
</td>
<td style="text-align: right">
<%=aBook.getPrice()%>
</td>
<td style="text-align: right">
<%=aBook.getQuantity()%>
</td>
</form>
</tr>
<%
}
%>
</table>
<p/>
<form name="checkoutForm" action="eshop" method="POST">
<input type="hidden" value="checkout" name="do_this">
<input type="submit" value="Checkout">
</form>
<%
}
}
%>
</body>
</html>
I guess it sends redirect to the servlet when session attribute is null
It worked! I have forgotten to put annotation before the servlett class, that is why it couldn't find the page. Author of the book didn't put, maybe cause it wasn't used that time. I just put
#WebServlet(name = "ShoppingServlet", urlPatterns = {"/eshop"})
and standart web.xml and all worked! I used Tomcat server, and hope it will work for Glassfish also.

Send attribute in Struts 2 Action class

I have a screen which contains dojo sx:div. The action class who manage the loading of the div is different that the principal. but when i click on my link i would like refresh the sx:div with parameter input in the main form. How can I do that ?
JSP File :
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sx" uri="/struts-dojo-tags"%>
<script language="javascript">
function refreshDiv() {
var td = element.parentNode;
document.getElementById('idSubFamily').value = td.getAttribute('id');
dojo.event.topic.publish("/listQuestionTopic", "0", "1");
}
</script>
<table class="board" width="100%">
<tr class="titre">
<td class="titleFamily" width="30%" height="32"><s:property
value="getText('resultat.sous_famille.question.label')" /></td>
<s:if test="%{displayWeight}">
<td class="titleFamily" width="30%" height="32"><s:property
value="getText('question.weight.label')" /></td>
</s:if>
</tr>
<s:if test="%{subFamilyItem.size != 0}">
<s:iterator value="subFamilyItem" status="rowstatus">
<s:if test="#rowstatus.odd == true">
<s:set name="trClass" value="%{'even'}"></s:set>
</s:if>
<s:else>
<s:set name="trClass" value="%{'odd'}"></s:set>
</s:else>
<tr class="<s:property value="#trClass"/>">
<td class="family_<s:property value="#trClass"/>"><s:a
cssClass="board" onclick="refreshDiv()">
<s:property value="%{getText(traductionCode)}" />
</s:a></td>
<s:if test="%{displayWeight}">
<td class="family_<s:property value="#trClass"/>"><s:property
value="%{weight}" /></td>
</s:if>
</tr>
</s:iterator>
</s:if>
</table>
<sx:div id="listQuestions" href="Question.do" formId="idFormQuestion"
listenTopics="/listQuestionTopic" theme="ajax" preload="false">
<s:hidden id="idFamily" name="idFamilySelected"></s:hidden>
</sx:div>
PrinciaplAction class :
package com.omb.controller;
import java.util.ArrayList;
import java.util.List;
import com.omb.ui.SubFamilyItem;
import com.opensymphony.xwork2.ActionSupport;
public class PrincipalAction extends ActionSupport {
private List<SubFamilyItem> subFamilyItem = new ArrayList<SubFamilyItem>();
#Override
public String execute() throws Exception {
subFamilyItem.add(new Item("1", "Family 1"));
subFamilyItem.add(new Item("2", "Family 2"));
return SUCCESS;
}
public List<Item> getSubFamilyItem() {
return this.subFamilyItem;
}
public void setSubFamilyItem(List<Item> subFamilyItem) {
this.subFamilyItem = subFamilyItem;
}
}
DivAction class :
package com.omb.controller;
import com.opensymphony.xwork2.ActionSupport;
public class DivAction extends ActionSupport {
Service myService;
// From the principal screen
Long idFamilySelected;
/**
*
* #see com.opensymphony.xwork2.ActionSupport#execute()
*/
public String execute() {
MyObject object = myService.findObject(idFamilySelected);
return SUCCESS;
}
public String getMyService() {
return this.subFamilySelected;
}
public void setMyService(Service myService) {
this.myService = myService;
}
public String getidFamilySelected() {
return this.idFamilySelected;
}
public void setidFamilySelected(Service idFamilySelected) {
this.idFamilySelected = idFamilySelected;
}
}

Bring jsp form page after previous submit (java spring)

New to spring (and HTML/forms etc for that matter) and been stuck on this problem for long time.
So I want to have a front page where you enter a username. Then click submit, and takes you to a dashboard (ultimately, there will be a page with a list of connected users, a load of submit buttons to send predefined messages out - using qpid jms).
The front page is fine, but I click submit and I get an error (java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'dashboardModel' available as request attribute)
This only happens if I have a form:form in dashboard.jsp. I literally have no idea how to fix this and have tried everything I can find. My code is simple, and is just modified from a tutorial, so here it is:
login.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Login Page:</h2>
<form:form modelAttribute="loginModel" method="POST"
action="/HelloWeb/dashboard">
<table>
<tr>
<td><form:label path="username">Name</form:label></td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Login.java
package com.tutorialspoint;
public class Login {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
LoginController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
return new ModelAndView("login", "loginModel", new Login());
}
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("Login") Login login, ModelMap model) {
model.addAttribute("username", login.getUsername());
return "dashboard";
}
}
dashboard.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>DASHBOARD</title>
</head>
<body>
<table>
<tr>
<td>Dashboard</td>
<td>DASHBOARD</td>
</tr>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>variable</td>
<td>${variable}</td>
</tr>
</table>
<form:form modelAttribute="dashboardModel" method="POST"
action="/HelloWeb/dashboard">
<table>
<tr>
<td><form:label path="variable">Name</form:label></td>
<td><form:input path="variable" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Dashboard.java
package com.tutorialspoint;
public class Dashboard {
private String variable;
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
}
DashboardController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
#Controller
public class DashboardController {
#RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView dashboard() {
return new ModelAndView("dashboard", "dashboardModel", new Dashboard());
}
#RequestMapping(value = "/dashboard", method = RequestMethod.POST)
public String addVariable(#ModelAttribute("SpringWeb") Dashboard dashboard,
ModelMap model) {
model.addAttribute("variable", dashboard.getVariable());
return "dashboard";
}
}
Thanks for your time.
I think the problem is here:
<form:form modelAttribute="loginModel" method="POST" action="/HelloWeb/dashboard">
^^^^^^^^^^
and here:
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("Login") Login login, ModelMap model) {
^^^^^
The modelAttribute value on form:form element and the #ModelAttribute argument should be the same.
I mean:
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("loginModel") Login login, ModelMap model) {
^^^^^^^^^^
Edit:
Also, the form part should be like this:
<form:form modelAttribute="dashboardModel" method="POST" action="/loggedIn.htm">
<table>
<tr>
<td>Name</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>

JSP, "User cannot be resolved to a type"

I am working through Murach's Java Servlets and JSPs
I am in chapter 4, when I load http:// button is pressed I get the error. Can anyone see what is causing the problem, I have all the files stored in tomcat/webapps/MailList. I have gone through this code for hours and cannot find any syntax causing the problem, just thinking another set of eyes would probably catch it. Or someone could explain it, any help is greatly appreciated, this is my first day messing with Servlets/JSPs and tomcat.
The join_email_list.html
<!DOCTYPE html>
<html>
<head>
<title>Chapter 4 - Email List application</title>
</head>
<body background="C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg" >
<h1>Join the Murach's mailing list</h1>
<p>To join the Murach's mailing list, enter your name and email address below.<br>
Then, click n the submit to recieve special offers.</p>
<form action="show_email_entry.jsp" method="get">
<table cellspacing="5">
<tr>
<td align="right" >First name</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td align="right">Last name</td>
<td><input type="text" name="lastName"></td>
</tr>
<tr>
<td align="right">email address</td>
<td><input type="text" name="emailAddress"></td>
</tr>
<tr>
<td></td>
<td><br><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
the show_email_list.jsp
<!DOCTYPE html public"-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Chapter 4 - Email List</title>
</head>
<body>
<%#page import="business.*, data.*" %>
<%
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
User user = new User(firstName, lastName, emailAddress);
UserIO.addRecord(user, "..webapps/MailingList/UserEmail.txt");
%>
<h1>Thanks for joining</h1>
<table cellspacing="5">
<tr>
<td align="right">First Name: </td>
<td><%= user.getFirstName() %></td>
</tr>
<tr>
<td align="right">Last Name: </td>
<td><%= user.getLastName() %></td>
</tr>
<tr>
<td align="right">Email Address: </td>
<td><%= user.getEmailAddress() %></td>
</tr>
</table>
<form action="join_email_list.html" method="post">
<input type="submit" value="Return">
</form>
</body>
</html>
the User.java class
package business;
public class User {
private String firstName;
private String lastName;
private String emailAddress;
//this class defines a user, what we can get from a user to store
public User(){}
public User(String first, String last, String email){
firstName=first;
lastName=last;
emailAddress=email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
the UserIO.java class
package data;
import business.User;
import java.io.*;
public class UserIO { //the user io class adds the entered info to a txt file a.k.a psuedo db
public synchronized static void addRecord(User user, String fileName)
throws IOException{
PrintWriter out = new PrintWriter( //open the printwriter
new FileWriter(fileName, true)); //write to file
out.println(user.getEmailAddress()+"|"//write these things to file
+user.getFirstName()+"|"
+user.getLastName());
out.close();//close out to free resources
}
}
user is not in not accessible in the scope you are trying to, also
C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg
is not going to work
use
UserIO.addRecord(user, "MailingList/UserEmail.txt");
instead of
UserIO.addRecord(user, "..webapps/MailingList/UserEmail.txt");

Categories

Resources