I want to fetch a text box value from jsp to my action class.
But my action class in not getting called while submitting the page.
My code are
Jsp page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="AddedColor" method="post">
<div class="box">
<span class="label">Color Name</span>
<span class="ib"> <input type="text" name="color" id="color"/></span>
</div>
<div class="box">
<input type="button" id="submit_color" value="Add Color"/>
</div>
</form>
</body>
</html>
In struts.xml
<package name="colorpkg" extends="struts-default">
<action name="AddedColor" class="iland.work.ColorAction" method="insert">
<result name="success">/pages/colors/showColors.jsp</result>
</action>
</package>
In ActionClass
public class ColorAction extends ActionSupport {
private String color;
//getter and setter of color
public String insert() {
System.out.println("-> ColorAction insert()");
System.out.println(getColor());
return SUCCESS;
}
}
try this:
<div class="box">
<input type="submit" id="submit_color" value="Add Color"/>
</div>
Related
I'm having a hard time figuring out how to essentially reload a section of my view with new data after a selection from a DropDownMenu(in grails 3.3.9)
I've tried using the same convention of a button in grails, which is pretty straight forward:
<g:select class="btn bg-primary" action="filterByCommittee" controller="management"
from="${Committee.list()}" optionKey="id" optionValue="${name}"
name="committees" value="${committees}" noSelection="${['null':'Select..']}"/>
the code above means(AFAIK) i want to trigger an action(filterByCommittee) which resides in a controller(Management), using params.committees(the name of the field). the mentioned action would filter the purchases(a list shown to the user) by the selected committee.
any help would be greatly appreciated!
some relevant code:
class ManagementController {
PurchaseService purchaseService
CommitteeService committeeService
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
List<Purchase> purchaseList = Purchase.findAllByAccountantApprovalInList(Approval.findAllByApproved(true))
}
respond purchaseList, model:[purchaseCount: purchaseService.count()]
}
def filterByCommittee() {
Committee selectedCommittee = Committee.findByName(params.committees)
List<User> userList = User.findAllByCommittee(selectedCommittee)
List<Purchase> purchaseList = Purchase.findAllByUserInList(userList)
respond purchaseList, model:[purchaseCount: purchaseService.count()]
}
}
class Committee {
String name
static hasMany = [users:User, summaries:Summary]
static constraints = {
users(nullable: true)
summaries(nullable: true)
}
#Override
public String toString() {
return name
}
}
<!DOCTYPE html>
<!--<%# page import="attainrvtwo.Committee" contentType="text/html;charset=UTF-8" %>-->
<html xmlns:g="http://www.w3.org/1999/html">
<body>
<g:message code="default.link.skip.label" default="Skip to content…"/>
<div class="nav" role="navigation">
<ul>
<li><g:select class="btn bg-primary" action="filterByCommittee" controller="management" from="${Committee.list()}" optionKey="id" optionValue="${name}" name="committees" value="${committees}" noSelection="${['null':'Select..']}"/></li>
</ul>
</div>
<div id="list-purchase" class="content scaffold-list" role="main">
<h1><g:message code="default.list.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<f:table collection="${purchaseList}" />
<div class="pagination">
<g:paginate total="${purchaseCount ?: 0}" />
</div>
</div>
</body>
</html>
In gsp file, on select (fill "" with the corresponding values):
<g:select id="" name="" value="" from='${}' optionKey="id"
onchange="optionChanged(this.value);" >
</g:select>
<div id="tabla" style="display:block;"></div>
In same gsp file:
<script>
function optionChanged(committeeId) {
<g:remoteFunction controller="management" action="filterByCommittee"
update="tabla" params="'commId='+committeeId"/>
}
</script>
In another gsp file name="filterByCommittee.gsp":
Code to display
In the controller add the id param to the function:
def filterByCommittee(commId)
the solution i pieced together looks something like this:
in the ManagementController
package attainrvtwo
class ManagementController {
CommitteeService committeeService
List<Purchase> purchaseList
def filterByCommittee() {
session.filterPurchases = true
Committee selectedCommittee = committeeService.get(params.id)
List<User> userList = User.findAllByCommittee(selectedCommittee)
purchaseList = Purchase.findAllByUserInList(userList)
respond purchaseList, model:[purchaseCount: purchaseService.count()]
}
}
in the index.gsp file of management view
<!DOCTYPE html>
<!--<%# page import="attainrvtwo.Committee" contentType="text/html;charset=UTF-8" %>-->
<html xmlns:g="http://www.w3.org/1999/html">
<head>
<meta name="layout" content="main" />
<g:set var="entityName" value="${message(code: 'purchase.label', default: 'Purchase')}" />
<title></title>
</head>
<body>
<g:message code="default.link.skip.label" default="Skip to content…"/>
<div class="nav" role="navigation">
<ul>
<!-- <li><a class="home" href="${createLink(uri: '/volunteer/index')}"><g:message code="default.home.label"/></a></li>-->
<li><g:select class="btn bg-primary" id="commDDLid" name="committeeDDL" action="filterByCommittee" controller="management" from="${Committee.list()}" optionKey="id" optionValue="${name}" value="${committees}" noSelection="${['null':'Select..']}" onchange="goToPage(this.value)"/></li>
</ul>
</div>
<div id="list-purchase" class="content scaffold-list" role="main">
<h1><g:message code="default.list.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<f:table collection="${purchaseList}" />
<div class="pagination">
<g:paginate total="${purchaseCount ?: 0}" />
</div>
</div>
<script type="text/javascript">
function goToPage(requestParams) {
window.location.href="${'/management/filterByCommittee'}" + "/" + requestParams;
}
</script>
</body>
</html>
then i've also added the filterByCommitty.gsp view which is basically a copy of my index.gsp
(notice the import line at the beginning and the script tag at the end)
<!DOCTYPE html>
<!--<%# page import="attainrvtwo.Committee" contentType="text/html;charset=UTF-8" %>-->
<html xmlns:g="http://www.w3.org/1999/html">
<head>
<meta name="layout" content="main" />
<g:set var="entityName" value="${message(code: 'purchase.label', default: 'Purchase')}" />
<title></title>
</head>
<body>
<g:message code="default.link.skip.label" default="Skip to content…"/>
<div class="nav" role="navigation">
<ul>
<li><g:select class="btn bg-primary" id="commDDLid" name="committeeDDL" action="filterByCommittee" controller="management" from="${Committee.list()}" optionKey="id" optionValue="${name}" value="${committees}" noSelection="${['null':'Select..']}" onchange="goToPage(this.value)"/></li>
</ul>
</div>
<div id="list-purchase" class="content scaffold-list" role="main">
<h1><g:message code="default.list.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<f:table collection="${purchaseList}" />
<div class="pagination">
<g:paginate total="${purchaseCount ?: 0}" />
</div>
</div>
<script type="text/javascript">
function goToPage(requestParams) {
window.location.href="${'/management/filterByCommittee'}" + "/" + requestParams;
}
</script>
</body>
</html>
i hope this helps someone.
if there are any improvement suggestions i'd be glad to correct them.
cheers ;)
How obtain value of hotel in Controller ? now i have only null. The nested object are not allowed because of html 5 doesn't let to be nested. I have objects in template but only object knight bring the value and I need also further written controls values. I ve tried to put the object but without formater yet, but I dont think it has meaning now.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Add knight</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" th:href="#{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
<script th:src="#{/webjars/jquery/3.2.1/jquery.min.js}"></script>
<script th:src="#{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
</head>
<body>
<div class="container">
<form class="form-horizontal" th:object="${knight}" th:action="#{/assignQuest}" th:method="post">
<input type="hidden" th:field="*{id}"/>
<input type="hidden" th:field="*{name}"/>
<input type="hidden" th:field="*{age}"/>
<input type="hidden" th:field="*{level}"/>
<div class="form-group">
<label class="control-label">Wykonaj zadanie</label>
<select th:field="*{quest}">
<option th:each="quest : ${notStartedQuests}"
th:value="${quest.id}"
th:text="${quest.description}">?</option>
</select>
</div>
<input type="hidden" th:field="*{name}"/>
<input type="hidden" th:field="*{id}"/>
<ul>
<label class="control-label">Zamiesszkaj w hotelu</label>
<li th:each="hotel : ${hotels}">
<input type="radio" th:field="*{id}" th:value="${hotel.id}" />
<label th:for="${hotel.name}" th:text="${hotel.name}"></label>
</li>
</ul>
<div class="row">
<button type="submit" class="btn btn-default">Wyslij rycerza</button>
</div>
</form>
</div>
</body>
</html>
QuestController:
import java.util.List;
#Controller
public class QuestController {
#Autowired
KnightService knightService;
#Autowired
QuestService questService;
#Autowired
HotelService hotelService;
#RequestMapping("/assignQuest")
public String assignQuest(#RequestParam("knightId") Integer id, Model model) {
Knight knight = knightService.getKnight(id);
List<Quest> notStartedQuests = questService.getAllNotStartedQuests();
List<Hotel> hotels = hotelService.getAllHotels();
model.addAttribute("knight", knight);
model.addAttribute("notStartedQuests", notStartedQuests);
model.addAttribute("hotels", hotels);
return "assignQuest";
}
#RequestMapping(value = "/assignQuest", method = RequestMethod.POST)
public String assignQuest(Knight knight, Hotel hotels, BindingResult result) {
System.out.println(result);
System.out.println(hotels);
knightService.updateKnight(knight);
// Quest quest = knight.getQuest();
// questService.update(quest);
return "redirect:/knights";
}
}
In my aplication I need photo upload. I want that User first creates album folder and after cliking on that album, uploads photos. My album has: ID, album_name, username and my photo:ID, album_ID, photo_name, type
album controller:
import java.io.File
import grails.plugin.springsecurity.annotation.Secured
import java.text.SimpleDateFormat
#Secured(['ROLE_USER','ROLE_ADMIN', 'IS_AUTHENTICATED_FULLY'])
class AlbumController {
def springSecurityService
def index() { }
def create(){
def user = User.get(springSecurityService.currentUser.id)
def album = new Album()
album.a_name = params.name
album.user = user
album.save(failOnError:true)
def photo = new Photo()
def uploadedFile = request.getFile('myFile')
def name = System.currentTimeMillis()
if (uploadedFile.empty) {
flash.message = 'file cannot be empty'
redirect (action:'index')
return
}
photo.type = uploadedFile.contentType
photo.p_name = name
photo.album = album
uploadedFile.transferTo(new File("../test101111/web-app/album/" + user.username + "/"+ photo.getP_name() + ".jpg"))
//response.sendError(200, 'Done')
photo.save(failOnError:true)
redirect (action:'index')
}
}
Photo controller:
import java.io.File
import grails.plugin.springsecurity.annotation.Secured
import java.text.SimpleDateFormat
#Secured(['ROLE_USER','ROLE_ADMIN', 'IS_AUTHENTICATED_FULLY'])
class PhotoController {
def springSecurityService
def index() { }
def create(){
def photo = new Photo()
def uploadedFile = request.getFile('myFile')
def name = System.currentTimeMillis()
if (uploadedFile.empty) {
flash.message = 'file cannot be empty'
redirect (action:'index')
return
}
photo.type = uploadedFile.contentType
photo.p_name = name
photo.album = params.albumId
uploadedFile.transferTo(new File("../test101111/web-app/album/" + photo.getP_name() + ".jpg"))
//response.sendError(200, 'Done')
photo.save(failOnError:true)
redirect (action:'index')
}
}
Photo view:
<%# page contentType="text/html;charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta name="layout" content="main" />
<title>Photo</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("span.button").click(function() {
$("form.forma_album").toggle();
});
});
</script>
</head>
<body>
<div class="body">
<div class="album_title">
<span class="title1">Fotografije</span>
<div class="new_album">
<img class="plus" src="${resource(dir: 'images', file: 'plus.png')}" />
<span class="button">Dodaj novu sliku</span>
</div>
</div>
<hr class="usual">
<g:uploadForm action="create" class="forma_album">
<input type="file" name="myFile" />
<input type="submit" />
</g:uploadForm>
</div>
</body>
</html>
Album view:
<%# page contentType="text/html;charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta name="layout" content="main" />
<title>Album</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("span.button").click(function() {
$("form.forma_album").toggle();
});
});
</script>
</head>
<body>
<div class="body">
<div class="album_title">
<span class="title1">Foto albumi</span>
<div class="new_album">
<img class="plus" src="${resource(dir: 'images', file: 'plus.png')}" />
<span class="button">Kreiraj novi album</span>
</div>
</div>
<hr class="usual">
<g:form action="create" class="forma_album">
<g:textArea class="album_name" name="name" placeholder="Ime albuma"></g:textArea>
<g:submitButton class="submit2" name="Dodaj" />
</g:form>
<g:each in="${albums}" var="album">
<g:link controller="photo" action="index" class="contact"
params="[albumId: album.id]">
${album.a_name}
</g:link>
</g:each>
<%--<g:uploadForm action="create" class="forma_album">
<g:textArea class="album_name" name="name" placeholder="Ime albuma"></g:textArea>
<input type="file" name="myFile" />
<input type="submit" />
</g:uploadForm>
--%>
<div>
<%--<g:each in="${albums}" var="album" class="picture">
<div class="picture">
<img src="${resource(dir: 'images', file: 'picture.png')}" />
<div class="album_name">
${album.a_name}
</div>
</div>
</g:each>
--%>
</div>
</div>
</body>
</html>
My Error is: No signature of method: org.springframework.security.web.servletapi.HttpServlet3RequestFactory$Servlet3SecurityContextHolderAwareRequestWrapper.getFile() is applicable for argument types: (java.lang.String) values: [myFile] Possible solutions: getXML(), getPart(java.lang.String), getAt(java.lang.String), getAt(java.lang.String), getLocale(), getJSON()
What is wrong? sorry for my English and thanks for the answer ;)
You can either set grails.servlet.version = "2.5" in your BuildConfig.groovy or in application.properties
or
use the request.getPart(String) instead of request.getFile(String)
see JavaDoc on Part interface
Could you please print the params and paste them here.
Alternatively you can try with request.getInputStream().
I have an array list in action class. I want to access this arraylist in my jsp page along with a checkbox. if the checkbox is checked i want to get the associated value of checkbox in another actionclass. how can i do this??
Action class:
public class CreateModuleAction extends ActionSupport{
private List modNameList=new ArrayList();
private int size;
public String manageModule()
{
ManageModule ob=new ManageModule();
modNameList=ob.selectModule();
if(modNameList.isEmpty()) {
addActionError("Module list is empty!!!");
return ERROR;
}
else{
setSize(modNameList.size());
return SUCCESS;
}
}
public List getModNameList() {
return modNameList;
}
public void setModNameList(List modNameList) {
this.modNameList = modNameList;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
jsp page:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../css/style.css" rel="stylesheet" type="text/css" />
<title>Admin Module Management</title>
</head>
<body>
<div class="main">
<div class="header">
<!-- Page heading-->
<jsp:include page="/templates/heading.jsp" flush="true"/>
</div>
<div class="menu">
<!-- Page menu-->
<jsp:include page="/templates/menu.jsp" flush="true"/>
</div>
<div class="content">
<!-- page content-->
<div id="right_top" style="position:absolute; left:900px; top:300px;;">
<img src="../images/add.jpg"/>Add
<img src="../images/edit.jpg"/>Edit
<img src="../images/add.jpg"/>Delete
</div>
<s:iterator status="size" value="modNameList">
<s:checkbox name="modNameCheck" fieldValue="true" value="modNameList"/>
<s:property value="modNameList"/>
</s:iterator>
<s:actionerror/>
</div>
<div class="footer" style="margin-left: 50%">
<!-- page footer-->
<jsp:include page="/templates/footer.jsp" flush="true"/>
</div>
</div>
</body>
</html>
Why dont you use struts2 checkboxlist tag
<s:form action="myAction">
<s:checkboxlist list="modNameList" name="modNameCheck"/>
</s:form>
Now in yoyr myAction action class declare
private List modNameCheck; //with getter/setter
It will have entries which were checked in the jsp
If you want submit values from checkboxes to action then you need form in your JSP. If you want to display checked/unchecked checkboxes depending on some values from action then you need some condition check in value attribute.
<s:checkbox name="modNameCheck" value="list.contains(something)"/>
I am trying to build a simple ASP.net MVC application.
My Controller Looks like below.
namespace CustomerReadAndLoad.Controllers
{
public class CustomerController : Controller
{
//
// GET: /Customer/
public ActionResult Index()
{
return View();
}
public ActionResult LoadCustomer()
{
return View();
}
[HttpPost]
public ActionResult DisplayCustomer()
{
Customer obj = new Customer();
obj.ID = Convert.ToInt16(Request.Form["CuatomerID"]);
obj.Name = Convert.ToString(Request.Form["CuatomerName"]);
obj.Amount = Convert.ToInt16(Request.Form["CuatomerAmount"]);
return View(obj);
}
}
}
I trying to Include the action DisplayCustomer in LoadCustomerView like below
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>LoadCustomer</title>
</head>
<body>
<div>
<form action ="DisplayCustomer" method ="post">
Welcome to Customer management System<br />
Enter the below details <br />
Customer ID :- <input type="text" name = "CuatomerID" /><br />
Customer Name :- <input type="text" name = "CuatomerName" /><br />
Customer Amount :- <input type="text" name = "CuatomerAmount" /><br />
<input type ="button" value="ClickHere" />
</form>
</div>
I am unable to move to the view DisplayCustomer once i click Submit Button.
Try this:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>LoadCustomer</title>
</head>
<body>
<div>
<%using(Html.BeginForm("DisplayCustomer", "Customer", FormMethod.Post)){%>
Welcome to Customer management System<br />
Enter the below details <br />
Customer ID :- <input type="text" name = "CuatomerID" /><br />
Customer Name :- <input type="text" name = "CuatomerName" /><br />
Customer Amount :- <input type="text" name = "CuatomerAmount" /><br />
<button type ="submit">"ClickHere"</button>
<%}%>
</div>