Data Injection from controller to jsp page - java

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";
}
}

Related

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.

Spring MVC-Response is not getting from controller using angular

I am implementing simple CRUD Operation using spring restful webservices and angular js.I trying to load all the details when the page is loading.But its not getting any response.
Controller :-
#RestController
public class EmployeeController {
public List<Employee> appList=new ArrayList<Employee>();
#RequestMapping(value="/employee",method=RequestMethod.GET)
public ModelAndView loadEmployee(){
return new ModelAndView("employee", "webemployee", new Employee());
}
#RequestMapping(value="/employees",method = RequestMethod.GET,headers="Accept=application/json")
public List<Employee>loadAllApps() {
Employee app=new Employee();
System.out.println(".........................loadAllApps.............");
app.setAppID("test_id");
app.setAppName("test_name");
appList.add(app);
return appList;
}
#RequestMapping(value="/employees/insert/{appID}/{appDescr}",method = RequestMethod.POST,headers="Accept=application/json")
public List<Employee> addApps(#PathVariable String appID,#PathVariable String appDescr) throws ParseException {
System.out.println("appID"+appID+"appDescr..........."+appDescr);
Employee app=new Employee();
app.setAppID(appID);
app.setAppName(appDescr);
appList.add(app);
return appList;
}
}
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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="AppManger">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>WebService Example</title>
<script data-require="angular.js#*" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
</head>
<div ng-controller="appController">
<div>
<table>
<tr ng-repeat="app in appList">
<td >{{ app.appID }}</td>
<td >{{ app.appName }}</td>
</tr>
</table>
</div>
<script type="text/javascript">
var appModule = angular.module('AppManger', []);
appModule.controller('appController', function ($scope,$http) {
var url="http://localhost:8080/Apps";
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get(url+'/employee').
success(function(data, status, headers, config) {
alert(status);
$scope.appList = data;
});
});
</script>
</script>
</html>
when i am trying to checking status value in $http.get method.its not showing any alert message.Please let me know what issues here.
You seem to call your /employee endpoint but expecting a list of employees , because you assigning data response to the:
$scope.appList = data;
First, change that to the other endpoint you created (/employees) which returns the list.
What is the servlet-path of your mvc dispatcher servlet? This would be my first point of failure to check for. I see that you call:
var url="http://localhost:8080/Apps";
Does that mean that you deploy your app in context 'Apps' or is that your servlet path? If this is the context name then I assume that mvc is resolved to the 'root' path i.e. '/'. If not, check what is servlet path for the dispatcher and add that to your url (on the client side). This would explain why you get 404.
And also, check that you can call your API directly in the browser to rule out the server-side errors as user Chandermani suggested.

Passing a variable from JSP to Java

I am trying to pass a string variable called seq from a JSP to a Java program, and pass it on to the another Java program by passing the string as an argument to its object. I am somehow getting stuck.
Start.jsp:
<%# page import="org.dypbbi.nirmiti.ProtModMain %>
<%# 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>NIRMITI</title>
</head>
<body>
<h1>Please wait...</h1>
<%
String seq=request.getParameter("s");
ProtModMain.getSequence(seq);
%>
</body>
</html>
ProtModMain.java:
package org.dypbbi.nirmiti;
public class ProtModMain {
String sequence="";
public static String getSequence(String str)
{
return str;
}
public static void main(String args[])throws Exception
{
ProtModMain MainObj = new ProtModMain();
sequence = MainObj.getSequence();
new ObjectFactory(sequence);
}
}
Start.jsp will retrieve the string value from the HTML. It passes the string to ProtModMain class via the method getSequence. I now need to use the string value to pass it to other classes that require it, so I intend to pass it a parameter to the ObjectFactory object. But before that, I need to call the getSequence method in the ProtModMain class so that I can pass the value. I am not understanding how to call the getSequence method in the main method of ProtModMain class.
You need to set the parameter to the request using request.setAttribute("<name>",<value>). Then you can get it in the Java file using request.getAttribute("<name>").
Reference - Oracle Docs - HttpServletRequest
You are not calling the main method. In your JSP you are calling only the static getSequence that, by the way, only returns the value.
I think you have a project concept problem: why your web (JSP) app has a main class?
I think you should adapt:
Start.jsp:
<%# page import="org.dypbbi.nirmiti.ProtModMain %>
<%# 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>NIRMITI</title>
</head>
<body>
<h1>Please wait...</h1>
<%
String seq=request.getParameter("s");
ProtModMain protModMain = new ProtModMain();
ObjectFactory myFactory = protModMain.createFactory(seq);
//do whatever you want with your factory ;)
%>
</body>
</html>
ProtModMain.java:
package org.dypbbi.nirmiti;
public class ProtModMain {
public ObjectFactory createFactory(final String sequence) {
return new ObjectFactory(sequence);
}
}
This way you will be calling the methods you intended to.
You can use <form> tags and <input type='hidden'> with an <input type='submit'> button, in the form you will specify the method to send and to where send the data.
Or you can store in POJOs and store in session and recover it with a servlet.
Or use Ajax with an XmlHttpRequest.

