Spring Mvc 4 - <form:errors/> Not Working - java

I am new to Spring MVC
I am using in my application & it is not showing error along with field.
Please look into the following code
Employee.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# 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=UTF-8">
<title>Zaptech</title>
</head>
<body>
<form action="save">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
<td><form:errors path="name"></form:errors></td>
</tr>
<tr>
<td>Blood Group</td>
<td><input type="text" name="bloodGroup" id="bloodGroup"></td>
<td><form:errors path="bloodGroup"></form:errors></td>
</tr>
<tr>
<td><input type="submit" value="Save"></td>
</tr>
</table>
</form>
</body>
</html>
EmployeeController.java
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jagir.hrm.Validator.EmployeeValidator;
import com.jagir.hrm.model.Employee;
import com.jagir.hrm.service.EmployeeService;
#Controller
public class EmployeeController
{
#Autowired
EmployeeService empService;
#Autowired
EmployeeValidator empValidator;
#RequestMapping(value="/")
public String homePage()
{
System.out.println("Inside intel");
return "employee";
}
#RequestMapping(value="employee")
public String showEmployee()
{
return "employee";
}
#RequestMapping(value="save")
public String saveEmployee(#ModelAttribute("command") #Validated Employee e , BindingResult result) throws IOException
{
System.out.println("Inside employee :: " + e.getName());
//throw new IOException("Excption");
System.out.println(result);
empValidator.validate(e, result);
System.out.println(result);
System.out.println(result.hasErrors());
if(result.hasErrors())
{
System.out.println("Error has occured");
}
else
{
System.out.println("No Errors continue to save records");
empService.saveEmployee(e);
}
return "employee";
}
}
EmployeeValidator.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.jagir.hrm.model.Employee;
import com.jagir.hrm.service.EmployeeService;
#Component
public class EmployeeValidator implements Validator
{
#Autowired
EmployeeService employeeService;
public boolean supports(Class<?> clazz)
{
return Employee.class.equals(clazz);
}
public void validate(Object target, Errors errors)
{
System.out.println("validation of objects");
Employee employee = (Employee) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "employee.name.notempty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bloodGroup", "employee.bloodGroup.size");
if(employee.getBloodGroup().length()>=2)
{
System.out.println("Inside blood groups");
errors.rejectValue("bloodGroup", "employee.bloodGroup.size");
}
}
}
If i input proper values then it working properly and goes to database but,
When i input 5 characters in blood group it throws error which i can see in console but in my web page i am not able to see error along with blood group field.

Employee.jsp uses plain HTML form element + Spring form:errors tag.
form:errors tag is supposed to be used inside form:form tag (or spring:bind tag to be precise).
Try to use form:form tag and see how it works. I also suggest to use form:input instead of plain HTML input.
<form:form modelAttribute="command" action="save"
...
<form:input path="name"/>
<form:errors path="name"/>
...
</form>

Related

view not display data in table using mysql spring mvc and jpa

i am follwing this tutorial https://www.codejava.net/frameworks/spring/spring-mvc-spring-data-jpa-hibernate-crud-example . I successfully save data into database using jpa but it not disply on index.jsp, index page show normal html tags data but not retrieving data from database. Please have a look into my code.
index.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page isELIgnored="false" %>
<html>
<head>
</head>
<title>
Student Manager
</title>
<body>
<div align="center">
<h1>Student Manager</h1>
<form method="get" action="search">
<input type="text" name="keyword"/>
<input type="submit" name="search"/>
</form>
<h2>Add new Student</h2>
<table border="1" cellpadding="5">
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Qualification</th>
<th>Mobile</th>
<th>Action</th>
</tr>
<c:forEach items="${ModelList}" var="listStudent">
<tr>
<td>${listStudent.id} </td>
<td>${listStudent.name} </td>
<td>${listStudent.age} </td>
<td>${listStudent.qualification} </td>
<td>${listStudent.mobile} </td>
<td>
Edit
Delete
</td>
</tr></c:forEach>
</table>
</div>
</body>
</html>
controller
package com.uc.student;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class StudentController {
#Autowired
private StudentService studentservice;
#RequestMapping("/")
public ModelAndView home() {
List<Student> list=studentservice.listAll();
ModelAndView model=new ModelAndView();
model.addObject("ModelList",list);
return model;
}
#RequestMapping("/new")
public String newStudentForm(Map<String,Object> model) {
Student student=new Student();
model.put("student",student);
return "new_student";
}
#RequestMapping(value="/save", method=RequestMethod.POST)
public String saveStudent(#ModelAttribute("student") Student student) {
studentservice.save(student);
return "redirect:/";
}
}
new_student.jsp
<%# 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" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add new Student</title>
</head>
<body>
<h2>Add New Student</h2>
<br>
<div align="center">
<form:form method="post" action="save" modelAttribute="student">
<table>
<tr><td>Name : <form:input path="name"/></td></tr>
<tr><td>Age : <form:input path="age"/></td></tr>
<tr><td>Qualification : <form:input path="qualification"/></td></tr>
<tr><td>Mobile : <form:input path="mobile"/></td></tr>
<tr><td><input type="submit" value="save"/></td></tr>
</table>
</form:form>
</div>
</body>
</html>
StudentService .java
package com.uc.student;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class StudentService {
#Autowired StudentRepository repo;
public void save(Student student) {
repo.save(student);
}
public List<Student> listAll(){
return (List<Student>)repo.findAll();
}
public Student getById(Long id) {
return repo.findById(id).get();
}
public void delete(Long id) {
repo.deleteById(id);
}
}

