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...
Related
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);
}
}
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
Hello I am facing the 'HTTP Status 405 - Request method 'POST' not supported'
exception when trying to do login using spring security.
Following is my code :
pgLogin.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
<script type="text/javascript">
function focusOnLoad() {
document.getElementById("username").focus();
}
</script>
</head>
<body onload="focusOnLoad()">
<div align="center">
<c:if test="${not empty error}">
<div>
<p style="color: red;">${error}</p>
</div>
</c:if>
<c:if test="${not empty message}">
<div>
<p style="color: red;">${message}</p>
</div>
</c:if>
<c:url var="loginUrl" value="/login" />
<form action="${loginUrl}" method="post">
<div>
<table>
<tr>
<td><label for="username">Email</label></td>
<td><input type="text" id="username" name="email" placeholder="Enter Email" required></td>
</tr>
<tr>
<td><label for="password">Password</label></td>
<td><input type="password" id="password" name="password" placeholder="Enter Password" required></td>
</tr>
</table>
</div>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<div>
<input type="submit" value="Log In">
</div>
</form>
</div>
</body>
</html>
DesertLampSecurityConfiguration.java
package co.in.desertlamp.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class DesertLampSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
authenticationMgr.inMemoryAuthentication()
.withUser("subodh.ranadive#desertlamp.com")
.password("Dlpl123#")
.authorities("ROLE_SUPER_USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/home").access("hasRole('ROLE_SUPER_USER')")
.and()
.formLogin().loginPage("/loginPage")
.defaultSuccessUrl("/homePage")
.failureUrl("/loginPage?error")
.usernameParameter("email").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/loginPage?logout");
}
}
DefaultController.java
package co.in.desertlamp.controller;
import org.springframework.stereotype.Controller;
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;
#Controller
public class DefaultController {
#RequestMapping(value = { "/"}, method = RequestMethod.GET)
public ModelAndView welcomePage() {
ModelAndView model = new ModelAndView();
model.setViewName("common/pgDefault");
return model;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView loginPage(#RequestParam(value = "error",required = false) String error) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid Email OR Password");
}
model.setViewName("common/pgLogin");
return model;
}
#RequestMapping(value = { "/home"}, method = RequestMethod.GET)
public ModelAndView homePage() {
ModelAndView model = new ModelAndView();
model.setViewName("common/pgWelcome");
return model;
}
}
Change your config as following to match your method handlers:
...
.formLogin().loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error")
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>
// 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";
}
}