Linking a jsp page to a java class

I have written a hello world program in jsp and now i am trying to process forms via JSP.
My jsp form(GetName.jsp) looks like this
<%#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>
<FORM METHOD=POST ACTION="SaveName.jsp">
Name <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
Email <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
Age <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
</body>
</html>
Similarly SaveName.jsp looks like this
<%#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>
<jsp:useBean id="userData" class="javabeans.UserData" scope="session"/>
<jsp:setProperty name="userData" property="*"/>
</BODY>
</HTML>
</body>
</html>
And in the same project in a package named javabeans the class named UserData looks like this.
package javabeans;
public class UserData {
String username;
String email;
int age;
public void setUsername( String value )
{
username = value;
}
public void setEmail( String value )
{
email = value;
}
public void setAge( int value )
{
age = value;
}
public String getUsername() { return username; }
public String getEmail() { return email; }
public int getAge() { return age; }
}
Now when run GetName.jsp i get the following errors
D:\javaworkspace\Netbeans7-2\HelloWeb\build\generated\src\org\apache\jsp\SaveName_jsp.java:56: cannot find symbol
symbol : class UserData
location: class org.apache.jsp.SaveName_jsp
UserData user = null;
^
D:\javaworkspace\Netbeans7-2\HelloWeb\build\generated\src\org\apache\jsp\SaveName_jsp.java:58: cannot find symbol
symbol : class UserData
location: class org.apache.jsp.SaveName_jsp
user = (UserData) _jspx_page_context.getAttribute("user", PageContext.SESSION_SCOPE);
D:\javaworkspace\Netbeans7-2\HelloWeb\build\generated\src\org\apache\jsp\SaveName_jsp.java:60: cannot find symbol
symbol : class UserData
location: class org.apache.jsp.SaveName_jsp
user = new UserData();
3 errors
D:\javaworkspace\Netbeans7-2\HelloWeb\nbproject\build-impl.xml:930: The following error occurred while executing this line:
D:\javaworkspace\Netbeans7-2\HelloWeb\nbproject\build-impl.xml:284: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 2 seconds)
You need to import UserData class inside SaveName.jsp
Add this to the top of your jsp code in SaveName.jsp
<%# page import="javabeans.UserData" %>
I'm not sure what you want to implement over here but i can give you simple idea about jsp servlets
first you can create a simple jsp program. it will ask the user for name and email id and on form action redirect it to abc 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> My first JSP </title>
</head>
<body>
<form action="abc">
Please enter a name <br>
<input type="text" name="name"size="20px">
Please enter an email <br>
<input type="text" name="email"size="20px">
<input type="submit" value="submit">
</form>
</body>
</html>
and then create the "abc" servlet
place this code in your servlet. it will get the value from jsp page and display it.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class abc extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// reading the user input
String name= request.getParameter("name");
String email= request.getParameter("email");
String msg="I'm"+name+"id is"+email;
PrintWriter out = response.getWriter();
out.println (
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"
\"http://www.w3.org/TR/html4/loose.dtd\">\n" +
"<html> \n" +
"<head> \n" +
"<meta http-equiv=\"Content-Type\" content=\"text/html;
charset=ISO-8859-1\"> \n" +
"<title> Hi </title> \n" +
"</head> \n" +
"<body> \n" +
msg +
"</font> \n" +
"</body> \n" +
"</html>"
);
}
}
Define your servlet in "web.xml" . you need to do servlet mapping in web.xml file.
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>abc</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>

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