Args with Spring MVC - spring

I need help to pars args in a method inside my controller.
i have a form for sending my parameter to function
<form method="post" action="/">
<input type="text" id="query" placeholder="file to search ...">
<input type="submit" id="submit" value="fetch!">
</form>
and in my controller :
#RestController
public class mainController {
#RequestMapping(value = "/index", method = RequestMethod.POST)
public String index(Model model) throws IOException, GeneralSecurityException {
DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
model.addAttribute("query");
String res = drive.checkFile("query");
return res;
the query is a string send via the form. and return res in the same view.
Do you have any tips?
thanks you very mutch

In Spring MVC It will be like this:
#Controller
public class mainController {
#PostMapping( "/index")
public String index(#ModelAttribute FormDataObjectClass object) throws IOException, GeneralSecurityException {
DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
//model.addAttribute("query");
String name = object.getName();
String address = object.getAddress();
String res = drive.checkFile("query");
return res;
}
Here no need of passing Model as argument as we need a custom Object(FormDataObjectClass) to be used.
Create a class FormDataObjectClass as per you data in HTML form/JQuery post method

Related

NullPointException while uploading file in spring

I try to upload a .csv file's data into database, but when i upload and submit it, it throws nullpointexception. Means, when I print name in controller, name is printed, but when i try to get the file, it show null.
FileUpload model class
public class FileUpload {
private CommonsMultipartFile[] files;
private String name;
// Getters and setters
}
Controller
#RequestMapping(value = "uploadPage", method = RequestMethod.GET)
public ModelAndView uploadPage() {
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) throws IOException, JAXBException {
System.out.println("myfirl "+fileUpload.getFiles()); // output is null
System.out.println("name "+fileUpload.getName()); // name is displaying
//other stuffs
}
upload_page
<spring:url value="/doUpload" var="doUploadURL"/>
<form:form method="post" modelAttribute="formUpload" action="${doUploadURL }" enctype="multipart/form-data">
<form:input path="files" type="file" multiple="multiple"/>
<form:input path="name" type="text"/>
<button type="submit">Upload</button>
</form:form>
WebConfig
#Bean(name="multipartResolver")
public CommonsMultipartResolver getResolver(){
CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver();
commonsMultipartResolver.setMaxUploadSizePerFile(20*1024*1024);
return commonsMultipartResolver;
}
I tried to sort it out in many ways, but failed. Anyone try to sort it out? Thanks in advance
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
#ResponseBody
public String uploadFileHandler(#RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
System.out.println(file.getName);
}
}
or you can do that
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFileHandler(MultipartHttpServletRequest request) {
Iterator<String> itr = request.getFileNames();
while (itr.hasNext()){
System.out.println(itr.next().toString());
}
....
}

Spring form binding return null with many-2-one relationship

Here is the problem, when I try to submit form, user entity returns null.
Form is
<form:form class="g-form" modelAttribute="objView" id="userAssignmentForm">
<form:hidden path="id" value="${objView.id}"/>
${objView.user.id}
<div class="g-form-group required">
<label for="user">User</label>
<form:hidden id="user" path="user" value="${objView.user}"/>
<input type="text" value="${objView.user.userName}" readonly="true"/>
<input type="button" class="import-input" onclick="gImport.showImportUserForm()"/>
</div>
Controller is
#RequestMapping(value = "/create", method = RequestMethod.POST)
public #ResponseBody
String create(
#ModelAttribute("objView") UserAssignmentView objView, BindingResult result,
SessionStatus status,
HttpServletRequest request) throws UnsupportedEncodingException {
UserAssignment obj = new UserAssignment();
obj.setUser(objView.getUser());
userAssignmentService.create(obj);
return "ok";
}
Model is below contains a view entity. What am I missing?
public class UserAssignmentView extends UserAssignment {
public UserAssignmentView() {
}
public UserAssignmentView(UserAssignment obj) {
setId(obj.getId());
setStatus(obj.getStatus());
setUser(obj.getUser());
}
}
And this is form view part of controller
#RequestMapping(value = "/form", method = RequestMethod.POST)
public ModelAndView form(HttpServletRequest request) {
UserAssignment obj = new UserAssignment();
Account account = AccountRegistry.getByHttpSession(request.getSession());
ModelAndView modelAndView = new ModelAndView("forms/userAssignmentForm");
modelAndView.addObject("objView", UserAssignmentWrapper.wrap(obj));
return modelAndView;
}
I could not solve since 3 days, how can I set user to userassignment?

Getting CommandBean or form bean object with out #ModelAttribute in spring mvc

I have a requirement of getting commandbean or form bean object into the controller without using #ModelAttribute either from ModelMap or HttpServletRequest or anything else.
My code is:
JSP:
<form:form commandName="user" method="POST"
action="${pageContext.request.contextPath}/user/createUser">
Name:<form:input path="name" />
Password:<form:input path="password" />
<input type="submit"/>
</form:form>
Controller:
#Controller
#RequestMapping("/user")
public class UserController {
#RequestMapping(method = RequestMethod.GET)
public String setupForm(ModelMap model) {
modelMap.addAttribute("user", new User());
return "userRegistration";
}
#RequestMapping(value = "/createUser", method = RequestMethod.POST)
public String createUser(ModelMap model,HttpServletRequest request) {
User user=(User)model.get("user");// Retruns null
//Tried using request object but user object is not available in it.
return "message";
}
}
I tried different ways but nothing worked out.
You can implement a HandlerMethodArgumentResolver to create the bean manually, then (for example) use a WebMvcConfigurerAdapter to declare it. The argument resolvers supportsParameter method should check the expected type of the parameter. After that you can add a parameter in your Controller that is of the desired type.
You can do it by hand like you would do if you did not know the magic of Spring : just the the HttpServletRequest and gets its parameters to feed your User. It could look like :
#RequestMapping(value = "/createUser", method = RequestMethod.POST)
public String createUser(ModelMap model,HttpServletRequest request) {
User user= new User();
String name = request.getParameter("name");
String password = request.getParameter("password");
if (name != null) {
user.setName(name);
}
if (password!= null) {
user.setPassword(password);
}
model.addAttribute("user", user);
//Tried using request object but user object is not available in it.
return "message";
}
Or in a more terse way : user.setName(request.getParameter("name");

Neither BindingResult nor plain target object for bean name 'loginuser' available as request attribute

#Controller
#RequestMapping("Page/Login.do")
public class HomeController
{
#RequestMapping(method = RequestMethod.GET)
protected String showLoginPage(HttpServletRequest req,BindingResult result) throws Exception
{
loginuser lu=new loginuser();
lu.setLoginn("Amit");
System.out.println(lu.getLoginn());
return "Login";
}
}
Above code is ##HomeController.java##
loginuser.java
package Com.Site.Name.Order;
public class loginuser
{
private String Loginn;
public String getLoginn()
{
System.out.println("hi i m in login get");
return Loginn;
}
public void setLoginn(String loginn)
{
System.out.println("I m in Loin set");
Loginn = loginn;
}
}
My JSP PAGE IS
Login.jsp
<form:form action="Login.do" method="post" commandName="loginuser">
<div id="Getin">
<img alt="" src="Image/loginttt.png">
</div>
<div id="login">
</div>
<form:input path="Loginn"/>
<input type="submit" value="LOGIN"/>
</form:form>
You are trying to use a Model attribute (commandName) but there is no such attribute added to the model or request attributes. You need to add it. Also, the BindingResult in your handler makes no sense. Remove it.
#RequestMapping(method = RequestMethod.GET)
protected String showLoginPage(HttpServletRequest req, Model model) throws Exception
{
loginuser lu=new loginuser();
lu.setLoginn("Amit");
System.out.println(lu.getLoginn());
model.addAttribute("loginuser", lu);
return "Login";
}
The Model attributes are added to the request attributes and are therefore available in the jsp.

NullPointer on Multipartfile with Spring MVC

It seems my case is simple, so I'm guessing the problem is stupid. Nonetheless...I don't see it.
I'm trying to accept the upload of a collection of files and have been looking at this article as a guide:
http://viralpatel.net/blogs/spring-mvc-multiple-file-upload-example/
Here's the form upload client side:
<form:form method="post" action="save.html" modelAttribute="uploadArtifact" enctype="multipart/form-data">
<div class="controls" id="artifacts">
<input type="file" id="uploader" class="multi"/>
</div>
<div>
<input type="submit" value="Upload" />
</div>
</form:form>
Here's the Model/Bean code:
public class ArtifactModel {
private List<MultipartFile> artifacts;
public List<MultipartFile> getArtifacts() {
return artifacts;
}
public void setArtifacts(List<MultipartFile> artifacts) {
this.artifacts = artifacts;
}
}
...and the controller code:
#Controller
public class ArtifactController {
private static Log logger = LogFactory.getLog(ArtifactController.class);
// #Autowired
// ArtifactService artifactService;
#RequestMapping(value = "/getUploadDialog", method = RequestMethod.GET)
public String displayForm() {
return "uploadArtifacts";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public void save(
#ModelAttribute("uploadArtifact") ArtifactModel uploadArtifact,
Model map) {
logger.info("Received file upload request with "+uploadArtifact.getArtifacts().size()+" files");
List<MultipartFile> files = uploadArtifact.getArtifacts();
List<String> fileNames = new ArrayList<String>();
if (null != files && files.size() > 0) {
for (MultipartFile multipartFile : files) {
String fileName = multipartFile.getOriginalFilename();
fileNames.add(fileName);
// Handle file content - multipartFile.getInputStream()
logger.info("Received file with filename: " + fileName);
}
}
map.addAttribute("files", fileNames);
}
}
I'm getting a NullPointerException when I attempt to call the getter on the ArtifactModel object which should have come from the uploadArtifact #ModelAttribute parameter...
I've looked in the browser debugger and seen that the client is sending the data...
Suggestions?
I think you're missing an attribute from your file input element.
Try adding:
name='artifacts[0]'

Resources