I have a spring boot project but, I have some links from past and users are linking url on their websites and I cannot request client to change their urls. I am trying to navigate jsp link to React app. I have just found a solution but I got stuck.
Here is the link example: abc/Dashboard.jsp#/company/88
I am handling abc/Dashbord but I cannot handle abc/Dasboard.jsp to navigate a jsp page.
There is my handling endpoint;
#Controller
#RequestMapping("")
public class DashboardController {
#GetMapping("/Dashboard")
public String viewBooks() {
return "view-dashboard";
}
}
#GetMapping("/Dashboard.jsp")
public String viewBooks2() {
return "view-dashboard";
}
My Jsp Page
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>e-ŞİRKET</title>
</head>
<body>
</body>
</html>
<script>
const url = window.location.href.split('/')
if(url && url.length > 0) {
const id = url[url.length -1]
if(id) {
window.location.replace(window.location.origin + '?page=company&company=' + id)
}
}
</script>
It is working for abc/Dashboard#company/88 but;
how I can handle abc/Dashboard.jsp#/company/123. I am getting 404.
Related
I write simple Jax-Rs app (Restful), and try to return jsp file with java code. But, when I run app I get the error:
Could not find MessageBodyWriter for response object of type: com.sun.jersey.api.view.Viewable of media type: text/html;charset=UTF-8
My jsp file:
<%# page import="com.trofimovep.models.Book" %>
<%# page import="com.trofimovep.dao.BooksDao" %>
<%# page import="java.util.ArrayList" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>Bookshop</title>
</head>
<body>
This is a bookshop!
The books on our site:
<%
BooksDao booksDao = new BooksDao();
ArrayList<Book> books = booksDao.getBooks();
for (Book book : books) {
out.println("<tr>");
out.println("<th>" + book.getName() + "</th>");
out.println("<th>" + book.getAuthor() + "</th>");
}
%>
<button type="submit">Make order</button>
</body>
</html>
And function:
#Path("/bookshop")
public class Start {
#GET
#Path("/books")
#Produces({MediaType.TEXT_HTML})
public Response Books() {
return Response.ok(new Viewable("/views/mainPage", null)).build();
}
}
What I do wrong? And how it possible to fix?
I am trying to pass an attribute from a java servlet to jsp and write this attribute on jsp file. However it does not redirect to jsp file url but it writes the content of the jsp file. Here is my related codes:
Control.java:
#WebServlet("/Control")
public class Control extends HttpServlet{
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Key key = MacProvider.generateKey();
long time = System.currentTimeMillis();
try{
String jwt = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, key)
.setSubject("username")
.setIssuedAt(new Date(time))
.setExpiration(new Date(time+6000000))
.claim("password","password")
.compact();
req.setAttribute("jwt", jwt);
req.getRequestDispatcher("/Home.jsp").forward(req,resp);
}catch (Exception e){
e.printStackTrace();
}
}
}
Home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
${jwt}
</body>
</html>
Here, browser stays on http://localhost:8080/Control but it writes the content of Home.jsp file which is just a java web token result string.
2) My second question is when I tryed to store this jwt result string in browser local storage and then write it in jsp file in order to check if it stored in browser or not. But it does not prints anything. To do this, I just changed the Home.jsp file as follow:
(I took both of the code snippets from here)
Home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<script>
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.write(jjwt);
</script>
</body>
</html>
Another try:
<html>
<head>
<script>
function myFunction() {
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.getElementById("myText").innerHTML = jjwt;
}
</script>
</head>
<body onload="myFunction()">
<span id="myText"></span>
</body>
</html>
Where am I doing wrong?
1) When you use RequestDispatcher.forward(request,response), your servlet will still have control but your jsp page will be loaded so this is nothing to worry about.
If you want your browser URL to show your JSP page URL, do response.sendRedirect("URL TO LOAD");
2)Since you are using JSP, try accessing the request variables like below and print it
<% String jwt = (String) request.getAttribute("jwt");%>
We need to set it as
localStorage.setItem('jwt', <%=jwt%>);
Problem:
I have a simple controller which returns me a list of hardcoded locations. When i want to get my locations in my javascript file using $.get and print it in my console, i get some weird "undefined" results.
Controller:
#RestController
#RequestMapping("/locationOverview")
public class LocationOverviewController {
private LocationGuide service;
public LocationOverviewController() {
this.service = new LocationGuide("Memory");
}
#RequestMapping(method = RequestMethod.GET)
protected ModelAndView getLocations() {
ArrayList<Location> locations = new ArrayList<Location>();
locations.add(new Location(1,"KHL",new Geolocation(51,51)));
locations.add(new Location(2,"KUL",new Geolocation(51,51)));
return new ModelAndView("locationOverview", "locations", locations);
}
}
mapScript JS:
function initialize() {
$.get("locationOverview.htm", function(data){
for(var i=0; i<data.length; i++){
console.log(data[i].name);
}
})
}
JSP file:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="domain.Location"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Leuven Speaks</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript" src="<c:url value="/js/mapScript.js" />"></script>
</head>
<body onload="initialize()">
<jsp:include page="header.jspf"/>
</body>
</html>
You should actually inspect with dev tools what that data contains. The controller method you show us looks like it is not the one mapped to locationOverview.htm. If you want to query data with ajax, return the list using the #ResponseBody annotation instead.
Data passed in a model would be available in the JSP page that you define as the view in ModelAndView.
Some learning resources:
http://www.beingjavaguys.com/2014/05/json-response-with-responsebody_31.html
https://developer.chrome.com/devtools/docs/javascript-debugging
I am using Eclipse, Spring MVC, Maven and Tomcat. This index.jsp displays exactly as show below in the web browser. It is not rendering properly.
Any idea what is wrong?
index.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>
<h1>Index</h1>
</body>
</html>
#Controller
public class HelloController {
#RequestMapping("/greeting")
public String sayHello() {
System.out.println("Greeting");
return "hello";
}
#RequestMapping("/")
public String index() {
System.out.println("Index page");
return "index";
}
}
A controller has a GET and a POST RequestMethod.However at a quick glance you need to change #RequestMapping("/greeting") to #RequestMapping(value = "/greeting") just for starters. By default your jsp file should be in /src/main/webapp/WEB-INF/views (Spring MVC Starter Project)
When you return a String - Spring MVC will look for a jsp with that .jsp. So in this example you just want to have greeting.jsp
#Controller
public class GreetingController {
/**
* GET
*/
#RequestMapping(value = "/greeting", method = RequestMethod.GET)
public String handleRequest() {
// This will be used when you GET the URL
return "greeting";
}
/**
* POST
*/
#RequestMapping(value = "/greeting", method = RequestMethod.POST)
public String processSubmit(){
// This will be used when you POST to the URL
//TODO Do something here and it will put you right back in your page
return "greeting";
}
}
Go ahead and comment if you have any other questions. Also check my account for my other example Neither BindingResult nor plain target object for bean name available as request attr
Hope this helps. Good Luck!
Just a note Spring has more RequestMethod's but GET and POST are the most used and easiest to understand.
It could be that the only thing you're missing is to
Right click on the jsp page and click RUN AS, then RUN ON SERVER.
I use Spring MVC 3 in my project.
This is my AddressController :
#Controller
public class AddressController {
private static Logger logger = Logger.getLogger(AddressController.class);
#RequestMapping(value="/address",method=RequestMethod.GET)
public ModelAndView init(
#RequestParam(value="language",required=false,defaultValue="fr") String language){
Locale locale = new Locale(language);
logger.info("here");
String[] isoCountries = locale.getISOCountries();
Map<String,String> treeMap = new TreeMap<String,String>();
for(String isoCountry : isoCountries){
Locale countryLoc = new Locale(language, isoCountry);
String name = countryLoc.getDisplayCountry(locale);
if(!"".equals(name)){
treeMap.put(name,name);
}
}
Map<String,String> tree = new TreeMap<String,String>(treeMap);
ModelAndView modelAndView = new ModelAndView("address");
modelAndView.addObject("address",new Address());
modelAndView.addObject("countriesList", tree);
return modelAndView;
}
}
The first time, when I executed /address, it's going well to my controller and it returns my address.jsp by executing the javascript in this last one. But when I execute /address?language=fr or /address?language=en, the javascript code of my address.jsp is not executed.
This is a part of my address.jsp :
<%#page import="org.springframework.context.i18n.LocaleContextHolder"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="forms" uri="http://www.springframework.org/tags/form" %>
<%#page import="com.application.myGoogleAppEngine.Internationale"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.util.Locale" %>
<%# page import="java.util.List" %>
<%# page import="java.util.ArrayList" %>
<%# page import="java.util.Collections" %>
<html>
<head>
<jsp:include page="ressources.jsp"></jsp:include>
<link rel="stylesheet" type="text/css" href="stylesheets/320x480/portrait/address.css" />
<%! Internationale internationale = Internationale.getInstance(); %>
<script>
$(document).ready(function(){
//checkParams();
alert("here");
var unit = "em";
alert("here2");
$("#backButton").attr("href","/index");
$('#validationBtn').click(function(){
var streetName = $('#streetName').val();
var streetNumber = $('#streetNumber').val();
var zipCode = $('#zipCode').val();
var city = $('#city').val();
var country = $('#country').val();
var ref = "MyServlet?streetName="+streetName+"&streetNumber="+streetNumber+"&zipCode="+zipCode+"&city="+city+"&country="+country;
$(this).attr("href",ref);
});
});
//rest of the script
</script>
<body>
<a id="backButton" data-role="button" data-icon="arrow-l"
data-ajax="false">
<spring:message code="backButton"/>
</a></div>
//rest of the code
</body>
In web MVC spring serves as server side technology. Javascript is client (browser) side technology, thus Spring "cannot" execute javascript.