Successful login with Custom login page in spring boot starter security not getting to next page

I have been studying spring boot. When using spring-boot-starter-security for a todo application,I tried to login with custom user id and password and custom login page.When I tried login , it is not taking me to next page. Note : user name is required parameter for next page.
I tried using below but after login it again takes me to login page as error
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/", "/*Todo*/**").access("hasRole('USER')").and()
.formLogin().loginPage("/login").permitAll();
}
This is my securityConfig code
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/listTodo").hasAnyRole("USER","ADMIN")
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").permitAll().and()
.logout().permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("Sudhakar").password("qwe123").roles("USER","ADMIN");
}
}
I would need to login with user name and get the todo details of the user who logged in. But I am not able to get to next page, after trying many times I am getting below error
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
Below is my controller
package com.example.SpringLogin.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.example.SpringLogin.service.loginService;
#Controller
#SessionAttributes("name")
public class LoginController {
#Autowired
loginService service;
#RequestMapping(value="/login",method = RequestMethod.POST)
public String loginMessage(ModelMap model,#RequestParam String name,#RequestParam String password) {
boolean isValidUser=service.validateUser(name, password);
if(!isValidUser) {
model.put("message", "Invalid Credentials");
return"Room";
}
model.put("name", name);
model.put("password",password);
return "redirect:/todoList";
}
#RequestMapping(value="/login",method = RequestMethod.GET)
public String roomLogin(ModelMap model, String error) {
//model.put("name", name);
if(error!=null) {
model.addAttribute("errorMsg","UserName or Password is invalid");
}
return "Room";
}
/*#RequestMapping(value="/login",method = RequestMethod.GET)
public String showLogin(ModelMap model) {
//model.put("name", name);
return "Welcome";
}*/
#RequestMapping(value = "/welcome")
public String showWelcome(ModelMap model) {
return "login";
}
}
My login page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="contextPath" value=""/>
<!DOCTYPE html>
<html>
<head>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<title>Todo Application</title>
</head>
<body>
<div class="container">
<font color="red">${message}</font>
<form:form method="post" action="/login">
<fieldset class="form-group">
Name : <input type="text" name="username" class="form-control" placeholder="Username"
autofocus="true"/>
Password: <input type="password" name="password"
class="form-control" placeholder="Password" />
</fieldset>
<button type="submit" class="btn btn-success">Submit</button>
</form:form>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
After successful login it should go to below page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="contextPath" value=""/>
<!DOCTYPE html>
<html>
<head>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<title>Todo Application</title>
</head>
<body>
<div class="container">
<table class="table table-striped">
<H1>Name : ${pageContext.request.userPrincipal.name}</H1>
<thead>
<tr>
<th>Id</th>
<th>Course</th>
<th>End Date</th>
<th>Is it Done</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<c:forEach items="${todo}" var="item">
<tr>
<td>${item.id}</td>
<td>${item.course}</td>
<td><fmt:formatDate value="${item.date}" pattern="MM/dd/yyyy" /></td>
<td>${item.isdone?'Yes':'No'}</td>
<td><a type="button" class="btn btn-success"
href="/update-Todo?id=${item.id}">Update</a></td>
<td><a type="button" class="btn btn-warning"
href="/delete-Todo?id=${item.id}">Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<div>
<a type="button" href="/add-Todo" class="btn btn-success">Add a
Todo</a>
</div>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
Service class
package com.example.SpringLogin.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Service;
import com.example.SpringLogin.model.todoList;
#Service
public class TodoService {
public static List<todoList> todos=new ArrayList<todoList>();
public static int todoCount=5;
static {
todos.add(new todoList(1, "Sudhakar", "Study history", new Date(), false));
todos.add(new todoList(2,"Sudhakar","Study geography",new Date(),false));
todos.add(new todoList(3,"Sudhakar","Study GK",new Date(),false));
todos.add(new todoList(4,"Mani","Study Java",new Date(),false));
todos.add(new todoList(5,"Mani","Study script",new Date(),false));
}
public List<todoList> retrievetodos(String name){
List<todoList> retrieved=new ArrayList<todoList>();
for (todoList todo : todos) {
if(todo.getName().equalsIgnoreCase(name)) {
retrieved.add(todo);
}
}
return retrieved;
}
public void addTodo(String name,String Course,Date date,boolean isDone) {
todos.add(new todoList(++todoCount,name,Course,date,isDone));
}
public todoList retrieveTodo(int id){
for (todoList todo : todos) {
if(todo.getId()==id) {
return todo;
}
}
return null;
}
public List<todoList> UpdateTodo(todoList todo){
/*for (todoList td : todos) {
if(td.getId()==todo.getId()) {
td.setCourse(todo.getCourse());
td.setDate(todo.getDate());
}
}*/
todos.remove(todo);
todos.add(todo);
return todos;
}
//it will delete the todo
public void deleteTodo(int id) {
Iterator<todoList> it = todos.iterator();
while(it.hasNext()){
todoList td=it.next();
if(td.getId()==id) {
it.remove();
}
}
}
}
my expectation is to login application using user name and get the todolist of the user
Try adding a loginProcessUrl and a defaultSuccessUrl. Something like this:
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/do_login")
.defaultSuccessUrl("/index")
index in this example is the page you want to be taken to upon successful login.
Use this one
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/homepage.html", true)

