Send parameter from Spring MVC controller to jsp code - spring

I'm trying to send the variable average review from controller to view and show a number of stars equal with average review.
The problem is that I don't know how to loop through received variable and java code doesn't recognize that variable. I tried with a foreach from JSTL, but there is no list of objects; I want a classic for loop.
Here is my controller:
#RequestMapping(value = "/viewDetails", method = RequestMethod.GET)
public ModelAndView viewProductDetails(HttpServletRequest request) {
int productID = Integer.parseInt(request.getParameter("id"));
// irrelevant code goes here
double averageReview= reviewDAO.getAverageReview(productID);
modelAndView.addObject("averageReview",averageReview);
return modelAndView;
}
This is my view page, where I tried to loop:
<p>
<c:set var = "averageReview" scope = "session" value ="${averageReview}"/>
<% for(int i=0;i< ${averageReview}; i++){ %>
<span class="glyphicon glyphicon-star"></span>
<% } %>
</p>

How about this?
<c:forEach var = "i" begin = "0" end = "${averageReview}">
<span class="glyphicon glyphicon-star"></span>
</c:forEach>

Related

How to display existing and newly created values in EL in Spring MVC?

Only the last value of the model is displayed as EL, so the existing value is not displayed.
The BoardController code for that.
#RequestMapping("viewPage.do")
public String viewPage(HttpSession session,HttpServletRequest request, HttpServletResponse response,Model model,
#RequestParam(value="board_idx", defaultValue="0") int board_idx) throws IOException,IllegalStateException
{
// View comment list for this post
List<HashMap<String, Object>> commentList= bService.getBoardForComment(boardData.getBoard_idx());
// loop (comment.size)
for(int i = 0; i < commentList.size(); i++)
{
System.out.println("commentList Size : " + commentList.size());
//Saving the board_comm_idx value in the commentList to a variable
int board_comm_idx= (Integer) commentList.get(i).get("board_comm_idx");
//System.out.println("board_comm_idx : " + board_comm_idx);
// View comments in comments (viewed by board_idx, board_comm_idx)
List<HashMap<String, Object>> getCommentOfCommentList =
bService.getBoardCommentOfComment(board_idx, board_comm_idx);
model.addAttribute("cocList", getCommentOfCommentList);
System.out.println("GetCommentOfCommentList : " + getCommentOfCommentList);
System.out.println("cocList (Model) : " + model);
}
model.addAttribute("commentList", commentList); // CommentList Information
return "viewPage";
}
Here is the JSP code.
<c:forEach items="${cocList}" var="cocList">
<div class="commentList" style="margin-left:70px">
<div class="what">
<div class="nickname">
<span>
${cocList.board_c_of_c_writer}
</span>
</div>
<div class="writedatezone" style="margin-left: 715px;">
<span class="era">
<span class="glyphicon glyphicon-time enterReReply"></span>
<span class="commentWriteDate">
<fmt:formatDate value="${cocList.board_c_of_c_writeDate}" pattern="yyy-MM-dd"/>
</span>
</span>
</div>
<c:if test="${cocList.idx == idx}">
<div class="duzone">
<span class="deleteOrUpdateComment">
<a class="updateComment">수정</a>
<a class="deleteComment" onclick="deleteCoc(${cocList.board_idx},${cocList.board_c_of_c_idx})">삭제</a>
<input type="hidden" value="${cocList.board_comm_idx}">
<input type="hidden" value="${cocList.board_c_of_c}">
<input type="hidden" name="board_idx" value="${boardInformation.board_idx}">
</span>
</div>
</c:if>
</div>
<pre>${cocList.board_c_of_c_content}</pre>
</div>
</c:forEach>
First, it is the log of when you first commented on the comment.
GetCommentOfCommentList : [{board_idx=3, board_c_of_c_writer=웹개발자, board_c_of_c_content=Test, board_c_of_c_idx=8, board_comm_idx=5, idx=4, board_c_of_c_writeDate=2017-11-30 10:33:06.0}]
cocList (Model) : {cocList=[{board_idx=3, board_c_of_c_writer=웹개발자, board_c_of_c_content=Test, board_c_of_c_idx=8, board_comm_idx=5, idx=4, board_c_of_c_writeDate=2017-11-30 10:33:06.0}]}
After that, if you make a new comment,
GetCommentOfCommentList : [{board_idx=3, board_c_of_c_writer=웹개발자, board_c_of_c_content=Test, board_c_of_c_idx=8, board_comm_idx=5, idx=4, board_c_of_c_writeDate=2017-11-30 10:33:06.0}]
cocList (Model) : {cocList=[{board_idx=3, board_c_of_c_writer=웹개발자, board_c_of_c_content=Test, board_c_of_c_idx=8, board_comm_idx=5, idx=4, board_c_of_c_writeDate=2017-11-30 10:33:06.0}]}
GetCommentOfCommentList : []
cocList (Model) : {cocList=[]}
As above, when you create a new comment, the comment list will disappear from the existing comment.
The last cocList is an empty string because you have not commented on the comment.
I am convinced that EL is wrong. How do I fix the EL to solve my problem?
Even though you have the
<c:forEach items="${cocList}" var="cocList">
cocList is a reference your list (model attribute), but since you are assigning it to something else var="cocList" you are going to have unintended consequences, you should name your list item to something else.
<c:forEach items="${cocList}" var="item">
You should then be able to reference the item like ${item.blah}
Think of
<c:forEach items="${cocList}" var="cocList">
as
for (Object cocList : cocList) {
...
}
Which obviously is bad, instead you want:
<c:forEach items="${cocList}" var="item">
which is
for (Object item : cocList) {
...
}
I believe that should fix your problem.
For what it is worth as well, most likely, you are not using EL or SpEL, you are using JSTL at the moment. Normally the SpEL tags are going to look like spring:..., c:... normally references JSTL.
I solved this problem.
I added getCommentofCommentList to commentList instead of modifying the query statement.
As follows.
for(int i = 0; i < commentList.size(); i++)
{
System.out.println("commentList Size : " + commentList.size());
// commentList 에 담긴 board_comm_idx 값을 변수에 저장
int board_comm_idx= (Integer) commentList.get(i).get("board_comm_idx");
//System.out.println("board_comm_idx : " + board_comm_idx);
// 댓글에 댓글 조회 (board_idx , board_comm_idx으로 조회)
List<HashMap<String, Object>> getCommentOfCommentList =
bService.getBoardCommentOfComment(board_idx, board_comm_idx);
commentList.get(i).put("cocList", getCommentOfCommentList);
}
I added the following code.
commentList.get(i).put("cocList", getCommentOfCommentList)
as the result, It's very well work.

MVC Pass Paramater from ActionLink to View to return Recordset

I would like to pass a value from a link to a View and display the fields of the single record on the page.
Lets say I have #Html.ActionLink(item.Title, "Article/"+#item.ID, "News") which outputs /News/Article/1, I would need a Controller called NewsController with a /News/Article View.
I already have the following:
NewsController:
namespace WebApplication1.Controllers
{
public class NewsController : Controller
{
private WebApplication1Entities db = new WebApplication1Entities();
public ActionResult Article()
{
var articleModel = (from m in db.News where (m.Id == 1) && (m.Active == true) select m);
return View(articleModel);
}
[ChildActionOnly]
public ActionResult LatestNews()
{
var latestModel = (from m in db.News where (m.Id != 1) && (m.Active == true) select m);
return View(latestModel);
}
}
Not sure if I should use FirstOrDefault() as it can only be one record as the Id is unique, but unsure how to reference item objects inside the View without an IEnumerable list. At present the Id is set to 1 but I would like the recordset to reflect the Id passed.
Not sure what code to put inside the View, Article though, here is what I have so far:
Article.cshtml
#model IEnumerable<WebApplication1.Models.News>
#foreach (var item in Model) {
ViewBag.Title = #item.Title;
<div class="row">
<article class="span9 maxheight">
<section class="block-indent-1 divider-bot-2">
<h2>#item.Title</h2>
#item.Summary
#item.Content
</section>
</article>
<article class="span3 divider-left maxheight">
<section class="block-indent-1">
<h2>Latest News</h2>
#{ Html.RenderAction("LatestNews", "News"); }
</section>
</article>
</div>
}
LatestNews.cshtml
#{ Layout = null; }
#model IEnumerable<Shedtember.Models.News>
<ul class="nav sf-menu clearfix">
#foreach (var item in Model)
{
#Html.MenuLink(item.Title, "Article/"#item.ID, "News")
}
</ul>
This works for Id 1 but this needs to be dynamic.
Any help would be much appreciated :-)
In your RouteConfig class map a route as follows:
routes.MapRoute("Article", "Article/{id}", new {controller = "News", action = "Article"});
then in your Article method you can add and use the id parameter as follows:
public ActionResult Article(int id)
{
var articleModel = (from m in db.News where (m.Id == id) && (m.Active == true) select m);
return View(articleModel);
}

