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}"/>
Related
I am new to Spring MVC and Servlets. I am trying to run home() method in controller class SearchController but the output is only from home.jsp file. Statement:
out.println("<h1> this is my response block</h1>");
in not included in the result on browser.
Is there anything that can be done to print the out object statement in the browser with home.jsp file?
package springmvcsearch;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class SearchController {
#RequestMapping("/home")
public String home(HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1> this is my response block</h1>");
return "home";
}
}
This is home.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>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="<c:url value='/resources/css/style.css' />"
rel="stylesheet">
<script src="<c:url value='/resources/js/sample.css' /> "></script>
</head>
<body>
This is home view
</body>
</html>
This is the output on the browser:
out.println() is used in jsp file. So you can edit your home.jsp as follows
<%# 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>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="<c:url value='/resources/css/style.css' />"
rel="stylesheet">
<script src="<c:url value='/resources/js/sample.css' /> "></script>
</head>
<body>
This is home view
<%
out.println("<h1> this is my response block</h1>");
%>
</body>
</html>
If you want to add something for home.jsp via the controller class, you can change your controller class as follows.
package springmvcsearch;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class SearchController {
#RequestMapping("/home")
public String home(HttpServletRequest req,HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String message = "this is my response block";
req.setAttribute("message", message);
return "home";
}
}
Then change your jsp file as follows.
<%# 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>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="<c:url value='/resources/css/style.css' />"
rel="stylesheet">
<script src="<c:url value='/resources/js/sample.css' /> "></script>
</head>
<body>
This is home view
<h1>${message}</h1>
</body>
</html>
For further explanation, go through this link how to message from servlet and display in jsp
I want to pass a data from controller method to jsp page. In doing so, using HttpServletRequest.setAttribute().
Now, I can pass it to the just next jsp page. But, I want to hold that data for few more pages.
In this case, what should I do?
Flow of Data:
Controller method1 --> jsp page1 --> jsp page2 --> jsp page3 --> jsp page4 --> Controller method2
I tried setting attribute in each page but it returns null value, as follows
<% request.setAttribute("accId", request.getAttribute("accountId")); %>
You have to use session in jsp when sending data from one page to another.
A demo to show this.
For example :
Create a DemoController class.
#Controller
public class DemoController {
#RequestMapping(value = "/getid", method = RequestMethod.POST)
public String getAccountID(Model model) {
model.addAttribute("accountId", "ABC1234"); // example
return "account";
}
}
Suppose, create an account.jsp.
<!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">
</head>
<body>
<%
String accountId = request.getAttribute("accountId");
out.println("account.jsp -> " + accountId);
session.setAttribute("accId", accountId);
%>
<form action="account2.jsp" method="post">
<input type="submit" name="Submit">
</form>
</body>
</html>
Create another page with the name account2.jsp :
<!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">
</head>
<body>
<%
String accId = (String) session.getAttribute("accId");
out.println("account2.jsp -> " + accountId);
// now you want to sent it to the another controller
// set the parameter in the session and retrieve it in the controller.
session.setAttribute("accountId", accId);
%>
</body>
</html>
Create a DemoController2 class :
#Controller
public class DemoController2 {
#RequestMapping(value = "/getid2", method = RequestMethod.POST)
public String getAccountId2(HttpSession session) {
String id = (String) session.getAttribute("accountId"); // example
System.out.println(id);
return "some-page-name";
}
}
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.
So to be more specific what Im trying to solve. How can I show the first element in my Arraylist:"sortedDomainList" in my jsp?
EDIT : Model and ArrayList working tried in normal java application.
MODEL short version.
public ArrayList<String> sortedDomainList = new ArrayList<String>();
public ArrayList<String> getSortedDomainList() {
return sortedDomainList;
}
public void setSortedDomainList(ArrayList<String> sortedDomainList) {
this.sortedDomainList = sortedDomainList;
}
}
CONTROLLER/SERVLET
package com.comparebet.controller;
import com.comparebet.model.*;
#WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
public Controller() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
ArrayList<String> sortedDomainList = new BeanModel().getSortedDomainList();
request.setAttribute("d", sortedDomainList);
RequestDispatcher view = request.getRequestDispatcher("view.jsp");
view.forward(request, response);
}
}
VIEW/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>CompareBet</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/Comparebet" method="get" accept-charset="UTF-8"></form>
<h1> ${d.sortedDomainList[0]}</h1>
</body>
</html>
This is my first try on MVC so I feel really lost when it comes down to servlet.
<%# 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>CompareBet</title>
</head>
<body>
<%
ArrayList<String> sortedDomainList= request.getAttribute("d");
for(String domain:sortedDomainList){
%>
<h1> <%= domain %> </h1>
<% } %>
</body>
</html>
Im working on a DynamicWebProject in Eclipse IDE.I got an error in console while running a jsp page showing "Failed to load resource: the server responded with a status of 404 (Not Found)".I already referred many questions regarding this problem but could not resolve it.Here is my javascript file
availability.js
var ajaxRequest = null;
if (window.activeXObject) {
ajaxRequest = new ActiveXObject("Microsoft.HTTP");
} else {
ajaxRequest = new XMLHttpRequest();
}
function ajaxValidation() {
var name = document.getElementById("username").value;
ajaxRequest.open("GET", "/SpringHibernateProject/validate?name=" + name,
true);
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var message = ajaxRequest.responseText;
document.getElementById("div").innerHTML = "<font color='red'>"
+ message + "</font>";
}
};
ajaxRequest.send(null);
}
Here is my jsp page
AjaxPage.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>
<script type="text/javascript" src="../Js/availability.js"></script>
</head>
<body>
<input type="text" name="username" id="username" onkeyup="ajaxValidation()"></input>
<div id="div"></div>
</body>
</html>
Im getting this error though I referred the script file correctly.Why is it so?