I can't find the error from .jsp - java

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.

Related

Model Data is not getting transferred to the jsp page

I have designed a Login page using Spring MVC,JPA(Hibernate) and Jsp.
Please find the login.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"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<h2>Login page</h2>
<form:form method="POST" modelAttribute="loginBean" action="showProfile">
<table>
<tr>
<td>UserName :<form:input path="userName"/></td>
</tr>
<tr>
<td>Organization Id :<form:input path="OrgId" /></td>
</tr>
<tr>
<td>Password : <form:input path="password" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
profilePage.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"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<table border="2" width="70%" cellpadding="2">
<tr>
<th>UserName</th>
<th>Password</th>
</tr>
<c:forEach var="staff" items="${staffData}">
<tr>
<td>${staff.userName}</td>
<td>${staff.password}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
LoginController.java:-
#Controller
public class LoginController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showLoginPage(Model model) {
model.addAttribute("loginBean", new LoginBean());
return "login";
}
#RequestMapping(value = "/showProfile", method = RequestMethod.POST)
public ModelAndView redirectToprofile(#ModelAttribute("loginBean") LoginBean loginBean) {
StaffServiceImpl staffServiceImpl = new StaffServiceImpl();
Staff staff = staffServiceImpl.authenticateStaff(loginBean);
if (null != staff) {
return new ModelAndView("redirect:/profilePage","staffData",staff);
}
return new ModelAndView("profileNotFound");
}
#RequestMapping(value = "/profilePage", method = RequestMethod.GET)
public String showProfilePage() {
return "profilePage";
}
After giving the valid details in the Login.jsp page it is redirecting to profilePage.jsp but the data in profilePage.jsp is not correct. Please help me to understand where i am doing the mistake.
The profilePage.jsp is displayed a below:-
UserName Password
${staff.userName} ${staff.password}
The Value of this variable is not getting displayed.
profilePage.jsp : Add isELIgnored="false" in page directive.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
Update your controller with the following :
#Controller
public class LoginController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showLoginPage(Model model) {
model.addAttribute("loginBean", new LoginBean());
return "login";
}
#RequestMapping(value = "/showProfile", method = RequestMethod.POST)
public String redirectToprofile(#ModelAttribute("loginBean") LoginBean loginBean , Model model) {
StaffServiceImpl staffServiceImpl = new StaffServiceImpl();
Staff staff = staffServiceImpl.authenticateStaff(loginBean);
if (null != staff) {
model.addAttribute("staffData",staff);
return "profilePage";
}
return "profileNotFound";
}
the above answer is correct, and this is an explination:
The isELIgnored attribute gives you the ability to disable the evaluation of Expression Language (EL) expressions which has been introduced in JSP 2.0.
The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text.
Source :enter link description here

Spring MVC form submission, populate on the same page

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.

Content-Type not allowed: fileUpload in Struts 2

I am new to Struts 2 and trying to do use fileUpload interceptor. I am attaching all my code layers
Action Class (FileUploadAction):
package com.caveofprogramming.actions;
import java.io.File;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private File fileUpload;
private String fileUploadContentType;
private String fileUploadFileName;
public String getFileUploadContentType() {
return fileUploadContentType;
}
public void setFileUploadContentType(String fileUploadContentType) {
this.fileUploadContentType = fileUploadContentType;
}
public String getFileUploadFileName() {
return fileUploadFileName;
}
public void setFileUploadFileName(String fileUploadFileName) {
this.fileUploadFileName = fileUploadFileName;
}
public File getFileUpload() {
return fileUpload;
}
public void setFileUpload(File fileUpload) {
this.fileUpload = fileUpload;
}
#Action( value = "/fileUpload",
results={#Result(name="success",location="/success.jsp"),
#Result(name="error",location="/error.jsp"),
#Result(name="input",location="/error.jsp")
},
interceptorRefs={
#InterceptorRef(
params={"allowedTypes","image/jpeg,image/jpg,application/zip",
"maximumSize","1024000"},
value="fileUpload"
),
#InterceptorRef("defaultStack"),
#InterceptorRef("validation")
}
)
public String execute(){
try{
return SUCCESS;
} catch(Exception e){
return ERROR;
}
}
public String display() {
return NONE;
}
}
error.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<s:fielderror/>
</body>
</html>
Success.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">
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Success
</body>
</html>
fileUpload.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>
<body>
<h1>Struts 2 <s:file> file upload example</h1>
<s:form method="post" enctype="multipart/form-data" action="fileUpload">
<s:file label="File One" name="fileUpload" />
<s:submit />
</s:form>
</body>
</html>
I am not understanding why I am getting this error
"Content-Type not allowed: fileUpload "photography-104a.jpg" "upload_37fbf440_169b_4687_af65_93c8c967256c_00000000.tmp" image/pjpeg"
Although my uploading file format is .jpg.
You are getting this error probably because you don't allow files with content type image/pjpeg. Use parameter of fileUpload interceptor to define allowed MIME types
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/pjpeg</param>
</interceptor-ref>