Silverstripe Sessions or URL Parameters

I'm trying to figure out how to pass a value from my .ss page to my controller for a custom search filter that I've built. The idea is you click on this image or a form button and then the page will set a session variable and refresh itself. Upon page load the page loads different information depending on what it reads in the session variable. I can accomplish the same thing with URL Parameters but there are no examples online that I could find that would show me how to do this.
Basically I have this as my php:
class ArticleHolder_Controller extends Page_Controller {
public function ValidateType(){
if(isset($_SESSION['mySearchTag']) && !empty($_SESSION['mySearchTag'])) {
$tag = $_SESSION['mySearchTag'];
}
else{
$tag='News';
}
$filter = $this::get()->filter('Filters:PartialMatch', $tag)->First();
if ($filter == NULL){
return NULL;
}
else{
$_SESSION['mySearchTag']=$tag;
return $this->PaginatedPages();
}
}
public function PaginatedPages(){
$paginatedItems = new PaginatedList($this->filterArticles($_SESSION['mySearchTag']), $this->request);
$paginatedItems->setPageLength(3);
return $paginatedItems;
}
public function filterArticles($tag){
return ArticlePage::get()->filter('category:PartialMatch', $tag)->sort('Date DESC');
}
}
my .ss looks like this:
<% if ValidateType() %>
<ul>
<% loop $PaginatedPages %>
<li>
<div class="article">
<h2>$Title</h2>
<h3>$Date</h3>
<img class="indent" src="$Photo.link" alt="image"/>
<p class="indent">$Teaser</p>
</div>
</li>
<% end_loop %>
</ul>
<% include Pagination %>
<% else %>
<p>SORRY NO RESULTS WERE FOUND</p>
<% end_if %>
This code works as is. What I cannot figure out how to now add a clickable button on .ss page that will reload the page and set a session variable value.
If I can achieve this with url parameters then that can work too, I just need to know how to set them in the .ss page and how to retrieve them in the php.
Create a SetFilter function that will take the URL parameter ID and set it to your session variable:
public function SetFilter() {
if($this->request->param('ID')) {
$_SESSION['mySearchTag'] = $this->request->param('ID');
}
return array();
}
Make sure your SetFilter function is added to the $allowed_actions of your controller:
static $allowed_actions = array (
'SetFilter'
);
This function is called by your page link followed by /SetFilter/[your-filter].
In your template you would create a link to create this filter like so:
Filter articles by example