Search field in java webpage to list result of mysql database in the web page

Hi I am very much new to java coding, by going through few online tutorials I was able to write a small project in spring mvc, I am trying to build a webapplication where I can store some applications repository like application name, host name (where it is running), application type, environment type (DEV, TEST, QA, PROD) into mysql table and fetch the same information to a webpage in form of tables. I was successful to achieve till this part but got stuck in the next step which is having a search field on the top of the table displayed in the webpage (table information fetched from mysql db ) where if we enter a keyword or any text it should search the db and fetch the result in the table (samepage).
This is what I have now
enter image description here
jsp page which displays the table
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# include file="/WEB-INF/jsp/includes.jsp" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE>
<html>
<head>
<link type="text/css" rel="stylesheet" href="<c:url value="resources/style.css" />" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Client Management</title>
</head>
<body>
<h1>Client Data</h1>
<div >
<form:form method="POST" commandName="client">
<table class="myTable myTable-zebra myTable-horizontal">
<thead>
<tr>
<th>Application Name</th>
<th>Client Type</th>
<th>Client Name</th>
<th>Hostname</th>
<th>Environment</th>
</tr>
</thead>
<c:forEach items="${clientList}" var="client">
<tr>
<td>${client.applicationname}</td>
<td>${client.clienttype}</td>
<td>${client.clientname}</td>
<td>${client.hostname}</td>
<td>${client.envtype}</td>
</tr>
</c:forEach>
</tbody>
</table>
</form:form>
</div>
</body>
</html>
Controller
package com.webappdemo01.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.webappdemo01.model.Client;
import com.webappdemo01.service.ClientService;
#Controller
public class ClientController {
#Autowired
private ClientService clientService;
#RequestMapping(value = "/AdminPage", method = RequestMethod.GET)
public String adminpage() {
return "AdminPage";
}
#RequestMapping("/addclient")
public String setupForm(Map<String, Object> map){
Client client = new Client();
map.put("client", client);
map.put("clientList", clientService.getAllClient());
return "client";
}
#RequestMapping(value="/client.do", method=RequestMethod.POST)
public String doActions(#ModelAttribute Client client, BindingResult result, #RequestParam String action, Map<String, Object> map){
Client clientResult = new Client();
switch(action.toLowerCase()){
case "add":
clientService.add(client);
clientResult = client;
break;
case "edit":
clientService.edit(client);
clientResult = client;
break;
case "delete":
clientService.delete(client.getClientname());
clientResult = new Client();
break;
case "search":
Client searchedClient = clientService.getClient(client.getClientname());
clientResult = searchedClient!=null ? searchedClient : new Client();
break;
}
map.put("client", clientResult);
return "ClientAddSuccess";
}
#RequestMapping("/clientlist")
public String clientPage(Map<String, Object> map){
Client client = new Client();
map.put("client", client);
map.put("clientList", clientService.getAllClient());
return "clientlist";
}
}
Now I want to have search field on the top to fetch the result from db and display in the same table on the webpage.
Without refreshing the page you can use javascript to make an ajax call to your controller for each word they are entering in your page and display the result

