Spring MultipartResolver is not configured - spring

I want to upload files to a folder in my project. But when I select a file and click the upload button I get the following error:
HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?
This is my MultipartResolver bean:
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="10000000"/>
</beans:bean>
This is my Controller:
#Controller
public class UploadController {
private String folderTujuanUpload="/uploads";
private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);
#RequestMapping(value = "/upload/form",method = RequestMethod.GET)
public void tampilkanFormUpload(){}
#RequestMapping(value = "/upload/form",method = RequestMethod.POST)
public String prosesFormUpload(HttpSession session, #RequestParam("filegambar") MultipartFile hasilUpload) throws IOException{
String lokasiUpload = tujuanUpload(session).getAbsolutePath();
LOGGER.debug("name File [{}]",hasilUpload.getName());
LOGGER.debug("Size File [{}]",hasilUpload.getSize());
LOGGER.debug("Type File [{}]",hasilUpload.getContentType());
File tujuan = new File(lokasiUpload + File.separator + hasilUpload.getOriginalFilename());
try{
hasilUpload.transferTo(tujuan);
}catch (Exception ex) {
LOGGER.error("cant upload file");
LOGGER.error("Penyebab : {}", ex.getMessage());
}
return "redirect:list";
}
#RequestMapping(value = "/upload/list")
public ModelMap tampilkanhasilUpload(){
ModelMap mm=new ModelMap();
return mm;
}
private File tujuanUpload(HttpSession session){
String lokasiFullPath = session.getServletContext().getRealPath(folderTujuanUpload);
LOGGER.debug("lokasi full path : [{}]",lokasiFullPath);
File hasil = new File(lokasiFullPath);
if (!hasil.exists())
{
LOGGER.debug("lokasiblabla");
hasil.mkdirs();
}
return hasil;
}
}
And this are the jsp pages i have:
form.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>form upload</h1>
<form method="POST" enctype="multipart/form-data">
<table border="0">
<tbody>
<tr>
<td>pilla palla </td>
<td>
<input type="file" name="filegambar">
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="Üpload">
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
list.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>upload</title>
</head>
<body>
<h1>hassandsjaiadsf upload</h1>
</body>
</html>

Related

Why is the string not added to the property via Model.addObject?

I created #ControllerAdvice to handle BindException:
#ControllerAdvice
class globalControllerAdvice {
#ExceptionHandler(BindException.class)
public ModelAndView handleMyException(HttpServletRequest req, Exception e) {
ModelAndView model = new ModelAndView();
model.addObject("myerror",e.getErrCode());
model.addObject("message",e.getMessage());
model.addObject("exception","bind exception");
model.setViewName("error");
return model;
}
}
And created error.html :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
table td{
vertical-align:top;
border:solid 1px #888;
padding:10px;
}
</style>
</head>
<body>
<h1>Error Page</h1>
<table>
<tr>
<td>Error</td>
<td th:text="${myerror}"/>
</tr>
<tr>
<td>Message</td>
<td th:text="${message}"/>
</tr>
<tr>
<td>Exception</td>
<td th:text="${exception}"/>
</tr>
</table>
</body>
</html>
And when executing, when I make a mistake on purpose, the page appears normally,but the properties are not filled in .That is, a table is created, but the text "${myerror}" , "${message}" , "${exception}" are not filled in with e.getErrCode() , e.getMessage() ,
"bind exception". Can anyone tell me what the problem is? thanks

use Thymleaf and spring met org.springframework.web.method.annotation.MethodArgumentTypeMismatchException

