I tried to figure it out by myself, but i did not get it either how to create my own menu category/item to link to a new page or just call a method from my controller in the view.
I implemented Spring batch for XML/Database stuff, it's working fine, i put the call of this method inside the "list all" method to test it until i find a way call this method in the view.
Thank you for your time.
For creating my menu Entry and my controller, i did in roo shell :
controller class --class ~.web.DataTransferController --preferredMapping /datatransfer
Then my method :
#RequestMapping(value = "/exportdatatoxml" , method=RequestMethod.GET)
private void runExportDataTOXML(HttpServletRequest request, HttpServletResponse response) throws SQLException {
...
}
And in my jspx
<input type="button" onclick="location.href='${pageContext.request.contextPath}/datatransfer/exportdatatoxml'" value="Export to XML" />
i should look harder.
Related
I'm trying to use Thymeleaf fragments with Ajax on my project and I have this method on my controller:
public def displayInfo(Model model) {
log.info("Guests method!")
model.addAttribute("content", "testing ajax");
"fragments/content::form-basic";
}
And I get this message before running the application:
WARNING: The [displayInfo] action in [ca.capilanou.hrpay.workload.NonInstructionalWorkloadController] accepts a parameter of type [org.springframework.ui.Model]. Interface types and abstract class types are not supported as command objects. This parameter will be ignored.
public def displayInfo(Model model) {
^
On the html where I want to add the fragment by ajax I have this just for testing:
<button id="bt1" onclick="$('#content').load('/nonInstructionalWorkload/displayInfo');">Load Frag 1</button>
<div id="content"></div>
What is happening is that I get the "Guests method!" message on the console, which means that it's reaching the controller, but when it tries to do:
model.addAttribute("content", "testing ajax");
I get a nullPointerException because the model parameter is coming null.
So I tried to comment this line and just return the fragment I want to display.
This is the fragment I have:
<th:block th:fragment="content" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<div th:text="${content}"></div>
</th:block>
I tried to put the ${content} text hard coded when commenting the model.addAttribute line, but I'm not getting anything back on my screen.
What do I need to do to fix the "WARNING" I'm getting and also the to be able to see the fragment being shown on the right place?
I was able to solve it this way:
Instead of using this method:
public def displayInfo(Model model) {
log.info("Guests method!")
model.addAttribute("content", "testing ajax");
"fragments/content::form-basic";
}
I'm now using this:
ModelAndView addWorkItem() {
log.info("Display Fragment using Ajax")
ModelAndView modelAndView = new ModelAndView("/fragments/content :: content")
modelAndView.addObject("content", "Hello World!")
return modelAndView
}
We need to return the ModelAndView. If there anything you need to use on the screen you can addObject adding its attributes.
By doing this I avoid the Model, so I get rid of the Warning issue.
That's it. I wasn't able to find this solution anywhere.. I found pieces in different articles.
https://github.com/dandelion/dandelion/issues/28
http://www.marcelustrojahn.com/2016/08/spring-boot-thymeleaf-fragments-via-ajax/
http://www.xpadro.com/2014/02/thymeleaf-integration-with-spring-part-2.html
I have a JSP page with two buttons. One is On and other one is OFF.
If I click on ON button in JSP, On click some predefined string will have to send to IP address.
How can we call Java program from JSP on click button?
Just give the individual button elements an unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements
E.g.
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" name="button1" value="Button 1" />
</form>
with
#WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MyClass myClass = new MyClass();
if (request.getParameter("button1") != null)
{
myClass.function1();
}
else
{
// ???
}
request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
}
}
You can call it using Ajax . AJAX request will invoke any java program you want by sending the request to the server. see this for more info.
There are also other possible options you can use DWR for secure transactions.
See here for jquery ajax post . Also here is good example for using it with servlets.
Hope this helps !!
side-note: If you need any specific help , please post us the code which you are trying
On the surface, this question will sound a lot like questions that may have been asked previously on SOF but I tried those answers long ago and no luck.
(For example, this question spring 3 not rendering model in jsp)
So I had a Spring 2.0 Controller that extended CancellableFormController, and it contained the following to bind the Command Object to the Form on JSP page render:
public class MyFormController extends CancellableFormController {
....
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
MyCommand myCommand = new MyCommand();
... // add some list info to command object etc in preparation for page render
return myCommand;
}
....
}
The JSP Page looked something like the following:
<form:form method="post" commandName="myCommand">
<c:forEach items="${myCommand.myList}" var="myItem" varStatus="index">
</form:form>
To be clear, between the form tag definitions, a list of items was displayed on the JSP page. This is before any form submission has occurred (ie. at page render time). And what a beautifully simple world we lived in. Everything worked first time and there was peace on earth... sorry, enough sarcasm! ;)
OK, so I happily tried to upgrade this old code to Spring 3 and annotations. My current problem is ONLY getting the Command object to render on page load. When I enter data into form fields and submit the form etc, the data gets bound correctly. What I am trying to do is pre-populate the Command object, and then render that content into the JSP page before the form is populated and submitted.
I initially tried this:
#Controller
#RequestMapping(value = "/myContextPath")
public class MyFormController {
...
#RequestMapping(method = RequestMethod.GET)
public ModelAndView initForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv = new ModelAndView("myTilesViewName");
MyCommand myCommand = new MyCommand();
...
mv.addObject("myCommand", myCommand);
return mv;
}
...
}
Then I tried each of the following methods (the Controller class construct being the same as the above):
#RequestMapping(method = RequestMethod.GET)
#ModelAttribute("myCommand")
public String initForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
MyCommand myCommand = new MyCommand();
....
return "myTilesViewName";
}
#RequestMapping(method = RequestMethod.GET)
public String initForm(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception {
MyCommand myCommand = new MyCommand();
...
model.addAttribute("myCommand", cmd);
return "myTilesViewName";
}
I don't wish to add any confusion. I "imagine" that the answer to this problem is likely the same if I were just returning the view name of a JSP page... However, I am using Apache Tiles to handle the page selection. My definition looks something like:
<definition name="myTilesViewName" extends=".myTemplate">
<put-attribute name="title" value="MyTitle" type="string" />
<put-attribute name="body" value="/WEB-INF/jsp/myPage.jsp" />
</definition>
Please remember everything worked perfectly before with the Spring 2 CancellableFormController code. I have not changed the Tiles config or JSP pages at all so don't believe they are the source of this problem.
Thank you so much to anyone who can offer any assistance. It is certainly appreciated!
UPDATE:
This issue finally related to a Client side (JSP page) related problem. My assumption that "nothing had changed other than in the Controller" was incorrect. Sincere apologies to those who took the time to read this post and consider solutions. For anyone else reading with the same symptoms, please double check your View pages (JSP) and ensure they are syntactically correct for rendering. In my case, I had moved a JSP (with around 2000 lines of code) into a subfolder and broken a relative link to a nested jsp import declaration.
I have a a JSP file in this format(two select tags)-
<%# page import="mypackage.*" %>
<all the main tags>...
<form>
<select> options... </select>
<select> options... </select>
<input type="submit" value="submit" />
</form>
<textarea></textarea>
There is a java method inside "mypackage" which should take arguments from the <select> tags after clicking on submit.
The method returns a string which I want to output in the <textarea>.
How do I go about this ?
Thanks a lot guys.
Send it as HTTP POST or HTTP GET to a servlet, and receive it via doGet() or doPost() methods. You can access it via HttpServletRequest.getParameter().
void doPost(HttpServletRequest request, HttpServletResponse response)
I see that you are importing the mypackage.* classes into your JSP. Indeed, you could include Java code inside your JSP and call the class directly. Something like:
<%
MyClass c = new MyClass();
String result = c.doSomething(request.getParameter("select"));
out.println("<textarea>" + result + "</textarea>");
%>
should be sufficient (but not good: the result should be escaped).
However, this code is not very maintainable and it can be done better (the answer of kaustav datta is one standard way of doing it).
It can be done in a more elegant way using the Spring framework's MVC part: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html
It needs some configuration at the beginning and takes some time to understand, but when you got it, it is very nice.
In your case, a controller of the following form would be sufficient:
#Controller
public class SelectController {
private final class MyClass c = new MyClass();
#RequestMapping(value="/select", method = RequestMethod.POST)
public String doSelect(#RequestParam("selection") final String selection, final ModelMap model) {
final String result = c.doSomething(selection);
modelMap.addAttribute("result", result);
return "yourJsp";
}
}
request.getParameterValues("select")
here getParameterValues is a method of the request interface which returns a string in argument of this method pass name of your controller
when you get value from text box use the method request.getParameter("name");
In Spring 3.0
if i have a jsp page with two different links each calling different method on MultiActionController
<form:form method="POST">
Add
Delete
</form:form>
on the MultiActionController i get request parameter as null so cannot validate the values
String username=request.getParameter("username");
String password=request.getParameter("password");
i also tried uing a button and changed it to look like a link but in case of button click add method is called twice once with requestparameter as null and second time with correct values, but this twice entry is creating a mess in the code also to make this work i am using form action which will not work in case of two different method calls
<form:form action="user.htm?action=add method="POST">
<input type="submit" value="I have info"/>"> ---> should call delete method
<input type="submit" value="Click to send info"/> ---> should call add method
</form:form>
want to achieve this without javascript
I have also set param reslover in xml file with default method to call
let me explain my problem again forget the above code i was just giving some example
I have a jsp page which has two input text field and two links each should call different method of the controller both the method will validate the input and will get redirect to another page simple!!
The reason i have using MultiActionController.......
Unfortunately i have to continue using a controller which extends MultiActionController because the same jsp page also has paging which work absolutely fine
So all i wan to do is simply achieve server and client side validation once either of the link is clicked and redirect accordingly.
Please give me some example to move ahead in this...
i want to achieve this w/o javascript i got this example here
but my problem is why the requestParameter is Null
http://www.goospoos.com/2009/11/spri...oller-example/
Here's my code
<bean id="myExampleController" class="com.ui.controller.MyExampleController">
<property name="methodNameResolver">
<ref bean="paramResolver" />
</property>
<property name="validators" ref="myExampleValidator"/>
</bean>
<bean id="paramResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="defaultMethodName" value="loadPage"></property>
<property name="paramName">
<value>action</value>
</property>
</bean>
<bean id="myExampleValidator" class="com.validator.MyExampleValidator" />
Controller
public ModelAndView validateValues(HttpServletRequest request, HttpServletResponse response) throws Exception{
ModelAndView mav=null;
----> this is null ???
String value1=request.getParameter("textvalue1");
String value2=request.getParameter("textvalue2");
mav = new ModelAndView("myexample");
mav=getPageData(request, false);
return mav;
}
JSP page
<form action="myexample.htm" method="post">
input type="text" name="textvalue1" size="20" />
input type="text" name="textvalue2" size="20" />
</form>
click to validate
----------> what's wrong with this if the above mentioned site can call a method and works fine ,why i cannot get request parameters
You should consider re-working your controller. Your desired operations should contextually fall under a semantic identifier. For CRUD (create, read, update, delete) operations for a User entity, one my set up the RequestMappings like:
/user (root user index page, lists all users)
/user/add (create a new user)
/user/delete/{id} (delete a user by id)
/user/{id} (find a user by id)
At the controller level, you would accomplish this by:
#RequestMapping(value="/user")
public class UserController
{
#RequestMapping(method=RequestMethod.GET)
public String getListUsers() // default page that is resolved by /user
{
return "user/list"; // used by view resolver
}
#RequestMapping(value="/add.html" method=RequestMethod.GET)
public String getAddUser(Model model)
{
//add person form backing entity to model
return "user/add"; // used by view resolver to locate view
}
#RequestMapping(value="/add.html" method=RequestMethod.POST)
public String postAddUser(#ModelAttribute person) // other objects for errors, etc.
{
// add person, validate person, etc.
return "redirect:/user"; // redirects to index
}
}
et cetera...you'd follow those patterns for the other URIs
Then below works for me
UI
<form:form action="user.htm?action=add method="POST">
<input type="submit" name="add"/>
server side
(WebUtils.hasSubmitParameter(request, "add")