I am using spring 3 MVC and i have below classes.
External system would call my application using below URL:
http://somehost/root/param1/param2/param3
I have a spring MVC controller method as below:
public ModelAndView showPage(#PathVariable("param1") String paramOne, #PathVariable("param2") String paramTwo, #PathVariable("param3") String paramThree, HttpServletResponse response) {
SomeModel model = new SomeModel(paramOne, paramTwo, paramThree);
return new ModelAndView("SomeJsp", "model", model);
}
SomeModel.java
public class SomeModel{
private String paramOne;
private String paramTwo;
private String paramThree;
//constructor
//setters and getters
}
SomeJsp.jsp
//In this Jsp i have a div with few elements. Div is not visible by default.
//This jsp has externalJavascript included.
//I enable div and set the data into div elements using jquery.
externalJs.js
$(document).ready(function() {
//Here i need the model returned using ModelAndView
//I can get data from model and set into div elements.
});
In external java script file, is it possible to get the model content?
Thanks!
In the jsp page you may define global js variable and access those variables from the external js like:
jsp file
<script>
myModel=[];
myModel.paramOne='${model.paramOne}';
myModel.paramTwo='${model.paramTwo}';
myModel.paramThree='${model.paramThree}';
</script>
All server side scripts been rendered at server side and those value will be hardcoded once rendered. Once page loaded in the browser, global variables will be created with the rendered hardcoded value.
And my myModel can be access in the external file also.
EDIT:
Here is the someJsp.jsp file
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE>
<html>
<head>
<script>
myModel=[];
myModel.paramOne='${model.paramOne}';
myModel.paramTwo='${model.paramTwo}';
myModel.paramThree='${model.paramThree}';
</script>
<script src="externalJs.js"></script>
</head>
<body>
<!--content-->
</body>
and externalJs.js
$(document).ready(function() {
// myModel will be accessible from here because it's globally declared
alert(myModel);
});
Related
I am very new to Spring Boot framework and want to clarify why I am facing with this issue.
Issue: .jsp file is not shown at the correct endpoint.
this is my controller class
#Controller
public class HomeController {
#RequestMapping("home")
public String home() {
System.out.println("Hello World");
return "home.jsp";
}
}
This is my application.properties class
spring.mvc.view.prefix = /webapp/
spring.mvc.view.suffix = .jsp
this is what I have inside home.jsp file
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Change Titlte</title>
</head>
<body>
Hello
</body>
</html>
and lastly, the project directory
When I start spring boot app the site looks like this
Why do you think I can't see the content of home.jsp file?
Any help is appreciated.
Best,
PS: I already added Tomcat Jasper libraries in the pom.xml file
Check this simple examle. It seems you should not use .jsp extension in controller's return statement. Don't forget to specify method of your endpoint. Use #GetMapping instead of #RequestMapping
Also you'd better switch to Spring MVC thymeleaf that works good with html files. jsp - is used mostly for Java EE projects.
There are several things to notice here.
Change mapping to /home instead.
View resolver is configured already, return "home" instead of "home.jsp".
Take Model object as an argument it will be useful.
home(ModelMap model)
I have a simple Spring boot application. There URL that would be used here is going to be like:
sub.domain.com/variable1/variable2
and variable1 and variable2 can be anything for example:
sub.domain.com/kfc/foo
sub.domain.com/subway/boo
and I capture those in my controller as below:
#Controller
public class IndexController {
#RequestMapping(value="/{var1}/{var2}", method = RequestMethod.GET)
public String Index(#PathVariable(value="var1") String variable1, #PathVariable(value="var2") String variable2) {
return "/index.html";
}
}
which will redirect to my html page which is located at src/main/webapp/index.html
so the index page is loaded under the dynamic url but then none of the scrips or stylesheets are found because it's trying to find them under variable1 path.
for example if I have
sub.domain.com/kfc/foo
and my link to css in the index.html is
<link rel="stylesheet" href="styles/index.css" />
it will try to find the index.css under
sub.domain.com/kfc/styles/index.css
how can I tell the app to look into the right place for the styles or js files?
index.html is trying to load styles from a relative path.
In order for index.html to load styles under sub.domain.com/styles/index.css, add a / in link tag **/**styles/index.css <link rel="stylesheet" href="/styles/index.css" />
I have this little java project in which I have to use jsp files.
I have an html with a login button that triggers the following function:
var loginCall = "user/login";
var logoutCall = "user/logout";
var signupCall = "user/signup";
function login() {
var login = baseUrl + loginCall + "?";
var loginFormElements = document.forms.loginForm.elements;
login = addParam(login, USER_NAME, loginFormElements.userName.value, false);
login = addParam(login, PASSWORD, loginFormElements.password.value, true);
simpleHttpRequest(login, function(responseText){
var status = evalJSON(responseText);
if (status.errorCode == 200) {
var res = status.results;
var sessionId = res[0].sessionId;
setCookie(SESSION_ID,sessionId);
window.location="http://localhost:8080/"+baseUrl+"/main.html";
} else {
showError(status.errorCode, "Username or password was incorrect.")
}
}, function(status, statusText){console.log('z');
showError(status, statusText);
});
}
As far as I can see a httpRequest is made and sent with data to baseUrl + loginCall, meaning localhost/something/user/login?name=somename&pass=somepass
This is where I'm stuck, do I have to make a java file somewhere somehow, that takes the request information, works it up with the database and returns an answer?
If so, where, how? Do I have to name it login/user.java?
Can anyone point me to the right direction, if not give me some code example or explanation of what I have to do next?
You need to have another look at the JSP MVC
The jsp page should hold the html and javascript and java code. If you want to call a separate .java class, you need to write that class as a servlet then call it.
So in your .jsp you have you html and javascript just like you have it there, then any java you include in these brackets <% %>
Have a look at the tutorials here http://www.jsptut.com/
And i see your doing a login page. I used this brilliant tutorial for creating a log in system which helped me understand how jsp and servlets worked.
http://met.guc.edu.eg/OnlineTutorials/JSP%20-%20Servlets/Full%20Login%20Example.aspx
Also check out this image which should help you understand the concept. Remember servlets are pure java classes, used for mostly java but can also output html, jsp's are used for mostly html (& javascript) but can include jsp. So the servlets do the work, then the jsp gets the computed values so that they can be utilized by JavaScript. that's how i think of it anyway, may be wrong
http://met.guc.edu.eg/OnlineTutorials/static/article_media/jsp%20-%20servlets/LoginExample%20[4].jpg
All the best
If you are not using any MVC framework then best approach would be to extending HttpServlet classes for handling requests and doing all heavy lifting tasks such as business logic processing,accessing/updating databases etc. and then dispatching the request to .jsp files for presentation.In .jsp.You can also add custom objects to request scope that you wish to access on '.jsp' pages + using expression language you can access most request related implicit objects
I taken a typical example of flow in brief.You may can an idea and explore in deep yourself.
Here is java servlet class that will handle a posted form.
public class doLogin extends HttpServlet{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String username= request.getParameter("username"); // get username/pasword from form
String password = request.getParameter("password");
// This is your imaginary method for checking user authentication from database
if(checkUserAuthentication(username,password)){
/*
user is authenticated.Now fetch data for user to be shown on homepage
User is another class that holds user info. Initialize it with data received from database
*/
user userData = new User;
user.setName(...);
user.setAge(...);
user.setInfo(...);
// etc
}
RequestDispatcher view = req.getRequestDispatcher("login.jsp");
req.setAttribute("userdata", userData); // set user object in current request scope
view.forward(req, resp);//forward to login.jsp
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
}
but you need a form with some action to invoke above ServletClass
<form action="/checkLogin" method="POST">
<input type="text" name="username" value="">
<input type="password" name="password" value="">
<input type="submit" name="login" value="Login">
</form>
To tell your Servlet container to invoke doLogin class on form login button click
you have to configure it in deployment descriptor file web.xml which is part of standard dynamic web application in java
In web.xml' following xml snippet make apllication server aware ofdoLogin` class
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.yourdomain.doLogin</servlet-class>
</servlet>
But its not mapped to any url yet,It is configured as below in <servlet-mapping> section in web.xml
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/checkLogin</url-pattern>
</servlet-mapping>
Now any post request to url /checkLogin will invole doPost method on doLogin class
After successful login request will be trasfered to 'login.jsp' page.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
You can use java code in sciptlet <% %> syntax to access userData object
<%
User data = (User)request.getAttribute('userData');
%>
Better and tidy approach is to use expression language
${ pageContext.request.userData.name }
Above expression calls getName() method on object of User class using java beans naming conventions
Here, you can learn more about expression language
May be some time later I can improve this and provide you more insight.Hope that helps :)
I'm using Spring MVC 3.0 to construct a rest-style url.
Here is part of my code:
#RequestMapping(value = {"/", "/posts"}, method = RequestMethod.GET)
public String getNewestPosts(Model model, HttpServletRequest request)
throws DataAccessException {
return getPostsByPage(1, model, request);
}
#RequestMapping(value = "/posts/page/{page}", method = RequestMethod.GET)
public String getPostsByPage(#PathVariable long page, Model model,
HttpServletRequest request) throws DataAccessException {
// ... get the posts by page number
}
I wrote two methods. One handles the request from url "/posts" which means retrieving the first page of the posts , and the other one handles the request from url "/posts/page/{page}" which means retrieving the posts according to the path variable {page}.
And the problem is that all the two methods above point to the same view which is a jsp file, but they're in different paths("/posts, "/posts/page/xxx"). The css path (../style.css) can not adapt both of them.
I try to solve it by using absolute css path(/style.css), which means the web application works only if the application is deployed on a root path("/").
I would appreciate it if you could help me.
Use the <c:url> tag, which prepends the context path to an absolute URL.
<link rel="stylesheet" type="text/css" href="<c:url value="/style.css" />" />
or
<c:url var="cssUrl" value="/style.css" />
<link rel="stylesheet" type="text/css" href="${cssUrl}" />
I have a form which when submitted stores data from it's fields to the database. The action forward in the struts-config maps back to the same page on Success/Failure of data insertion into the database. I would like to alert the user once this is successfully completed, so I set a session attribute(i.e. success/failure) in the method of the action class for the form. I then get and print out this session attribute once the jsp page has been accessed again.
So far I have done this in the Action Class:
public static void setJavaScriptNotification(HttpServletRequest request, String notificationText) {
HttpSession session = request.getSession(true);
session.setAttribute("notification_javascript", notificationText);
}
And in the jsp file that contains the form I have:
<% String notificationJavaScript = (String) request.getSession().getAttribute("notification_javascript");
pageContext.setAttribute("notification_javascript", notificationJavaScript);
request.getSession().removeAttribute("notification_javascript"); %>
<html>
<head>
<logic:present name="notification_javascript">
<script type="text/javascript" language="JavaScript">
function showAlerts() {
alert("<bean:write name="notification_javascript"/>");
}
</script>
</logic:present>
</head>
<body onload="doPreOnload(); showAlerts();">
When I print out the session attributes in the jsp, I can't find the notification_javascript attribute. I'm new to HTTP, so I could be doing something wrong there.
After setting notification_javascript in session in setJavaScriptNotification() do the request is forwarded to jsp where notification_javascript is accessed.
If yes, then session.getAttribute("notification_javascript") will do the job.
request.setAttribute() vs session.setAttribute()
request.setAttribute() will make the key available in following page.
session.setAttribute() will make the key available in all pages.