How to make dynamic url-pattern using Spring MVC #PathVariable? - spring

I'm working that make search function.
I have a search form on jsp view.
<form action="<c:url value="/community/board/list/search" />">
<p class="serch_Area">
<select name="searchCategory">
<option value="subject" selected="selected">subject</option>
<option value="contents">contents</option>
</select>
<input type="text" name="searchWord" class="inputCom" style="width:150px; height:17px;" value="" maxlength="15" />
<input type="image" src="<c:url value="/resources/images/common/btn_search.gif" />" alt="search" />
</p>
</form>
I want to make request url-pattern like "/community/board/list/search/subject/abc". But this form action url like "/community/board/list/search?subject=abc"
How can I make request url pattern like RESTful?
This is my controller.
#RequestMapping("/list/search/{searchCategory}/{searchWord}/{pageNum}")
public String getSearchList(#PathVariable(value = "searchCategory") String searchCategory,
#PathVariable(value = "searchWord") String searchWord,
#PathVariable(value = "pageNum") int pageNum, ModelMap model) {
Please help me.

You can do this with JavaScript. You should add an onSubmit listener on your form and change your form action within that method.

Related

Thymeleaf form array with default values

I'm using Spring+Thymeleaf to see and modify the users in a database. I would like to set the input fields to the actual values of an original user but I've tried with different styles and it doesn't work.
With the present configuration I can update information of users and see the id of original user (it's not in a input field) but I can't show the actual configuration in input field as default.
CONTROLLER:
#GetMapping(value = {"/", ""})
public String subusersPage(HttpSession session, Model model) {
String idUser = BaseController.getLoggedUser(session);
UserDTO userDTO = userService.getUserById(idUser);
model.addAttribute("subusersDTO", userService.getSubusersDTO(userDTO.getSubusers()));
model.addAttribute("populations", userDTO.getPopulations());
model.addAttribute("configurations", userDTO.getConfigurations());
model.addAttribute("attributes", userDTO.getAttributes());
model.addAttribute("subuserDTO", new SubuserDTO());
return "subusers";
}
HTML:
<th:block th:each="subuserDTO_original : ${subusersDTO}">
<hr>
<form action="#" th:action="#{/subusers/__${subuserDTO_original.id}__}" th:object="${subuserDTO}" method="post">
<div>
<p th:text="${'Id: ' + subuserDTO_original.id}"></p>
<p>Name: <input type="text" th:field="*{name}" th:name="name" th:value="${subuserDTO_original.name}"/></p>
<p>Population: <input type="text" th:field="*{population}" th:name="population" th:value="${subuserDTO_original.population}"/></p>
<p>Configuration: <input type="text" th:field="*{configuration}" th:name="configuration" th:value="${subuserDTO_original.configuration}"/></p>
<p>Attributes: <input type="text" th:field="*{attributes}" th:name="attributes" th:value="${subuserDTO_original.attributes}"/></p>
<p>
<button type="submit" th:name="action" th:value="update">Update</button>
<button type="submit" th:name="action" th:value="delete">Delete</button>
<button type="reset" th:name="action" th:value="clear">Clear</button>
</p>
</div>
</form>
<form action="#" th:action="#{/subusers/__${subuserDTO_original.id}__}" method="get">
<button type="submit">Default</button>
</form>
</th:block>
Any help will be very appreciated, thank you!
If you want to edit an existing user, then your th:object (which is ${subuserDTO} in this case) needs to be populated with the values of the original user. This is because when you use the attribute th:field="*{name}", it actually overwrites the name, id, and value of the html tag (which is why th:value="${subuserDTO_original.name}" isn't working.
Two other options you could do:
You could also set name="name" and use th:value instead.
Or another option, you could use ${subuserDTO_original} as your th:object.

Spring & JSP: Get value from certain input using spring controller

Can somebody help me to get value from certain input using spring controller.
I have 2 input data, and I just need a value from one of these inputs:
<input type="text" name="data01" />
<input type="text" name="data02" />
I just want to retrieve a value from "data01".
I just have used
(HttpServletRequest) request.getParameter("data01")
Or
#RequestParam(value="data01") Integer data01
but the value is null.
Can somebody help me
EDIT:
jsp:
<table>
<tr>
<input type="text" name="data01" />
<input type="text" name="data02" />
</tr>
</table>
controller:
#RequestMapping(value = "/user", method=RequestMethod.GET)
public String showAllData(ModelMap model, HttpServletRequest request) {
String retrievedData = request.getParameter("data01");
System.out.println("data= " + retrievedData);
model.addAttribute("data", new data());
return "data";
}
The retrievedData value is null.
You should be able to get the parameter using this method
<form action="/user" method="get">
<table>
<tr>
<input type="text" name="data01" />
<input type="text" name="data02" />
<input type="submit" value="submit"/>
</tr>
</table>
</form>
and in the controller
#RequestMapping(value = "/user", method=RequestMethod.GET)
public String showAllData(String data01, ModelMap model) {
// your logic here
}
and from the code you have posted. You are casting the parameter to HttpServletRequest
request.getParameter("data01") //returns String as default.
Integer.parseInt(request.getParameter("data01");
From your comment at #user1516735 answer, you cannot use it outside of the form tag. Unless you include it in the parameter from ajax or append the value of "name01" in the url as /user?name01=value
You will get the value of data01 by using the below code:
request.getParameter("data01");
Here request is of type HttpServletRequest. Make sure your input control is inside form tag.

Controller Not receiving value from span in HTML using Spring boot and Thymeleaf

I have the following content in my HTML which is using Thymeleaf
<form action="#" th:action="#{/shutDown}" th:object="${ddata}" method="post">
<span>Domain</span>
<span th:text="${domain}" th:field="*{domain}">domain</span>
<input type="Submit" value="close" />
</form>
And I have the following in my Controller which is using Sprint Boot
#RequestMapping(value = "/shutDown", method = RequestMethod.POST)
public ModelAndView shutDownPage(ModelAndView modelAndView, Authentication authentication,
#ModelAttribute("ddata") DInputBean dInputBean) {
String domain = dInputBean.getdomain();
return modelAndView;
}
I'm hoping I'd get value of domain from the HTML in the Controller but it's always null. DInputBean has getters and setters for "domain" field.
The th:field attribute can be used on <input>, <select>, or, <textarea>.
A solution you could possibly replacing you second <span> with a hidden input element.
<form action="#" th:action="#{/shutDown}" th:object="${ddata}" method="post">
<span>Domain</span>
<input type="hidden" th:field="*{domain}" th:value="${domain}" />
<input type="Submit" value="close" />
</form>
If you wanted to keep the second div, just place the <input type="hidden"> inside the second <span> and remove the th:field attribute from the second <span>.
Edit:
If you wanted to add the value of domain in a span.
<form action="#" th:action="#{/shutDown}" th:object="${ddata}" method="post">
<span>Domain</span>
<span th:text="${domain}">domain<span>
<input type="hidden" th:field="*{domain}" th:value="${domain}" />
<input type="Submit" value="close" />
</form>
http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#inputs
An option is to use a read-only input field:
<input type="text" th:field="*{domain}" th:value="${domain}" readonly="readonly"/>
This both displays the value and sends it on submit.
The key is to add the value of the domain variable to the form:
#GetMapping("/shutDownPage")
public String shutDownPage(Model model) {
model.addAttribute("ddata" new Ddata()); //or however you create your bean
String username = ... //however you get your username
String domain = myRepositoryService.findDomainByUsername(username);
model.addAttribute("domain", domain);
return "shutDownPage";
}
Include an HTML page in the action so that when you open the HTML page in a browser without a server/container, the button will still appear to work:
<form action="confirmationPage.html" th:action="#{/shutDown}" th:object="${ddata}" method="post">
<!-- You can benefit from using a conditional expression -->
<span th:text="${domain != null ? domain : 'No domain supplied'}">[domain]</span>
<input type="hidden" th:field="*{domain}" th:value="${domain}"/>
<input type="Submit" value="close"/>
</form>
And your post method:
#PostMapping("/shutDown") //use shorthand
public String shutDownPagePost(#ModelAttribute("ddata") DInputBean dInputBean {
String domain = dInputBean.getDomain();
//do whatever with it
return "confirmationPage";
}

Access Get or Post parameters in MVC Web Api Authorization filter

I want to achieve the same as Accessing post or get parameters in custom authorization MVC4 Web Api ,but it only works in the case of a GET request.
So I have written the follwoing action filter for a web api:
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var request = actionContext.Request;
var headers = request.Headers;
HttpContext ctx = default(HttpContext);
ctx = HttpContext.Current;
if (ctx != null)
{
var apiKey = (string)actionContext.ActionArguments["apiKey"];
}
}
The form that posts looks like:
<form name="form1" method="post" enctype="multipart/form-data" action="#localPostUrl">
<fieldset>
<legend>File Upload Example</legend>
<div>
<label for="caption">Image Caption</label>
<input name="caption" type="text" />
</div>
<div>
<label for="image1">Image File</label>
<input name="image1" type="file" />
</div>
<div>
<input type="text" name="apiKey" id="apiKey" value="b2b54e7b-ca0b-4adf-a369-efe839e55120" />
<input type="submit" value="Submit" />
</div>
</fieldset>
So I'm trying to post an image and a string to the Web Api but the actionContext.ActionArguments in the ActionFilter is empty when doing a POST request but is working when doing a GET request.
When compared to the solution provided on top of my question I notice that the action where that posts has an attribute FormUri added to a parameter, but I can't send the ApiKey in the querystring.
Is there a solution to getting the Post paramteres in order to do some form on validation?

how to differenciate between onchange submit and button submit in spring controller

I have the jsp code as :
<s:url value="add" var="addUrl"/>
<form:form name="add" action="${addUrl}" modelAttribute="content" method="post">
<input type="hidden" name="add" value="" />
<form:select path="id" class="dClass" onchange="submit()">
<form:options items="${list}" /></form:select>
<input type="submit" class="btn" value="Refresh Content" />
</form:form>
And I have one controller method for both this call, is there any way to differentiate that from where the form is submitted? Either from the drop down or from the submit button?
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String getContentById(Model model, String id,Content content,HttpServletRequest request) {
if(call by onChange)
else if(call by submit button)
}
Kindly note that, onchange="submit()" will not submit your page. It will look for the function with name submit. Inside that function you can use code like this $('form#form_id').submit(); to submit. Check submit-a-form-using-jquery for more details.
#Vinoth Krishnan Thanks for your answer , its working now :) added a filed in my form as "dropDownSubmit"
function submitForm(formId){
var input = $("<input>").attr("type", "hidden").attr("name", "dropDownSubmit").val("true");
$("#" + formId).append($(input));
$("#" + formId).submit();
}
Then in controller:
if("true".equalsIgnoreCase(form.getDropDownSubmit()){
..
}
else{
.. button submit
}

Resources