I am running a springboot demo,integrated with Thymleaf.But it keep throwing the following exeption:
WARN 25302 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved
[org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type
'java.lang.Long'; nested exception is java.lang.NumberFormatException:
For input string: "form.html"]**
controller:
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserRepository userRepository;
private List<User> getUserlist() {
return userRepository.listUser();
}
#GetMapping
public ModelAndView list(Model model) {
model.addAttribute("userList", getUserlist());
model.addAttribute("title", "user management");
return new ModelAndView("users/list", "userModel", model);
}
#GetMapping("/form")
public ModelAndView createForm(Model model) {
User user=new User();
user=userRepository.saveOrUpateUser(user);
model.addAttribute("user", user);
model.addAttribute("title", "create user");
return new ModelAndView("users/form", "userModel", model);
}
list.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title th:text="${userModel.title}">welcome</title>
</head>
<body>
<div th:replace="~{fragments/header :: header}">...</div>
<h3 th:text="${userModel.title}">Welcome to baidu.com</h3>
<div>
create user
</div>
<table border="1">
<thead>
<tr>
<td>ID</td>
<td>Age</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<tr th:if="${userModel.userList.size()} eq 0">
<td colspan="3">no user info!!</td>
</tr>
<tr th:each="user : ${userModel.userList}">
<td th:text="${user.id}">1</td>
<td th:text="${user.age}">11</td>
<td><a href="view.html" th:href="#{'/users/' + ${user.id}}"
th:text="${user.name}">waylau</a></td>
</tr>
</tbody>
</table>
<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>
form.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title th:text="${userModel.title}">users : View</title>
</head>s
<body>
<div th:replace="~{fragments/header :: header}">...</div>
<h3 th:text="${userModel.title}">Welcome to baidu.com</h3>
<div>
back to home
</div>
<form action="/users" method="POST" th:object="${userModel.user}">
<input type="hidden" name="id" th:value="*{id}">
名称:<br>
<input type="text" name="name" th:value="*{name}">
<br>
年龄:<br>
<input type="text" name="age" th:value="*{age}">
<input type="submit" value="提交">
</form>
<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>
User.java
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement // mediatype 转为xml
public class User {
private long id; // 用户的唯一标识
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
....getter and setter
}
on the home page,everything goes fine,except the create user anchor which should return a form to fill.
any idea?

Search page in spring mvc doesn't work

