Spring MVC form submission, populate on the same page - java

I am trying to create a simple function using a post method. What I want is whatever is entered in the form and submitted- it should appear on the same page below the form. However the text just disappears once I click "submit". Here is my code
Contoller
#Controller
public class SearchController {
#RequestMapping(value = "/search", method = RequestMethod.GET)
public String goToSearch(Model model) {
model.addAttribute("item", new Item());
return "itemsearch";
}
#RequestMapping(value = "/search", method = RequestMethod.POST)
public String search(Item item, Model model, #RequestParam String itemId) throws IOException{
model.addAttribute("item", new Item());
return "itemsearch";
}
}
Jsp file
<%# 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="s" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Search for an item</h2>
<sf:form action="search" method="POST" modelAttribute="item">
<label>Please enter the item Id number:<sf:input type="text" name="itemId" id="itemId" path="itemId" /></label><br/>
<input type="submit" value="Submit" path="submit" />
<br> You are trying to search for Id Number: <b><h3>${item.itemId}<h3></h3></b>
</sf:form>
Item class
public class Item {
private String itemId;
private List<String> itemDetails;
public List<String> getItemDetails() {
return itemDetails;
}
public void setItemDetails(List<String> itemDetails) {
this.itemDetails = itemDetails;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
}
Many thanks

I think you need a basic understanding how Spring MVC works.
Have a look at this picture:
You see an incoming request (your POST request) from the client which is redirected to the desired controller. The controller (your SearchController) makes some business magic and returns the model to the front controller. The model is by default empty. You can add objects that should be rendered via model.addAttribute("someId", someObject);
The passed model is now handled by the view template (itemsearch) which connects the template and the model to a (static) response that is passed to the client.
And there is the problem. You are passing in your controller new Item() to the model. It is an empty object which has no values (and no id which you want to render after the form submition). Therefore on your JSP page could be nothing displayed. Just pass the found item or the item from your request to the model.

Related

Data Injection from controller to jsp page

I want to pass a data from controller method to jsp page. In doing so, using HttpServletRequest.setAttribute().
Now, I can pass it to the just next jsp page. But, I want to hold that data for few more pages.
In this case, what should I do?
Flow of Data:
Controller method1 --> jsp page1 --> jsp page2 --> jsp page3 --> jsp page4 --> Controller method2
I tried setting attribute in each page but it returns null value, as follows
<% request.setAttribute("accId", request.getAttribute("accountId")); %>
You have to use session in jsp when sending data from one page to another.
A demo to show this.
For example :
Create a DemoController class.
#Controller
public class DemoController {
#RequestMapping(value = "/getid", method = RequestMethod.POST)
public String getAccountID(Model model) {
model.addAttribute("accountId", "ABC1234"); // example
return "account";
}
}
Suppose, create an account.jsp.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
String accountId = request.getAttribute("accountId");
out.println("account.jsp -> " + accountId);
session.setAttribute("accId", accountId);
%>
<form action="account2.jsp" method="post">
<input type="submit" name="Submit">
</form>
</body>
</html>
Create another page with the name account2.jsp :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
String accId = (String) session.getAttribute("accId");
out.println("account2.jsp -> " + accountId);
// now you want to sent it to the another controller
// set the parameter in the session and retrieve it in the controller.
session.setAttribute("accountId", accId);
%>
</body>
</html>
Create a DemoController2 class :
#Controller
public class DemoController2 {
#RequestMapping(value = "/getid2", method = RequestMethod.POST)
public String getAccountId2(HttpSession session) {
String id = (String) session.getAttribute("accountId"); // example
System.out.println(id);
return "some-page-name";
}
}

I can't find the error from .jsp

I can't figure it out why that is not working. That is the jsp that make me problems. I follow a tutorial from youtube and my jsp looks the same like the jsp from the video. I adapted the code from the video but i don't think that is the problem because the controller and the jsp are the same like those from the video.
here is the tutorial, jsp is at min 24
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Page</title>
</head>
<body>
<spring:url value="/doUpload" var="doUplodaURL" />
<form:form method="post" modelAttribute="formUpload" action="${doUplodaURL
}" enctype="multipart/form-data" >
<form:input path="files" type="file" multiple="multiple"/>
<form:errors path="files" /><br/>
<button type="submit" >Upload</button>
</form:form>
</body>
</html>
and that is my controller
#Controller
public class CsvController {
#Autowired
FileValidator fileValidator;
#Autowired
CsvServices csvServices;
#RequestMapping(value = "/uploadPage", method = RequestMethod.GET)
public ModelAndView getPage() {
ModelAndView model = new ModelAndView("upload_page");
FileUpload formUpload = new FileUpload();
model.addObject("formUpload", formUpload);
return model;
}
#RequestMapping (value="/doUpload", method=RequestMethod.POST)
public String doUpload(#ModelAttribute("formUpload") FileUpload fileUpload, BindingResult result, RedirectAttributes redirectAttributes ) throws IOException {
fileValidator.validate(fileUpload, result);
if(result.hasErrors()) {
return "uploadPage";
} else {
redirectAttributes.addFlashAttribute("fileNames", uploadAndImportDb(fileUpload));
return "redirect:/succes";
}
}
#RequestMapping(value = "/succes", method = RequestMethod.GET)
public ModelAndView succes() {
ModelAndView model = new ModelAndView("succes");
return model;
}
private List<String> uploadAndImportDb(FileUpload fileUpload) throws IOException{
List<String> fileNames = new ArrayList<String>();
List<String> paths = new ArrayList<String>();
CommonsMultipartFile[] commonsMultipartFiles = fileUpload.getFiles();
String filePath = null;
for(CommonsMultipartFile multipartFile : commonsMultipartFiles) {
filePath = "C:\\Users\\bogda\\Desktop\\input\\" + multipartFile.getOriginalFilename();
File file = new File(filePath);
FileCopyUtils.copy(multipartFile.getBytes(), file);
fileNames.add(multipartFile.getOriginalFilename());
paths.add(filePath);
}
//parse and import
csvServices.process(paths);
return fileNames;
}
}
Kindly add commons-fileupload-x.x.jar inside WEb_INF/lib folder.

