Is it possible to get the model, that current view has used for rendering, in the onSubmit() method?
I somehow want to "redirect the model" that was given to the current view from another controller by return
new ModelAndView("searchResults", "model", myModel)
You can make a form reference any attribute and submit to any servlet/controller using something like :
Incldue tags
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
create url var
<c:url var="myURL" value="/ANywhere/whatever" />
define form something like
<form:form name="myForm" id="myForm" action="${myUrl}" method="POST" modelAttribute="yourAttribue">
<form:input path="firstname" />
Related
i am creating a quiz application where i want to group options in a radio button list after fetching options from database. My code is below so that one option from optionList of Question object is selected seprately.
i want to list group of questions and their options in a single page options with their relative questions .if i select option of one question i should be able to select another option of another question. how do i seprate radio buttons for each questions???
#Controller
public class ApiController {
#Autowired
private QuestionRepository qr;
#Autowired
private OptionRepository or;
#Autowired
private ActivitiesCrudRepository acr;
#RequestMapping("/questions")
public String ShowQuestions(#ModelAttribute("questions") Question question) {
return "questions";
}
#RequestMapping("/save")
public String save(#ModelAttribute("questions") Question question) {
qr.save(question);
return "questions";
}
#RequestMapping("/pq")
public String playQuiz(Model m, #ModelAttribute("questions") Question qsn) {
Iterable<Question> q = qr.findAll();
System.out.println(q);
m.addAttribute("q", q);
return "play-quiz";
}
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page isELIgnored="false"%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form:form action="play" modelAttribute="questions">
<c:forEach var="temp" items="${q}">
${temp.qsn_Name}<br>
<c:forEach var="temp1" items="${temp.options}">
<form:radiobuttons path="options[0].name" value="${temp1.name}"
items="${????????????}" />
<br>
</c:forEach>
<br>
</c:forEach>
<input type="submit" value="submit">
</form:form>
</body>
</html>
When using using the taglib function form:radiobuttons you don't need to iterate over the options you want in the radiobutton group.
You can replace
<c:forEach var="temp1" items="${temp.options}">
<form:radiobuttons path="options[0].name" value="${temp1.name}"
items="${????????????}" />
<br>
</c:forEach>
with
<form:radiobuttons path="options[0].name" items="${temp.options}" />
Be aware of the difference between form:radiobutton which create one single button and form:radiobuttons which creates the whole group.
See f.x. https://www.tutorialspoint.com/springmvc/springmvc_radiobuttons.htm or https://mkyong.com/spring-mvc/spring-mvc-radiobutton-and-radiobuttons-example/for more examples.
I am new to Ui design and I am trying to write simple application using JSP and spring boot.
The idea is to get the Google QR code URL in the controller and return to JSP page:
https://chart.googleapis.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=otpauth%3A%2F%2Ftotp%2FSpringRegistration%3Atest_user%3Fsecret%3DI2S5OTJXDG5NBWVY%26issuer%3DSpringRegistration
So, my controller looks like as below:
#GetMapping("/confirmRegistration")
public String confirmRegistration(final HttpServletRequest request,
final Model model) {
final User user = userService.getUser(token);
String qrUrl = userService.generateQRUrl(user);
log.info("QR URL: {}", qrUrl);
model.addAttribute("qr_code", qrUrl);
return "redirect:/qrcode";
}
My JSP looks like -
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
<title>Confirm your account</title>
</head>
<body>
<label>Scan following QR code.</label>
<c:if test="${param.url != null}">
<span> hi there </span>
${param.url}
</c:if>
<c:url value="${qr_code}" />
<img src="${qr_code}" width=256 height=256 />
<br />
<img src="${param.qr[0]}"/>
</body>
</html>
But it is not populating the image. UI page looks like below:
Can someone please help me here?
I think, the issue is related to return statement. You should point a name of your jsp page that the model with image url is forwarded to. But before, you need to define and configure InternalResourceViewResolver
For more info (redirecting / forwarding)
THis is my first 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="newjstl.jsp" method="post">
FirstName:<input type="text" name="fname"/><br/>
LastName:<input type="text" name="lname"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
The second page is
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach var='value' items='${paramValues}'>
First Name:<c:out value="${value.fname}"></c:out><br/>
Last Name:<c:out value="${value.lname}"></c:out>
</c:forEach>
It is throwing an exception org.apache.jasper.JasperException: javax.el.PropertyNotFoundException: The class 'java.util.HashMap$Entry' does not have the property 'fname'.
I don't know why it is not working.
See http://docs.oracle.com/javaee/1.4/tutorial/doc/JSPIntro7.html#wp71044.
paramValues is the map of parameters. It maps parameter names (the keys of the map) to their values (array of String).
You're iterating over this map. The forEach loop thus iterates over the entries of the map, which are of type Map.Entry<String, String[]>. And Map.Entry doesn't have any getFname() method.
What you actually want is
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
First Name:<c:out value="${param.fname}" /><br/>
Last Name:<c:out value="${param.lname}" />
There's no reason to loop, and you simply want to get the single value of a given parameter. That'w what param is for.
JB Nizet has it correctly.
Assume that 'fname' was set to "George", and 'lname' was set to "Smith" in 'first page'.
'paramValues' is a HashMap, so when you use it in 'forEach', what you're getting in 'value' is a Map.Entry, and Map.Entry doesn't have a 'fname' field, so there's no 'getFname' method for JSP to call.
If you insist, 'value' can be used as '${value.key}' and '${value.value}', but that will get you the pairs :
'fname', "George"
'lname', "Smith"
respectively. I doubt that's what you want. The only reason to use a 'forEach' would be if you were expecting multiple answers and needed to iterate through all of them. That's not what's been given as the example.
The following was copied from Implicit Objects, and shows pretty much what I suggest above.
<%-- For every String[] item of paramValues... --%>
<c:forEach var='parameter' items='${paramValues}'>
<ul>
<%-- Show the key, which is the request parameter
name --%>
<li><b><c:out value='${parameter.key}'/></b>:</li>
<%-- Iterate over the values -- a String[] --
associated with this request parameter --%>
<c:forEach var='value' items='${parameter.value}'>
<%-- Show the String value --%>
<c:out value='${value}'/>
</c:forEach>
</ul>
</c:forEach>
To pass parameters to a jsp jstl:
/* JSP PARENT */
<jsp:include page="../../templates/options.jsp">
<jsp:param name="action" value="${myValue}"/>
</jsp:include>
/* JSP CHILD (options.jsp)*/
<div id="optionButtons left">
<span>${param.action}</span>
</div>
Because the fields in your form aren't named the same, you can't use 'forEach' tag. I think this will work!
First Name:${param.fname}
Last Name:${param.lname}
I'm trying to implement optiontransferselect using ajax. I can not move the values from left side to right side.I've added <%# taglib uri="/struts-dojo-tags" prefix="sx"%> tags in my code and I've included <sx:head/> also, but it doesn't work. please help me out to solve the issue.
my.jsp
<%#taglib uri="/struts-tags" prefix="s" %>
<%# taglib uri="/struts-dojo-tags" prefix="sx"%>
<head>
<sx:head/>
</head>
<div class="width2 margin-bottom margin-top">
<div class="profile-text">
Preferred Location
</div>
<s:optiontransferselect
id="city"
name="cityNo"
list="cityList"
listKey="id"
listValue="cityName"
headerKey="0"
headerValue="City"
onfocus="getcitywithCountry(false);"
doubleList="prefererList"
doubleId="city"
doubleListKey="cityId.id"
doubleListValue="cityId.cityName"
doubleHeaderKey="0"
doubleHeaderValue="--selected locations--"
doubleName="selectedLocations" allowUpDownOnLeft="false" allowUpDownOnRight="false"/>
</div>
I don't see much wrong with your code. You need to remove <%# taglib uri="/struts-dojo-tags" prefix="sx"%> reference. Replace <sx:head/> with <s:head/>.
What is the best-practice for developing web-pages for both non-JS-enabled and JS-enabled pages? I am developing a Spring MVC web-application using JSP/JSTL as the view technology.
The way I work is to create a full web-page (with "html", "head", etc) tags in it. This will work on all browsers. My entire app works (however ugly-bugly) with JS disabled.
Also included in each page is some jQuery script that prettifies the page, typically turning top-level "divs" into tabs, other divs into dialogs, etc. The JS "hijacks" the underlying HTML. My JS hijacks the links and buttons, using AJAX calls to load the content into the correct dialog or tab div.
This all works nicely and I like the architecture, but I have added an optimisation such that the AJAX requests appends a "contentOnly" parameter; this is picked up by the Spring MVC view which conditionally ignores the "head", etc - i.e. it only renders the real content that the AJAX version wants. It just feels clunky.
I know I could load the entire page and discard the outer bits but this seems inefficient to load all the associated CSS and JS files which are not strictly necessary.
My question is: is there a nicer way to write this conditional formatting, should I be using a different view technology or something else, something like Velocity or FreeMarker or whatever Grails uses?
An example of my conditional: -
<%# 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" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:if test="${param.contentOnly == null}">
<!DOCTYPE html>
<html>
<head>
<%# include file="_stylesAndScripts.jsp"%>
<title>My App Title</title>
</head>
<body>
<%# include file="_header.jsp"%>
<%# include file="_menu.jsp"%>
</c:if>
<div id="leadListPanel" class="contentPanel">
<h1>My App Title</h1>
<p>The time on the server is ${serverTime}.</p>
<table id="leadTable" class="list">
... rest of content...
<c:if test="${param.contentOnly == null}">
<%# include file="_footer.jsp"%>
</body>
</html>
</c:if>
You need to include the files the other way round.
/WEB-INF/template.jsp
<!DOCTYPE html>
<html>
<head>
<%# include file="_stylesAndScripts.jsp"%>
<title>My App Title</title>
</head>
<body>
<%# include file="_header.jsp"%>
<%# include file="_menu.jsp"%>
<jsp:include page="${page}.jsp" />
<%# include file="_footer.jsp"%>
</body>
</html>
leads.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<div id="leadListPanel" class="contentPanel">
<h1>My App Title</h1>
<p>The time on the server is ${serverTime}.</p>
<table id="leadTable" class="list">
... rest of content...
And create a controller which sets leads as ${page} variable based on a specific request URL and forward to template.jsp instead. Since I don't do Spring, I can't answer in detail how to achieve it with Spring. But the following basic JSP/Servlet kickoff example should give the general idea:
#WebServlet(urlPatterns={"/pages/*"})
public class TemplateServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String page = request.getPathInfo();
// .. Do some other preprocessing if necessary .. and then:
request.setAttribute("page", page);
request.getRequestDispatcher("/WEB-INF/template.jsp").forward(request, response);
}
}
Invoke it as http://example.com/contextname/pages/leads to get the template displayed with leads.jsp included. Finally you should be able to invoke http://example.com/contextname/leads.jsp independently to get the sole template content.
I have used that kind of approach a few years ago with Freemarker and I don't know better way to do it.
What you could do is to create JSP-tags for those conditions so that they look nicer and hides the actual implementation. Something like this:
<t:NonAjax>
<!DOCTYPE html>
<html>
<head>
<%# include file="_stylesAndScripts.jsp"%>
<title>My App Title</title>
</head>
<body>
<%# include file="_header.jsp"%>
<%# include file="_menu.jsp"%>
</t:NonAjax>
<div id="leadListPanel" class="contentPanel">
<h1>My App Title</h1>
<p>The time on the server is ${serverTime}.</p>
<table id="leadTable" class="list">
... rest of content...
<t:NonAjax>
<%# include file="_footer.jsp"%>
</body>
</html>
</t:NonAjax>