Best way to pass single value from view to controller

I have a form that posts a single value, but I cant seem to get it to the controller. I have verified the value exists in the form, but it arrives at the controller as null. Here is the form post:
<%Html.BeginForm("SaveRecord", "NewApplicant", FormMethod.Post, new { id = Model.PersonModel.ApplicantID } ); %>
<%: Html.Hidden("NewId", Model.PersonModel.ApplicantID) %>
<input type="submit" class="SKButton" value="Save" title="Save this new application as a unique record." />
<% Html.EndForm(); %>
and here is the contoller action:
public ActionResult SaveRecord(NewApplicantViewModel model)
{
int NewAppId = model.PersonModel.ApplicantID;
I have also tried:
public ActionResult SaveRecord(int NewId)
{
model.PersonModel.ApplicantID = NewId;
These must be a simple fix, and I want to pass the id in the model, dont want to use ajax. Thoughts?
Try using:
<%: Html.HiddenFor(model => model.PersonModel.ApplicantID) %>

How can I get access to a variable in a View which was created in a Controller?

How can I get access to a variable in a View which was created in a Controller?
Either put the variable into the Model that you are using for your View
Or use a ViewBag variable - e.g. from http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx
public ActionResult Index()
{
List<string> colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
ViewBag.ListColors = colors; //colors is List
ViewBag.DateNow = DateTime.Now;
ViewBag.Name = "Hajan";
ViewBag.Age = 25;
return View();
}
and
<p>
My name is
<b><%: ViewBag.Name %></b>,
<b><%: ViewBag.Age %></b> years old.
<br />
I like the following colors:
</p>
<ul id="colors">
<% foreach (var color in ViewBag.ListColors) { %>
<li>
<font color="<%: color %>"><%: color %></font>
</li>
<% } %>
although hopefully you'll be using Razor :)
You need to send the variable to the view in the ViewModel (the parameter to the View() method) or the TempData dictionary.
You can add it to the ViewData[] dictionary or the (newer) ViewBag dynamic.
In your controller:
ViewData['YourVariable'] = yourVariable;
// or
ViewBag.YourVariable = yourVariable;
In your view:
<%: ViewData["yourVariable"] %>
// or
<%: ViewBag.YourVariable %>

Resources