I Have created simple mvc CRUD. All works fine except search page.
Im getting errorr as follows:
HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
Controller page is:
#RequestMapping(value="/search")
public ModelAndView search(){
return new ModelAndView("search","command", new Emp());
}
#RequestMapping(value="/jsp/searchemp",method = RequestMethod.POST)
public ModelAndView search1(#ModelAttribute("name") Emp emp){
String name = null;
name = dao.searchname(name);
return new ModelAndView("searchemp","name",name);
}
Search.jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>z
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
label {
text-align: right;
clear: both;
float:left;
margin-right:15px;
}
.box{background-color: #e1e8f0;}
body{background:#f0eceb;}
</style>
</head>
<body>
<div style=" left: 30%; top: 25%; position: absolute;">
<div class="col-sm-12 col-sm-offset-3 box " >
<center> <h1>Add New Employee</h1> </center>
<form method="post" action="jsp/searchemp/" >
<div class="form-group"> <div class="col-xs-7">
<label ><h5>Name :</h5></label>
<input name="name" class="form-control" placeholder="Enter Name of the employee" />
<button type="submit" value="Save" class="btn btn-primary btn-lg">Search</button>
</div></div>
</form>
</div>
</div>
</body>
</head>
Searchemp.jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Employees List</h1>
<table class="table table-hover" border="1" width="70%" cellpadding="2">
<thead>
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit</th><th>Delete</th></tr></thead>
<tbody><tr>
<td>${String.id}</td>
<td>${String.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td>Edit</td>
<td>Delete</td>
</tr> </tbody>
</table>
<br/>
Add New Employee
jdbctemplate query:
public String searchname(String name) {
String query = "select * from Emp99 where name=?";
Object[] inputs = new Object[] {name};
String empName = template.queryForObject(query, inputs, String.class);
return empName;
}
Dont know what goes wrong.
help me.
in order for jsp to consume an bean , your controller method should return data,in your jsp you are trying to utilize
{String.id} and {emp.id} which is never passed from the controller method search1.so you need to add your beans to a model and
return the page like this.
#RequestMapping(value="/jsp/searchemp",method = RequestMethod.POST)
public String search1(#ModelAttribute("name") Emp emp,Model model){
model.addAttribute("emp",emp); //passing the model name and the bean ,
//model.addAttribute("name",anotherBean); //you can add many attributes as you wish.
return "searchemp";
}
now inside the searchemp.jsp you can utilize the emp bean like this.
{emp.id}
remove the {String.id} part. inside the searchemp.jsp which will not work.

Spring MVC : Jsp file does not display data from the controller

This is my controller code
#RequestMapping(value="/testMvc")
public String testero(Model model ){
String nameClient="HENOCKE";
Long CodeClient=2L;
String Address="LONDO Street";
System.out.println("****End and outputting to Jsp page: ****");
return "rs";
}
And as you can see i want to display data to my jsp files and this is my jsp file:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" charset=UTF-8>
<title>Banque </title>
<link rel="stylesheet" type="text/css"
href="<%=request.getContextPath()%>/resources/CSS/style1.css">
</head>
<body>
<h2>Date Loaded from My controller....</h2>
<table>
<tr>
<th>Name : </th> <th><c:out value="${nameClient}"/></th>
</tr>
<tr>
<th>id Client: </th> <th> <c:out value=" ${CodeClient}" /> </th>
</tr>
<tr>
<th>Adress client: </th> <th> <c:out value="${Address}" /></th>
</tr>
</table>
</body>
</html>
How can i output data to my jsp? here rs is the Name of my Jsp file
You need to add the attributes to the model.
String nameClient = "Whatever";
model.addAttribute("nameClient",nameClient);
Read this:
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html
You should create ModelAndView object to put values to view:
#RequestMapping(value="/testMvc")
public ModelAndView testero(){
ModelAndView mov = new ModelAndView("rs");
mov.addAttribute("nameClient", "HENOCKE");
mov.addAttribute("CodeClient", 2L);
mov.addAttribute("Address", "LONDO Street");
System.out.println("****End and outputting to Jsp page: ****");
return mov;
}

Flash attributes and ResourceBundleViewResolver

I am facing an issue with the flash attributes which I have not able to retrieve it in the GET phase of POST/redirect/GET scenario. This is only happening when I use the ResourceBundleViewResolver.
view resolver
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="spring-views" /> </bean>
view properties
form.(class)=org.springframework.web.servlet.view.JstlView
form.url=/WEB-INF/pages/form.jsp
home.(class)=org.springframework.web.servlet.view.JstlView
home.url=/WEB-INF/pages/home.jsp
home_redirect.(class)=org.springframework.web.servlet.view.RedirectView
home_redirect.url=home
form.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<form action="register" method="post">
Name: <input type="text" name="name"/> <br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h2> ${status} </h2>
</body>
</html>
so in this page, home.jsp, the status should contain the value set as the flash attribute.
controller
#Controller
public class WebController {
#RequestMapping(value="/form", method=RequestMethod.GET)
public String showFormPage(){
return "form";
}
#RequestMapping(value="/register", method=RequestMethod.POST)
public ModelAndView login(#RequestParam("name") String name, RedirectAttributes flashMap){
System.out.println("name = " + name);
flashMap.addFlashAttribute("status", "Registered successfully");
//return new RedirectView("home"); -- with this returned its working
return new ModelAndView("home_redirect"); //-- with this returned its not working
//return "redirect:home"; // -- not working
}
#RequestMapping(value="/home")
public String showHomePage(){
return "home";
}
}
on the whole this is the observation made:
if used resource bundle view resolver
return view names as string - not working
return ModelAndView - not working
return RedirectAndView - working
if used internal view resolver
return view names as string - working
2 return modelandview - cannot be used to redirect
return RedirectAndView - working

Resources