Spring MVC-Response is not getting from controller using angular

I am implementing simple CRUD Operation using spring restful webservices and angular js.I trying to load all the details when the page is loading.But its not getting any response.
Controller :-
#RestController
public class EmployeeController {
public List<Employee> appList=new ArrayList<Employee>();
#RequestMapping(value="/employee",method=RequestMethod.GET)
public ModelAndView loadEmployee(){
return new ModelAndView("employee", "webemployee", new Employee());
}
#RequestMapping(value="/employees",method = RequestMethod.GET,headers="Accept=application/json")
public List<Employee>loadAllApps() {
Employee app=new Employee();
System.out.println(".........................loadAllApps.............");
app.setAppID("test_id");
app.setAppName("test_name");
appList.add(app);
return appList;
}
#RequestMapping(value="/employees/insert/{appID}/{appDescr}",method = RequestMethod.POST,headers="Accept=application/json")
public List<Employee> addApps(#PathVariable String appID,#PathVariable String appDescr) throws ParseException {
System.out.println("appID"+appID+"appDescr..........."+appDescr);
Employee app=new Employee();
app.setAppID(appID);
app.setAppName(appDescr);
appList.add(app);
return appList;
}
}
Jsp :-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="AppManger">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>WebService Example</title>
<script data-require="angular.js#*" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
</head>
<div ng-controller="appController">
<div>
<table>
<tr ng-repeat="app in appList">
<td >{{ app.appID }}</td>
<td >{{ app.appName }}</td>
</tr>
</table>
</div>
<script type="text/javascript">
var appModule = angular.module('AppManger', []);
appModule.controller('appController', function ($scope,$http) {
var url="http://localhost:8080/Apps";
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get(url+'/employee').
success(function(data, status, headers, config) {
alert(status);
$scope.appList = data;
});
});
</script>
</script>
</html>
when i am trying to checking status value in $http.get method.its not showing any alert message.Please let me know what issues here.
You seem to call your /employee endpoint but expecting a list of employees , because you assigning data response to the:
$scope.appList = data;
First, change that to the other endpoint you created (/employees) which returns the list.
What is the servlet-path of your mvc dispatcher servlet? This would be my first point of failure to check for. I see that you call:
var url="http://localhost:8080/Apps";
Does that mean that you deploy your app in context 'Apps' or is that your servlet path? If this is the context name then I assume that mvc is resolved to the 'root' path i.e. '/'. If not, check what is servlet path for the dispatcher and add that to your url (on the client side). This would explain why you get 404.
And also, check that you can call your API directly in the browser to rule out the server-side errors as user Chandermani suggested.

Trying to pass a list from servlet to jsp but prints null

