Spring mvc: forward to another controller - java

I have a method in a controller that shows a search page with some filters and a list of entities.
When I select one entity, I enter in edit-entity-page, the "save" button saves editing on db and go back to edit-entity-page.
Now: I should modify this behavior to go back to the list of entities.
This is the list method declaration, in my list controller:
#RequestMapping(value = "/customer/process/{filtro}/{processType}/filter.htm", method = RequestMethod.GET)
public String showHome(Map model, #PathVariable String filtro, #PathVariable String processType) {
and this is the forward I tried from detail controller:
return "forward:/customer/process/"+filtro+"/"+processType+"/filter.htm";
The forward method is called and list-entities-page displayed but I have some issue with the form on this page: every submit on it goes to the wrong controller (the detail controller instead of list controller)
(Spring 3.0.5)
Details asked by sgpalit :
This is what i called "detail controller" that manage the "save" process:
#Controller
public class ShipmentController {
#RequestMapping(method = RequestMethod.POST)
public String onSubmit(#ModelAttribute("shipmentForm") ShipmentForm shipmentForm, ModelMap model, HttpServletRequest request) {
return onSubmitNEW(model, shipmentForm, request);
}
public String onSubmitNEW(ModelMap model,ShipmentForm shipmentForm, HttpServletRequest request) {
--- save process ---
model.put("filtro",filtro);
model.put("processType", processType);
return "forward:/customer/process/"+filtro+"/"+processType+"/filterfrw.htm";
}
this is what i called "list controller":
#Controller
public class ProcessController {
#RequestMapping(value = "/customer/process/{filtro}/{processType}/filter.htm", method = RequestMethod.GET)
public String showHome(Map model, #PathVariable String filtro, #PathVariable String processType) {
CustomUserAuthentication ctoken = (CustomUserAuthentication) SecurityContextHolder.getContext().getAuthentication();
LoginCustomer loginCustomer = ctoken.getLoginCustomer();
LOG.debug("public String showHome()");
ResultFilterForm resultFilterForm = new ResultFilterForm();
List<ShipmentDetail> lDetails = new ArrayList<ShipmentDetail>();
List<ShipmentHeader> lShipments = new ArrayList<ShipmentHeader>();
SearchFiltersForm searchFiltersForm = new SearchFiltersForm();
searchFiltersForm = getSearchFiltersForm(searchFiltersForm);
searchFiltersForm.setNumPage(0);
searchFiltersForm.setProcessType(processType.toUpperCase());
searchFiltersForm.setFiltro(filtro.toUpperCase());
String strReturn = "";
List<String> chkPrint = new ArrayList<String>();
if (filtro.toUpperCase().equals("PIECES")) {
lDetails = shipmentDetailDAO.getDetails(null, processType, loginCustomer.getLcCustomer().getCwCustomer());
PagedListHolder pagedListHolder = new PagedListHolder(lDetails);
int page = 2;
pagedListHolder.setPage(searchFiltersForm.getNumPage());
pagedListHolder.setPageSize(pageSize);
model.put("lDetails", pagedListHolder.getPageList());
strReturn = "customer/process/listDetails";
if (lDetails.size() == 0) {
model.put("isEmpty", "msg_error");
}
if (loginCustomer.getLcFlagPrnLbl().equals("Y")) {
for (int i = 0; i < lDetails.size(); i++) {
chkPrint.add(lDetails.get(i).getSdCodPiece());
}
}
resultFilterForm.setCurrentPage(pagedListHolder.getPage() + 1);
resultFilterForm.setNumPage(pagedListHolder.getPageCount() - 1);
} else {
lShipments = shipmentHeaderDAO.getShipments(null, processType.toUpperCase(), loginCustomer.getLcCustomer().getCwCustomer());
PagedListHolder pagedListHolder = new PagedListHolder(lShipments);
int page = 2;
pagedListHolder.setPage(searchFiltersForm.getNumPage());
pagedListHolder.setPageSize(pageSize);
model.put("lShipments", pagedListHolder.getPageList());
strReturn = "customer/process/listShipments";
if (lShipments.size() == 0) {
model.put("isEmpty", "msg_error");
}
if (loginCustomer.getLcFlagPrnLbl().equals("Y")) {
for (int i = 0; i < lShipments.size(); i++) {
chkPrint.add(i + "");
}
}
resultFilterForm.setCurrentPage(pagedListHolder.getPage() + 1);
resultFilterForm.setNumPage(pagedListHolder.getPageCount() - 1);
}
resultFilterForm.setIsAddShipment(loginCustomer.getLcFlagCompMan());
if (loginCustomer.getLcFlagPrnLbl().equals("Y")) {
resultFilterForm.setChkPrint(chkPrint);
} else {
resultFilterForm.setChkPrint(null);
}
resultFilterForm.setSearchFiltersForm(searchFiltersForm);
resultFilterForm.setPageSize(pageSize);
model.put("resultFilterForm", resultFilterForm);
return strReturn;
}
}

Related

How to return nothing/pop up box/stay on page with just a message "success" after post mapping?

How to return nothing after post mapping in Spring Boot?
I have this controller, that controller is connected with button, when button is pressed this controller will save a current element from collection into new collection.
#PostMapping("/savedAdventureHolidays/post/{adventureHolidayId}")
public String saveAdventureHolidayElement(#PathVariable(value = "adventureHolidayId") String adventureHolidayId,
Model model) {
UserProfile comment = new UserProfile();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
return adventureHolidaysRepository.findById(adventureHolidayId).map(post -> {
comment.setAdventureHolidaysList(Collections.singletonList(post));
comment.setLoggedUserId(username);
comment.setSavedHolidayTitle(adventureHolidaysRepository.findById(adventureHolidayId).get().getTitle());
model.addAttribute("comment", comment);
userProfileRepository.save(comment);
return "redirect:/adventureHolidays/randomSummerCamps";
}).orElseThrow(() -> new ResourceNotFoundException("PostId " + adventureHolidayId + " not found"));
}
As you can see I have here this return:
return "redirect:/adventureHolidays/randomSummerCamps";
But its always a different element in HTML since I have this method
#Override
public AdventureHolidays findRandomAdventureHolidays(String type) {
if (elementsToReturn.size() == 0) {
Query query = new Query();
query.addCriteria(Criteria.where("typeOfAdventureHolidays").is(type));
List<AdventureHolidays> newData = mongoTemplate.find(query, AdventureHolidays.class);
Collections.shuffle(newData);
elementsToReturn.addAll(newData);
}
return elementsToReturn.poll();
}

Import and Reading a CsvFile with dedicated service to a existing repo with its own service

Trying to add some enhancements to this app,
private void parseCsv(CsvMapReader csvMapReader) throws IOException {
String[] header = csvMapReader.getHeader(true);
List<String> headers = Arrays.asList(header);
verifySourceColumn(headers);
verifyPovColumn(headers);
final CellProcessor[] processors = getProcessors(headers);
Map<String, Object> csvImportMap = null;
while ((csvImportMap = csvMapReader.read(header, processors)) != null) {
CsvImportDTO csvImportDto = new CsvImportDTO(csvImportMap);
if ( activationTypeP(csvImportDto) ){
AipRolloutVO aipRolloutVO = new AipRolloutVO(csvImportDto.getSource(),
csvImportDto.getPov(),
csvImportDto.getActivationType(),
csvImportDto.getActivationDate(),
csvImportDto.getDeactivationDate(),
csvImportDto.getMssValue());
aipRolloutRepository.updateAipRollout(aipRolloutVO.getDc(),
aipRolloutVO.getPov(),
aipRolloutVO.getActivationType(),
aipRolloutVO.getMssValue());
}
}
}
When it goes to the repo I get:
cannot find local variable 'csvImportMap'
5 times and then:
((CsvParserService)this).aipRolloutService = inconvertiible types; cannont cast 'org.spring.....
my controller method
#PostMapping(value = "/updatecsv", produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<?> processCsv( #RequestParam("csvFile") MultipartFile csvFile) throws IOException {
if (csvFile.isEmpty()) return new ResponseEntity(
responceJson("please select a file!"),
HttpStatus.NO_CONTENT
);
csvParserService.parseCsvFile(csvFile);
return new ResponseEntity(
responceJson("Successfully uploaded - " + csvFile.getOriginalFilename()),
new HttpHeaders(),
HttpStatus.CREATED
);
}
repo im trying to reuse to update these values
public int updateAipRollout(String dc, String pov, String activationType, int mssValue) {
String query = some query
logger.debug("Rollout update query: " + query);
int num =jdbcTemplate.update(query);
return num;
}
Do I need to autowire the other service class that this repo is in and then call that service? But when I did that it also didn't fix the error....

Are Spring boot Controller methods also singleton?

I am writing a Spring boot application and I have a question regarding my controller class. I read the documentation and saw that the controller is a singleton by deafult, so I have decided to save my user info in a DB and save it by session. I use the spring boot sesison managment JDBC. My question is though, if a method is also singelton. I know it seems like a foolish question but I am starting to second guess myself. I am confused if the code I have would fail if multiple users logged in with a session. Also, can I not have any variables in my methods, or should I move the logic I have here somewhere else. I really don't know.
Java Controller Method:
#RequestMapping(value = "/edit")
public ModelAndView editTab(#RequestParam(value = "currentAppcode", required = false, defaultValue = "Appcode") String currentAppcode,
#RequestParam(value = "currentAcro", required = false, defaultValue = "Arco") String currentAcro,
#RequestParam(value = "currentAppname", required = false, defaultValue = "Appname") String currentAppname,
HttpSession session) {
ModelAndView modelAndView = new ModelAndView();
private List<Some_Object> allQueryConfig = new ArrayList<Some_Object>();
session.setAttribute("SELECTED_APP",queryService.findDtoById(currentCode));
session.setAttribute("ALL_SERVERS", queryService.serverWork() );
allSystems.clear();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();
try {
OPTApplication selected_app = (OPTApplication) session.getAttribute("SELECTED_APP");
rc.setProxy();
if (rc.validateUser(currentPrincipalName, selected_app.getSys_id()) != 0 || queryService.isAuditor(currentPrincipalName)) {
session.setAttribute("GP_SELECTED", apiRunner.runGPData(selected_app.getNumber()));
allQueryConfig = queryService.getNonDistinctServerInfo();
modelAndView.setViewName("create");
for (AppSelectorTier current : allQueryConfig) {
allSystems.add(current.getSystem());
}
} else {
modelAndView.setViewName("forbidden");
}
} catch (Exception e) {
e.printStackTrace();
modelAndView.setViewName("test");
}
modelAndView.addObject("currentAppName", "Application: " + currentAppname);
modelAndView.addObject("ary4", queryService.getServerInfo());
modelAndView.addObject("adid", currentPrincipalName);
modelAndView.addObject("hasAccess", false);
return modelAndView;
}
Another example:
public #ResponseBody List<SelectorDTO> getGPdataTaddm(#RequestBody TestApp mTestApp, HttpServletRequest request, HttpSession session)
throws SQLException {
GroupPatternDTO gp_selected = (GroupPatternDTO) session.getAttribute("GP_SELECTED");
session.setAttribute("QUERY_CONFIG_DATA", new QueryConfigData());
QueryConfigData query_config_data = (QueryConfigData) session.getAttribute("QUERY_CONFIG_DATA");
List<SelectorDTO> inProgressInfo = queryService.getInfoFromInProgress(gp_selected.getCode());
if (inProgressInfo.size() != 0) {
gp_selected.setSels(inProgressInfo);
} else {
for (SelectorDTO current : gp_selected.getSels()) {
String objectPassed = current.getDescription().replaceAll("[^a-zA-Z0-9]", "");
System.out.println("First match: ----------------------------------------------------------------------"
+ objectPassed);
if (queryService.getTierTypeFromObj(objectPassed).size() != 0) {
AppSelectorTier selectorObj = queryService.getTierTypeFromObj(taddmObjectPassed).get(0);
query_config_data.setName(selectorObj.getName());
query_config_data.setSystem(selectorObj.getSystem());
query_config_data.setMqlList(selectorObj.getMqllisting());
query_config_data.setTag1(selectorObj.getTagname_one());
query_config_data.setTag2(selectorObj.getTagname_two());
query_config_data.setMqlSelector(selectorObj.getMqllisting());
query_config_data.setParseInstruc(selectorObj.getParseinstruction());
query_config_data.setTaddmObject(selectorObj.getTaddmobj());
}
}
}
session.setAttribute("GP_SELECTED", gp_selected);
session.setAttribute("QUERY_CONFIG_DATA", query_config_data);
return gp_selected.getSels();
}
I am unsure if this is a good pracice or if for my usecase this is fine?

Why won't the link go to controller, Spring mvc?

I am having trouble in redirecting the link of below code to my controller class.
This is the code:
$('#ticketDT').DataTable({
"dom": '<"toolbar">frtip',
"responsive": true,
"ordering": false,
"scrollY": "300px",
"scrollCollapse": true,
"ajax": "ticketList.json",
"bDestroy": true,
"deferRender": true,
"aoColumns": [
{"mData": "ticketNumber"},
{"mData": "category"},
{"mData": "subcategory"},
{"mData": "status"},
{"mData": "requestedBy"},
{"mData": "ticketNumber",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a class='linkColor' href='${pageContext.request.contextPath}/assignMessageTicket?sender_assign=" + encodeURIComponent(sender) + "&portId_assign="+portId+"&messageId=" + encodeURIComponent(messageId) + "&ticketNumber_assign=" + encodeURIComponent(oData.ticketNumber) + "'><span data-toggle='tooltip' title='Assign'><i class='ti-plus btn btn-simple btn-assign btn-icon' data-mode='assignTicket'></i></span></a>");
}
}
],
This is my handler for the controller class:
#RequestMapping(value = {"assignMessageTicket"}, method = RequestMethod.GET)
#PreAuthorize("hasAnyRole('CWO_ENCODER,ADMIN')")
public ModelAndView assignMessageTicket(#RequestParam(value = "sender_assign",required = true) String sender,
#RequestParam(value = "portId_assign",required = true) String portId,#RequestParam(value = "messageId",required = true) String messageId,
#RequestParam(value = "ticketNumber_assign",required = true) String ticketNumber,
ModelMap model,HttpServletRequest request) throws UnsupportedEncodingException {
String currentUser = request.getRemoteUser();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/YYYY");
Date date = new Date();
String currentDate = formatter.format(date);
dashboardService.assignMessageSmsMessages(messageId,ticketNumber);
dashboardService.assignMessageSmsReply(messageId,ticketNumber);
dashboardService.addRecentlyAssignedMessage(sender,portId,ticketNumber,currentUser,currentDate);
String newSender = URLEncoder.encode(sender, "UTF-8").replaceAll("\\+", "%2B");
String newPortId = URLEncoder.encode(portId, "UTF-8").replaceAll("\\+", "%2B");
boolean hasError = false;
model.clear();
return new ModelAndView("redirect:conversation?sender="+newSender+"&portId="+newPortId+"&hasError="+hasError);
}
This is my updated code.
The link to the controller is
$(nTd).html("<a class='linkColor' href='${pageContext.request.contextPath}/assignSpecificMessage?messageId="+messageId+"&sender_assign=" + encodeURIComponent(sender) + "&portId_assign="+portId+"&ticketNumber_assign=" + encodeURIComponent(oData.ticketNumber) + "'><span data-toggle='tooltip' title='Assign'><i class='ti-plus btn btn-simple btn-assign btn-icon' data-mode='assignMessageTicket'></i></span></a>");
The controller is
#RequestMapping(value = {"assignSpecificMessage"}, method = RequestMethod.GET)
#PreAuthorize("hasAnyRole('CWO_ENCODER,ADMIN')")
public String assignSpecific(#RequestParam(value = "sender_assign",required = true) String sender,
#RequestParam(value = "portId_assign",required = true) String portId,#RequestParam(value = "messageId",required = true) String messageId,
#RequestParam(value = "ticketNumber_assign",required = true) String ticketNumber,
ModelMap model,HttpServletRequest request) {
return "conversation";
}
I tried to create a new handler to test it, Still, The same error appears.
Ensure that href value for your link is getting build properly.
Go to browser elements tab and check the value for link href and make sure that it is not breaking.
or you can do that using jquery or javascript like below.
$("#idOfAnchorTag").on("click", function(){
var href = $(this).find('a').attr('href');
....
})
UPDATE: As you provided link in one of my comments, it is clear that your request parameters names are not matching with the controller one.
link :
http://localhost:8084/cwms/assignSpecificMessage?assign_sender=%2B639062165304&assign_portId=6&messageId=15416427366198288583&assign_ticketNumber=ADM-1809-00473
Controller :
#RequestParam(value = "sender_assign",required = true) String sender,
#RequestParam(value = "portId_assign",required = true) String portId,#RequestParam(value = "messageId",required = true) String messageId,
#RequestParam(value = "ticketNumber_assign",required = true) String ticketNumber,
You are using wrong parameter names in request so change all the parameters to controller one.
For example sender_assign you are sending as assign_sender and so on.
SO to make it work use sender_assign instead of assign_sender and all other parameters also from client side(anchor href)

Various Response Entity in Spring Controller

In my controller I am having if condition and two different response type. I will get response in JSON format from "if" condition, but I am getting response from else condition like unexpected '0 , instead I need to get my error message'.
My controller code snippet
#RequestMapping(value = "/saveuser", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST)
public ResponseEntity<?> addUser(#RequestBody TestUser user)
throws NotFoundException {
System.out.println(user.getAnswer().size());
if(questioncount == user.getAnswer().size())
{
return new ResponseEntity<TestUser>(service.addUser(user),
HttpStatus.OK);
}else {
String one="one";
String erromessage = "Only" + questioncount +" questions are allowed";
System.out.println(erromessage);
return new ResponseEntity<String>(erromessage,HttpStatus.NOT_ACCEPTABLE);
}
}

Categories

Resources