Springs 3.6.4 +form bindingerror

// type Exception report
message java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'test' available as request attribute
description The server encountered an internal error that prevented it from fulfilling this request.
HomeController.java
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/** Handles requests for the application home page. */
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/** Simply selects the home view to render by returning its name. */
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model, Locale locale) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
}
HomeModel.java
package com.test.app;
public class HomeModel {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
HometController.java
package com.test.app;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HometController {
#RequestMapping(value = "/try", method = RequestMethod.POST)
public String trynew(#ModelAttribute("test") HomeModel hm, BindingResult br, Model model) {
model.addAttribute("test", new HomeModel());
System.out.println("in try");
return "tst";
}
}
home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
</body>
<form:form method="POST" modelAttribute="test" name="test" action="try">
<form:input path="name"/>
<input type="submit" value="test"/>
</form:form>
<!-- onClick="document.test.submit()" -->
</html>
tst.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello World with Spring 3 MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
</head>
<body>
<h1>Registration Form</h1><br />
<form:form commandName="USER">
<table>
<form:errors path="*" cssStyle="color : red;"/>
<tr><td>Name : </td><td><form:input path="name" /></td></tr>
<tr><td colspan="2"><input type="submit" value="Save Changes" /></td></tr>
</table>
</form:form>
</body>
</html>
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'test' available as request attribute
remove this parameter #ModelAttribute("test") HomeModel hm to get rid of your exception
#Controller
public class HometController {
#RequestMapping(value = "/try", method = RequestMethod.POST)
public String trynew( BindingResult br, Model model) {
model.addAttribute("test", new HomeModel());
System.out.println("in try");
return "tst";
}
}

Upload/Download File using REST or Web Services

Is it possible to Upload/Download a file using REST or any other Web Service and send HTML code?
This has to be possible using: PHP, Java or ASP.
I think this will be helpful. At least when it comes to Java. Actualy, have a look at whole tutorial
Here is an example how to do it by using Spring:
Add commons-io and commons-fileupload dependencies to your pom.xml. Configure multipart resolver in your servlet context xml file:
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="10000000" />
</beans:bean>
This will be your JSP for upload of files (i.e. fileUpload.jsp):
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" 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=ISO-8859-1">
<title></title>
</head>
<body>
<form:form method="post" commandName="upload" action="uploadNewFile"
enctype="multipart/form-data">
<table class="table table-bordered">
<tbody>
<tr>
<td><label>File</label></td>
<td><input class="form-control" name="file" type="file"
id="file" /></td>
</tr>
<tr>
<td colspan="2"><input class="btn btn-primary" type="submit"
value="Upload" /></td>
</tr>
</tbody>
</table>
</form:form>
</body>
</html>
And this is controller:
import java.io.IOException;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class UploadController {
// Show page for upload
#RequestMapping(value = "/fileUpload", method = RequestMethod.GET)
public ModelAndView showUploadFilePage() {
return new ModelAndView("fileUpload", "upload", null);
}
// Get multipart file and save it
#RequestMapping(value = "/uploadNewFile", method = RequestMethod.POST)
public String save(#RequestParam("file") MultipartFile file) {
// Save it to i.e. database
// dao.save(file);
return "fileUpload";
}
// Downloads file. I.e. JPG image
#RequestMapping(value = "/download/{id}", produces = MediaType.IMAGE_JPEG_VALUE)
public #ResponseBody HttpEntity<byte[]> getFile(
#PathVariable("id") Integer id) throws IOException {
byte[] file= dao.get(id).getImage();
HttpHeaders header = new HttpHeaders();
header.set("Content-Disposition", "attachment; filename=Image");
header.setContentLength(file.length);
return new HttpEntity<byte[]>(file, header);
}
}
Yes...its possible.
It depends on the implementation on the server side though.
But if you just want an answer....its YES
http://blogs.msdn.com/b/uksharepoint/archive/2013/04/20/uploading-files-using-the-rest-api-and-client-side-techniques.aspx
yes its possible, need to use correct mimetype to achieve this. you can pass the string in response body if your using Rest...

Categories

Resources