I want to make the filtering using radio button event. And I've searched about calling java method into html, and found this link. And try to implement it.
HTML file
<form action="${pageContext.request.contextPath}/servlet" method="post">
<input type="radio" value="1" name="radioFilter1"/> <br/>
<input type="radio" value="2" name="radioFilter2"/> <br/>
<input type="radio" value="3" name="radioFilter3"/> <br/>
</form>
SomeClass.java
public class SomeClass{
public String value;
public String filter1() {
return value= "1";
}
public String filter2() {
return value= "2";
}
public String filter3() {
return value= "3";
}
}
Controller.java
#RequestMapping("/servlet")
public String filterServlet(HttpServletRequest request, HttpServletResponse response) throws Exception {
SomeClass s = new FilterSorting();
if (request.getParameter("radioFilter1") != null) {
s.value= s.filter1();
} else if (request.getParameter("radioFilter2") != null) {
s.value= s.filter2();
} else if (request.getParameter("radioFilter3") != null) {
s.value= s.filter3();
}
return "/newhtml.html";
}
#RequestMapping("/newhtml.html")
public String newhtml(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
FilterSorting s = new FilterSorting();
list = Common.getList(dbSessionId, s.value);
model.addAttribute("asnlist", asnList);
return "/newhtml.html";
}
I'm using Spring framework version 4.0.0. And also I already tried using servlet, but it seems didn't work.
What I want is, when I click radioFilter2 then it will call filter2() which is set the parameter value is 2, and so on. And then the value will use as parameter to load content. But from what I've tried, it didn't work. Please help me, thanks!
Related
<div>
<InputeFile class="form-control" #onchange="SelectBanner"></InputFile>
</div>
I want to get full path of file from input in blazor page
but I have this error:
cannot convert from 'method group' to 'EventCallback' in blazor
and this is my method that should get full path of selected file:
#code {
protected string banner;
protected async Task SelectBanner(InputFileChangeEventArgs e)
{
banner = e.File.Name;
}
}
how can I fix this error?
You are using wrong Event callback, it should be
OnChange
instead of
#onchange
so your code should look like this
<div>
<InputFile class="form-control" OnChange="#(async e=>await SelectBanner(e))"></InputFile>
</div>
#code {
protected string banner;
protected async Task SelectBanner(InputFileChangeEventArgs e)
{
banner = e.File.Name;
}
}
The problem is if the check box is not checked request can not find the correct mapping function in springMVC controller.Because it seems like it only send true values if it is checked,but it does not send false value if it not checked.
<form action="editCustomer" method="post">
<input type="checkbox" name="checkboxName"/>
</form>
#RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(#RequestParam("checkboxName")String[] checkboxValue)
{
if(checkboxValue[0])
{
System.out.println("checkbox is checked");
}
else
{
System.out.println("checkbox is not checked");
}
}
I solved a similar problem specifying required = false in #RequestMapping.
In this way the parameter checkboxValue will be set to null if the checkbox is not checked in the form or to "on" if checked.
#RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(#RequestParam(value = "checkboxName", required = false) String checkboxValue) {
if (checkboxValue != null) {
System.out.println("checkbox is checked");
} else {
System.out.println("checkbox is not checked");
}
}
Hope this could help somebody :)
I had the same problem and I finally found a simple solution.
Just add a default value to false and it will work out perfectly.
Html code :
<form action="path" method="post">
<input type="checkbox" name="checkbox"/>
</form>
Java code :
#RequestMapping(
path = "/path",
method = RequestMethod.POST
)
public String addDevice(#RequestParam(defaultValue = "false") boolean checkbox) {
if (checkbox) {
// do something if checkbox is checked
}
return "view";
}
I had to add hidden input with same name of the checkbox. Value must be "checked".Then I can check the length of the string array within controller or in my service class.
<form action="editCustomer" method="post">
<input type="hidden" name="checkboxName" value="checked">
<input type="checkbox" name="checkboxName"/>
</form>
#RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(#RequestParam("checkboxName")String[] checkboxValue)
{
if(checkboxValue.length==2)
{
System.out.println("checkbox is checked");
}
else
{
System.out.println("checkbox is not checked");
}
}
I think the proper answers are Paolo's and Phoste's ones.
ITOH, if you have many checkboxes/params/lasrge forms you can use a Map<T,T> RequestParam, so if the property does not exists - Map.get() return null - the checkbox is not checked.
#RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(#RequestParam Map<String,String> params)
{
String checkboxValue = map.get("checkboxName");
if(checkboxValue != null)
{
System.out.println("checkbox is checked");
return;
}
System.out.println("checkbox is not checked");
}
I'm attempting to make a simple page that will compare multiple form submissions.
I have a html page with a form, and a for-loop that generates a div for each item in a list of form submissions. The list is passed from the controller. I am trying to maintain the list in the controller rather than rely on a database.
When I try to resubmit the form, which should add another object to the list, the list re initializes.
In debugging, I see that the list is empty when the form gets submitted. I'm unsure as to the correct terminology, but it seems that the list is emptied whenever the view is rendered. Is there a way to maintain list contents?
I know there are better ways to do this, and welcome any advice. I'm still learning, so pleas go easy.
Thanks!
This is the simplified controller.
namespace MvcApplication2.Controllers
{
public class HomeController : Controller
{
List<paymentPlan> plansList = new List<paymentPlan>();
public ActionResult Index()
{
return View(plansList);
}
[HttpPost]
public ActionResult Index(FormCollection collection)
{
paymentPlan Project = new paymentPlan();
Project.customerName = Convert.ToString(collection["customerName"]);
plansList.Add(Project);
return View(plansList);
}
}
}
This is my simplified view.
#model List<MvcApplication2.Models.paymentPlan>
#using (Html.BeginForm("index", "home", FormMethod.Post, new { Id = "signupForm" }))
{
<label for="customerName">Customer Name:</label>
<input type="text" name="customerName" class="form-control required" />
#Html.ValidationSummary(true)
<input type="submit" value="Calculate" class="btn btn-primary" />
}
#{
bool isEmpty = !Model.Any();
if (!isEmpty)
{
foreach (var i in Model)
{
<div>
Name: #i.customerName
</div>
}
}
}
This is my simplified model.
namespace MvcApplication2.Models
{
public class paymentPlan
{
public string customerName { get; set; }
}
}
I think that's a question of controller and asp.Net MVC lifecycle !
A controller lifetime is the same as the request, for each request a new controller is created and once the work is done it's disposed!
So try to remove this List<paymentPlan> plansList = new List<paymentPlan>(); and work with TempData[] or ViewData[] or Session[] like this :
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
Session["plansList"] = ((List<paymentPlan>)Session["plansList"])!=null? (List<paymentPlan>)Session["plansList"] : new List<paymentPlan>();
return View((List<paymentPlan>)Session["plansList"]);
}
[HttpPost]
public ActionResult Index(FormCollection collection)
{
paymentPlan Project = new paymentPlan();
Project.customerName = Convert.ToString(collection["customerName"]);
((List<paymentPlan>)Session["plansList"]).Add(Project);
return View(plansList);
}
}
check this : http://www.asp.net/mvc/overview/getting-started/lifecycle-of-an-aspnet-mvc-5-application
I get this error and i dont know how to over come it:
"Object reference not set to an instance of an object."
Line 48: public ActionResult Upload(imageFile imageFile)
Line 49: {
Line 50: foreach (var image in imageFile.files)
Line 51: {
Line 52: if (image.ContentLength > 0)
I tried using ID attribute and name attribute and what not...
This is the problematic section in my controller :
[HttpPost]
public ActionResult Upload(imageFile imageFile)
{
foreach (var image in imageFile.files)
{
if (image.ContentLength > 0)
{
CloudBlobContainer blobContainer = _blobStorageService.GetCloudBlobContainer();
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(image.FileName);
blob.UploadFromStream(image.InputStream);
}
}
return RedirectToAction("Upload");
}
This is the HTML.Form :
<p>
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="imageFile" id="imageFile" multiple />
<input type="submit" name="submit" value="Upload" />
}
</p>
And this is the "imageFile" class :
public class imageFile
{
public IEnumerable<HttpPostedFileBase> files { get; set; }
}
What i'm doing wrong ? i read a lot of posts about this exception but none of them helped me..
Thank you.
Just change the name of your html input to be files, as in your model class:
Your input element in the view:
<input type="file" name="files" id="files" multiple />
Your model:
public class imageFile
{
public IEnumerable<HttpPostedFileBase> files { get; set; }
}
Reference: HTML forms, php and apostrophes
I've been trying to pass data from my HTML form to my servlet for processing. However, I noticed that I'd lose the apostrophes in the text inputs. I'm not sure if this is a client or server side processing error, but looking through the reference above, i think i need to do some processing on the servlet side? Tried looking for a servlet alternative to the above but couldn't find any.
Here's the code snippets:
Html form:
<form method="post" action="CreateThreadServlet">
<b>Title</b><br>
<input type="text" name="title" size="60%" placeholder="Enter your title here"/><br>
<br><b>Tags</b><br>
<input type="text" name="tags" placeholder="Additional Tags: comma separated, e.g. Gamification, Java" size="60%" /><br>
<br><b>Details</b><br>
<textarea name="content" style="width:100%;height:50%"></textarea>
<input type="hidden" name="nick" value=<%=nick%>>
<input type="hidden" name="userid" value=<%=userid%>>
<button type="button" style='float: right;' onClick="closeDimmer()">Cancel</button>
<input type="submit" name="Submit" value="Submit" text-align='center' style='float: right;'>
</form>
This is the servlet code that processes the form:
String userid = req.getParameter("userid");
String nick = req.getParameter("nick");
String title = null; //tried using the URLDecoder, doesn't work
try {
title = URLDecoder.decode(req.getParameter("title"), "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(CreateThreadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
String tags = req.getParameter("tags");
String[] tagStr = tags.split(",");
String[] addTags = req.getParameterValues("addTags");
PLEASE HELP THE NEWBIE.
As this link explains you could simply config a filter
<filter>
<filter-name>HitCounterFilter </filter-name>
<filter-class>
net.my.filters.HitCounterFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>HitCounterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
having this:
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig)
throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
chain.doFilter(request, wrapper);
}
}
so you force an UTF-8 encoding.