I am trying to pass an ArrayList of objects from a servlet to a jsp file but when I try printing it, it prints nothing. I used the exact lines from a similar post for the jsp...can someone help me because I have never used a jsp before.
The idea is to to traverse through an xml file using dom parser and then print its elements to an html table of a specific form. My java code successfully collects all the elements and stores them in a list which I want to pass in the jsp to format in the table asked...
SERVLET CODE (with missing pieces cause it's huge) :
import all the needed libraries
public class MyServlet extends HttpServlet {
private static xml_obj obj = null;
public static ArrayList<xml_obj> objList = new ArrayList<xml_obj>();
public static void main(String[] args){
try {
Start(); //starting the methods for the xml traversal and creates the list
//System.out.println("AA"+objList.get(1).getName());
}
catch(Exception e) {
e.getMessage();
}
}
public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
ArrayList list = getList();
//System.out.println(objList.get(1).getName());
request.setAttribute ("Xml_objList", objList );
RequestDispatcher view = request.getRequestDispatcher("DomNav.jsp");
view.forward (request,response);
}
static void Start(){
/*..........code missing.............*/
myDOMTreeProc dtp = new myDOMTreeProc();
dtp.processLvl(ListOfCh, 0); //processLvl -> method in myDOMTreeProc
}
public static ArrayList<xml_obj> getList() {
return objList;
}
}
class myDOMTreeProc {
/*........DOM XML TRAVERSE.......*/
}
class attribute {
private String Name;
private String Value;
/*.............setters/getters.......*/
}
class xml_obj {
public int Lvl;
private String Name;
private String Value;
private String Parent;
private ArrayList<attribute> attributes=null;
/*.............setters/getters.......*/
}
JSP CODE:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Expression Language Example</title>
</head>
<body>
<h1>TEST JSP</h1>
<% ArrayList list = (ArrayList) request.getAttribute("Xml_objList"); %>
<c:forEach var="item" items="${Xml_objList}">
${item.Lvl}
</c:forEach>
</body>
</html>
The list is correct I tested it. I think the problem is when I pass it in the jsp.
Follow Java Naming convention and everything will work fine. Just replace int Lvl with int lvl;
JSP:
<c:forEach var="item" items="${Xml_objList}">
${item.lvl}
</c:forEach>
Instead of ${item.lvl} you can try with ${item.getLvl()} or ${item['lvl']}

How do you query a database from JSP Form Data?

I am in need of assistance. I am trying to write a basic form that populates a drop-down list and based on what you select, it queries the database. However, I cannot get it to do it, It just receives all the queries. I am at a loss so if you have any helpful advice or helpful links, that'd be great. I really need to learn Spring MVC, and Hibernate combined. thanks!
HomeController Code: (This controller populates the list)
/**
* Handles requests for the application home page.
*/
#Controller
public class SearchController {
#Autowired
FilmBo filmBo;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, ModelMap model) {
Selection selection = new Selection();
model.addAttribute("selection", selection);
return "search";
}
#ModelAttribute("categoryList")
public List<String> populateList(){
List<String> categoryList = filmBo.searchByCategory("");
return categoryList;
}
}
Here is the MainController that the form upon submit gets sent to:
public class FilmController {
private static final Logger logger = LoggerFactory.getLogger(SearchController.class);
#Autowired
FilmBo filmBo;
#RequestMapping(value = "/films", method = RequestMethod.GET)
public String home(Locale locale, Model model, #RequestParam(value="title",required=false) String title,
#RequestParam(value="category",required=false) String category) {
logger.info("Welcome home! The client locale is {}.", locale);
List<Film> filmList = filmBo.searchByTitle(title);
logger.info("filmList: " + filmList);
model.addAttribute("filmList", filmList);
List<String> filmCategory = filmBo.searchByCategory(category);
logger.info("filmCategory: " + filmCategory);
model.addAttribute("filmCategory",filmCategory);
return "films";
}
}
Here is my jsp page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page session="false"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="form">
<form:form action="${pageContext.request.contextPath}/films"
method="GET" commandName="selection">
Film Title<input type="text" name="title">
<br>
Select a Film Category:<br>
<form:select path="selection">
<form:option value="NONE" label="--- Select ---" />
<form:options name="category" items="${categoryList}" />
</form:select>
<button name="submit" type="submit">Submit Name</button>
</form:form>
</div>
</body>
</html>

Categories

Resources