Display data from java class in JSP

I am trying to make a web project. My question can I display java properties on the JSP page using JSTL? I am quite new in JSP.
As far I am now , I created the login page which is handled by servlet. What I want to achieve is that user log in with his credentials. And based on the credentials the data are processed on the background and displayed on page. (after login user clicks on page my info and the data are automatically populated). Creating another servlet is not a good option, so I probably need to call the data from the normal class(without needing a form).
Login.jsp
<form action="LoginServlet" method="post">
<table>
<tr><td>Login : </td><td><input type="text" name="login"/></td></tr>
<tr><td>Password :</td><td><input type="password" name="password"/></td></tr>
<tr><td><input type="submit" value="Login"/></td><td></td></tr>
</table>
</form>
LoginServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String login = request.getParameter("login");
String password = request.getParameter("password");
request.setAttribute("login", login);
request.setAttribute("password", password);
LoginService.setPublicID(login);
boolean result = LoginService.Auth(login, password);
System.out.println(result);
if(result==true){
getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
}
else{
response.sendRedirect("login.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
LoginService.java (auth. handler) [i used static publicID because based on this, other stuff is done]
public class LoginService {
public static String publicID;
public static String getPublicID() {
return publicID;
}
public static void setPublicID(String login) {
LoginService.publicID = login;
}
public static boolean Auth(String login, String password){
System.out.println(password);
if(password.equals("gw") && login.equals("servo")){
return true;
}
else
{
return false;
}
}
}
This redirects me to the main.jsp.
<%# 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" %>
<!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>
<h2>Login successful!</h2>
UserInfo
Welcome <c:out value="${login}"/>
</body>
</html>
UserInfoService.java
public class UserInfoService {
static String userName;
static String lastName;
static String mobile;
static String email;
public static String getUserName() {
return userName;
}
public static void setUserName(String userName) {
userName = LoginService.getPublicID();
UserInfoService.userName = userName;
}
public static String getEmail() {
return email;
}
public static void setEmail(String email) {
UserInfoService.email = email;
}
}
And finally.
UserInfo.jsp
<%# 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" %>
<%# page import="org.UserInfo.UserInfoService"%>
<!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>
<c:out value="${UserInfoService.getUserName}"/>
</body>
</html>
But this is always empty. Can you please tell me where I am wrong?
UserInfoService resolves to null, You need to register it as a bean see here
You are not calling the UserInfoService.setUserName() method from anywhere in the code.

Spring mvc replaces quotes with html symbol

However I try to get double quotes into my view spring somehow replaces them, here is what I've tried :
#RequestMapping(value="test", method = RequestMethod.GET)
public ModelAndView test(){
ModelAndView mav = new ModelAndView();
mav.setViewName("test");
Wrapper wp = new Wrapper();
wp.setTestField("$(function() { alert(\"test\"); });");
mav.addObject("testObject", wp);
return mav;
}
Wrapper is custom object with one field testField.
#RequestMapping(value="test", method = RequestMethod.GET)
public ModelAndView test(){
ModelAndView mav = new ModelAndView();
mav.setViewName("test");
mav.addObject("testObject", "$(function() { alert(\"test\"); });");
return mav;
}
And 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"%>
<!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>
<script type="text/javascript">
<c:out value="${requestScope.testObject.testField}"></c:out>
</script>
</body>
</html>
Result is :
<script type="text/javascript">
alert('test');
</script>
I want to get :
<script type="text/javascript">
alert("test");
</script>
That's because <c:out> automatically escapes your content.
To stop it doing that, use
<c:out escapeXml="false" value="${requestScope.testObject.testField}"/>

Categories

Resources