I am new to Spring MVC I have setup a test DB to try to get a single flow through and have a table displayed in a JSP page. I assume I have something configured wrong but I cannot find it. Maybe a naming convention.
I have a mySql DB
A DAO Class that just does a select * from my table that works as I can step into it.
My controller just gets a list of my Run Models. No errors are thrown The JSP simple loads an empty table. The controller seems to have the correct info in it.
Model (snippet all the getters and setters seem to work as the controller gets a list of them fine)
public class QAModel {
private int idRun;
private String SuiteID;
private String run_name;
Controller Code
#RequestMapping(value="/RunList")
public ModelAndView listRun(ModelAndView model) throws IOException{
//#ModelAttribute
System.out.println("**** Controller ******");
List<QAModel> listRun = runDao.list();
model.addObject("RunList", listRun);
model.setViewName("RunList");
return model;
}
That does get a list of Run Model Objects that contain the correct DB info I can see them if I step into it. However the JSP loads a blank table.
JSP Code (I assume I'm missing some mapping or naming convention?)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Contact Manager Home</title>
</head>
<body>
<div align="center">
<h1>Contact List</h1>
<h3>New Run</h3>
<table border="1">
<th>No</th>
<th>Suite ID</th>
<th>Run Name</th>
<c:forEach var="QAModel" items="${RunList}" varStatus="status">
<tr>
<td>${status.index + 1}</td>
<td>${QAModel.SuiteID}</td>
<td>${QAModel.run_name}</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
If you are not able to print any jstl variable then one possible reason can be that your jstl core tag is not added.
Add this to begining of your JSP file.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Related
This question already has answers here:
"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat
(8 answers)
Closed 2 years ago.
I am trying to create a simple application in which a user can add an image. The name of the image and the path of the folder where I am storing the image but when trying to retrieve it. It shows "Not allowed to load local resource: file:///H:/Projectpictures/BrowserForDataTables.PNG" Error on browser console. please have a look and let me know what is it I am doing wrong here.
Here is my code.
This is the DAOImplementation code for retrive:
#Override
#Transactional
public List<pictureModal> allImages() {
Session currentSession = sessionFactory.getCurrentSession();
Query<pictureModal> query = currentSession.createQuery("from pictureModal");
List<pictureModal> pictues= query.getResultList();
return pictures;
}
This is Controller code for getimages:
#RequestMapping("/seeAllImages")
public String getAllImage(Model theModal) {
List<pictureModal> myPictures= pictureServ.allImages();
theModal.addAttribute("myPicture",myPictures);
return "ImagePage";
}
And here is the code for JSP file:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Pictures will display here</title>
</head>
<body>
<h2>Display Pictures </h2>
<table border="1">
<thead>
<tr>
<th>Picture Name</th>
<th>Picture</th>
</tr>
</thead>
<c:forEach var="tempPic" items="${myPicture}">
<tbody>
<tr>
<td>${tempPic.name}</td>
<td><img src="${tempPic.path}"></td>
</tr>
</tbody>
</c:forEach>
</table>
</body>
</html>
Maybe your program tries to access a location where does not have the correct rights. Maybe that is an administrator folder, and your program isn't started as an Administrator.
This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 7 years ago.
I have a facultylist.jsp page which displays List<Faculty> as a request attribute parameter in forEach loop and I want every item in this loop to be a link to specified faculty facultyview.jsp. How can I achieve that ?
facultylist.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculties</title>
</head>
<body>
<h1>Faculties list</h1>
<ul>
<c:forEach var="faculty" items="${faculties}">
<li>${faculty.name}</li>
</c:forEach>
</ul>
</body>
</html>
facultyview.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculty</title>
</head>
<body>
<h1>${faculty.name}</h1>
<ul>
<li>Faculty name: <c:out value="${requestScope.name}"></c:out></li>
<li>Total seats: <c:out value="${requestScope.total_seats}"></c:out></li>
<li>Budget seats: <c:out value="${requestScope.budget_seats}"></c:out></li>
</ul>
apply for this faculty
</body>
</html>
I don't know if its may help, but I'm using following technologies: tomcat, jsp, servlets and log4j.In my project I have one FrontController, which is a servlet that interacts with Command pattern - each Command returns a path to resource and action type: forward or redirect.
You can solve your issue by adding a query params to the link, edit with respect to the comment. Note that you cannot access directly the JSP pages that reside under WEB-INF folder. Also, to encode properly the paramters, better construct url like
<c:url value="facultyview.jsp" var="url">
<c:param name="name" value="${faculty.name}"/>
<c:param name="total_seats" value="${faculty.total_seats}"/>
<c:param name="budget_seats" value="${faculty.budget_seats}"/>
</c:url>
<li>${faculty.name}</li>
and than than in your facultyview.jsp read from the query params
<li>Faculty name: ${param.name}</li>
<li>Total seats: ${param.total_seats}</li>
<li>Budget seats:${param.budget_seats}</li>
This direct JSP communication should solve your immediate issue, but a truly proper way would be to pass an id of a faculty to servlet, fetch the faculty instance, place in the model and pass to the view.
in other way is just take the selected value from the drop down with a name and forward it to front controller servlet ,there use if else conditions and depends on the value you could forward the request to corresponding jsp or servlet
<select name="value"> in jsp
String value=req.getParameter("value"); in servlet
if()
else if()
If you have a field in Faculty entity simply:
${faculty.name}
#Mark: faculty represents an entity from database, i'm not sure if I want to change it adding another field, or you mean some other way ?
Add a field does not means you must change database, you can have a Helper entity that inherits from Faculty and have more fields you can need,
public class FacultyFormHelper extends Faculty implements Serializable {
private String URL;
and in your view:
${facultyHelper.name}
But, If you don't want to modify your database, either create a helper class, you may add onclick event to the <a>
<a onclick="goToURL(${faculty.id})">
Then retrieve the data... i'm not sure how you get the urls... from a variable in the view, ajax call or wherever you have this URL...
Learning spring + jsp.
I am setting a model attribute in a method in a controller
#RequestMapping("/viewExpenses")
public String viewAllExpenses(Model model){
List<Expense> expenses;
expenses = expenseService.getAllExpenses();
model.addAttribute(expenses);
for(Expense e : expenses)
System.out.println(e);
return "viewExpenses";
}
where expenses size is > 1
Following is my jsp page:
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home Page</title>
</head>
<body>
<h2>
Hello ${user.firstName} <br> HOME
</h2>
<div>All Expenses</div>
<span style=""></span>
<c:forEach var="expense" items="${expenses}">
<c:out value="${expense.expenseId}"></c:out>
<c:out value="${expense.expenseName}"></c:out>
<c:out value="${expense.expenseType}"></c:out>
<c:out value="${expense.expensePrice}"></c:out>
<c:out value="${expense.purchaseDate}"></c:out>
<c:out value="${expense.expenseComments}"></c:out>
</c:forEach>
</body>
</html>
Following is my output from the jsp(no errors):
Hello Pravat
HOME
All Expenses
I wonder why the expenses are not populated in my jsp
You need to give your attribute an attribute name:
model.addAttribute("expenses", expenses);
Background:
When a name is not supplied, Spring uses a generated name which is not the same as the variable name. The docs explain this:
Determine the conventional variable name for the supplied Object based on its concrete type. The convention used is to return the uncapitalized short name of the Class, according to JavaBeans property naming rules: So, com.myapp.Product becomes product; com.myapp.MyProduct becomes myProduct; com.myapp.UKProduct becomes UKProduct.
Give it a name
model.addAttribute("expenses", expenses);
Return ModelAndView.
Always enclose body of if/for/etc into { } even it's single-lined.
I'm writing a wizard for creating a user in my application with Spring MVC. At each step the controller will set session attributes for the completed wizard fields.
I want the wizard to look the same regardless of which page it's on, except for each page's fields, obviously. For example, menus and links at the top of the page and buttons at the bottom should remain the same.
I have the following JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# 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=ISO-8859-1">
<title>Create a new User</title>
</head>
<body>
<h1>User Creation Wizard</h1>
Step <c:out value = "${pageNum}"/>/<c:out value = "${pageMax}"/>
<form action="" method="POST">
<jsp:include page="userform${pageView}.jsp"/>
<input name = "currentPage" type = "hidden" value = "${pageNum}"/>
<c:if test = "${pageNum > 1}">
<input name = "prev" type = "submit" value = "Previous" />
</c:if>
<c:if test = "${pageNum < pageMax}">
<input name = "next" type = "submit" value = "Next" />
</c:if>
<c:if test = "${pageNum == pageMax}">
<input name = "submit" type = "submit" value = "Finish" />
</c:if>
</form>
</body>
</html>
In the jsp I'm including, do I need to remove the <html>, <head>, and <body> tags? The above code is based on this example.
Yes, you'd need to remove the <html>, <head> and <body> tags from the included JSP file. As they'd already be present in the including file keeping them would result in invalid HTML.
Only the content that you want to vary would be in the JSP file you're including. Everything else, including the necessary <html>, <head> and <body> tags, would be in the JSP file that does the including.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I've written the below JSP. Now I want to make it into a MVC pattern, could you please help me how to do it?
<%#page import="java.util.Date"%>
<%#include file="DBCon.jsp" %>
<%# 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>
<script language="javascript">
function UnBloc1(test){
var temp3id= 'temp3' + test;
var temp4id= 'temp4' + test;
//alert(temp3id);
document.getElementById(temp3id).style.display='block';
document.getElementById(temp4id).style.display='block';
}
function invoke(but1)
{
//var x=document.getElementById("temp3"+but).value;
//alert(x);
document.abc.action="Up_Query_DB.jsp?val1="+but1;
document.abc.submit();
}
function invoke1(but)
{
document.abc.action="Users_2.jsp?val="+but;
document.abc.submit();
//var t=document.getElementById("ab")+z;
//alert(t);
}
</script>
</head>
<body>
<form name="abc" method="post" action=""><table>
<%
try
{
String s=(String)session.getAttribute("muusername");
int i=0;
int temp=0, temp1=0,temp2=0, temp3=0, temp4=0;
ps=con.prepareStatement("Select DBID,Query_Raised,TR from Scope2 where TR!='null' AND (Query_Answered is null OR Count1 is null) And Specialist='"+s+"'");
rs=ps.executeQuery();
out.println("<b>QueryRaised</b>");
while(rs.next())
{
i++;
%>
<tr>
<td><input type="text" value="<%=i%>" name="id1" id="id1"></td>
<td><center><input type="text" value="<%=rs.getString("DBID")%>" readonly id="abc<%=i%>" name="abc<%=i%>" size="100"></center></td>
<td><input type="Submit" value="Resume" name="temp1<%=i%>" id="temp1<%=i%>" onclick="invoke1(<%=i%>)"></td>
<td><input type="button" value="Update Answer" name="temp2<%=i%>" id="temp2<%=i%>" onClick="UnBloc1(<%=i%>)"></td>
<td><input type="text" name="temp3<%=i%>" id="temp3<%=i%>" style="display: none"/></td>
<td><input type="Submit" value="Submit Answer" name="temp4<%=i%>" id="temp4<%=i%>" style="display: none" onClick="invoke(<%=i%>)"/> </td>
</tr>
<% }
}
catch(Exception e)
{
out.println(e);
}
%>
</table>
</form>
</body>
</html>
Let's say you go to the database and get a list of objects that contain few attributes (with setter and getter methods), among them, the dbid attribute. The object would be your model. Let's call it myBean.
The Java class from you will do the query will be the Controller class. Let's call it myController. So, the controller should: 1. Get the list of objects you need. 2. Do anything that should be done before representing the information (in your case, I would say nothing) and 3. pass the information to the JSP through the list of your beans setting the information in the request so the information can be displayed.
Your JSP, now, should look like this:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# 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>
<script language="javascript">
...
</script>
</head>
<body>
<form name="abc" method="post" action="">
<table>
<c:forEach var="myItem" items="${listDbid}" varStatus="i">
<tr>
<td><input type="text" value="${i.count}" name="id1" id="id1"></td>
<td><center><input type="text" value="${myItem.getDbid}" readonly id="abc${i.count}" name="abc${i.count}" size="100"></center></td>
<td><input type="Submit" value="Resume" name="temp1${i.count}" id="temp1${i.count}" onclick="invoke1(${i.count})"></td>
<td><input type="button" value="Update Answer" name="temp2${i.count}" id="temp2${i.count}" onClick="UnBloc1(${i.count})"></td>
<td><input type="text" name="temp3${i.count}" id="temp3${i.count}" style="display: none"/></td>
<td><input type="Submit" value="Submit Answer" name="temp4${i.count}" id="temp4${i.count}" style="display: none" onClick="invoke(${i.count})"/> </td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
So, basically, you need to remove from your JSP all the code that is not "view", take it to a "controller" and use a "model" for sending the information from the "controller" to the "view".
Also
You should avoid scriptles (<% %>) in your JSP, better to use JSTL and others similar tools. If you do it, probably your JSP will not have "controller" code.
I recommend you to use a MVC framework, like Spring MVC or Struts, among others.
It is also nice if you create another layer in your code just for database access. This database layer will be used by the controllers so the controllers. You can reuse code, make controllers independent of database and keep them clearer.
I am new too MVC as well, but I can suggest you some tips. Make a bean. Beans are Java class with getter and setter. In your case the bean would be
public class Scope2
{
String dbID;
//all other attributes of the table.Beans should be reusable so usually there is only one bean for one corresponding table
public String getDBID()
{
return dbID;
}
public void setDBID(String dbId)
{
this.dbId=dbId;
}
//Other getters and setters for all other attributes
}
Now make a class that would perform database query. And return bean Scope2 from that class to jsp. And in your jsp you will simply print the values as out.println(bean.getDBID());