Change page title from Spring MVC Velocity view? - java

I feel like page title ought to be defined by the view rather than by a controller or model.
In Zend Framework, I could write this in the view:
$this->headTitle('Signup');
And that would change the page's window title to 'Signup'.
How can I do that in Java Spring MVC using Velocity for the view?
I thought maybe I could use something like:
$page.setTitle("Signup")
but it didn't work.
This is probably similar to this question: https://stackoverflow.com/questions/18539645/how-to-set-head-meta-tag-from-view-layer-in-spring-mvc-velocity
P.S. I'm also using Apache Tiles, so I have a Velocity file for layout.vm (which creates the HTML, HEAD, BODY, etc) and a Velocity file for signup.vm (which just creates the signup form). I want to be able to specify within signup.vm what the page's title should be.

Your velocity view is generating all of the HTML that is sent to the browser. You just add a <title> element to your page.
SignupController.java
#RequestMapping(value = "/signUp", method = RequestMethod.GET)
public ModelAndView signup() {
ModelAndView modelView = new ModelAndView("sign_up");
modelView.setObect("personName", "The Dude");
return modelView;
}
sign_up.vm
<html>
<head>
<title>Signup</title>
</head>
<body>
<p>Looks like you are signing up for something, ${personName}</p>
</body>
</html>

Related

Freemarker - call external java function with page number as parameter

I have Freemarker templates for generating pdf documents, that can have multiple pages based on variables content. I need generate unique code on each page, the generating logic takes page number as parameter. I have working utils class, callable from template used for dates formatting etc.
Ideally I would like to be able call my utils class like that, with something that would provide current page number on each page (simplified example):
<h1>Utils result: ${utils.generateUniqueNumber(pageNumber)}</h1>
I will probably need to place this code into header/footer, to achieve have it on each page.
Currently I have working page counter in footer defined using css:
<head>
<title>RESEA - Selection Notice OWCMS</title>
<style type="text/css">
.page-counter:before {
content: "Page "counter(page)" of "counter(pages)
}
</style>
</head>
Then used in footer , works as expected.
I'm not sure if actual paging is driven by Freemarker or CSS, so maybe I need to make CSS call my utils function.
Any advise, or relevant study source is welcome!

How do I use Micronaut views to send back params and set local storage?

I am trying to use Micronaut Views annotation to send back few params and set local storage then redirect. I used script tag inside autoredirect.html template which should set local storage and then window.location.replace to redirect. Please help me with following 2 concerns.
Request hits the post and get methods, but corresponding view is not sent back, instead after computing everything I get 404 Not Found.
GET request -> http://localhost:8081/someapp/api/sso
Is this right way to set localstorage and redirect to another relative path?
POST request with necessary params to compute roles and JWT -> http://localhost:8081/someapp/api/sso/saml
added below additional entry in build.gradle
compile "io.micronaut:micronaut-views"
runtime "org.thymeleaf:thymeleaf:3.0.11.RELEASE"
view location
My controller
#Controller('/someapp/api/sso')
#Slf4j
#CompileStatic
class SomeController {
#View("home")
#Get("/")
HttpResponse index() {
return HttpResponse.ok(CollectionUtils.mapOf("loggedIn", true, "username", "raka"))
}
#View("autoredirect")
#Post('/saml')
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.TEXT_HTML)
HttpResponse<String> samlLogin(#Nullable #Body LinkedHashMap payload) {
//... some operations, computing user roles & jwt
if (payload != null) {
String results = handler.call(payload)
return HttpResponse.ok(results).
header("JWT", jwt.toString())
} else {
return HttpResponse.badRequest()
}
}
}
home.html
<!DOCTYPE html>
<html lang="en" th:replace="~{layoutFile :: layout(~{::title}, ~{::section})}" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
</head>
<body>
<section>
<h1 th:if="${loggedIn}">username: <span th:text="${username}"></span></h1>
<h1 th:unless="${loggedIn}">You are not logged in</h1>
</section>
</body>
</html>
autoredirect.html
<!DOCTYPE html>
<html>
<head>
<title>Cassini</title>
</head>
<script type="text/javascript">
localStorage.setItem('username', '${username}');
localStorage.setItem('perm', '${perm}');
localStorage.setItem('userDetails', '${userDetails}')
window.location.replace('${redirectURL}');
</script>
<body>
</body>
</html>
Update
I tried explicitly adding below lines in my application.yml, but still no luck. Gives 13:10:56.476 [pool-2-thread-3] DEBUG io.micronaut.views.ViewsFilter - view autoredirect not found message instead.
micronaut.views.enabled: true
micronaut.views.folder: views
micronaut.router.static-resources.*.enabled: true
micronaut.router.static-resources.*.paths: classpath:public
You should just have an endpoint to return the users information. Then the client side can call it and do whatever needs to happen. Trying to put things in local storage then redirect in an HTML file seems like a hack to me
For your 1st question:
Request hits the post and get methods, but corresponding view is not
sent back, instead after computing everything I get 404 Not Found.
I think you are missing the starting forward slash / while trying to specific view path in #View annotation.
Following basic code block renders the index.html located inside resources folder views/home/index.html
#Controller("/home")
class HomeController {
#Get("/")
#View("/home/index")
public Map index() {
return [:]
}
}
For you 2nd question:
Is this right way to set localstorage and redirect to another relative
path?
I am not sure completely on your requirement but if you trying to have session management and security in micronaut, you can look for
Micronaut Session
Micronaut Security
#Secured([RoleConstant.SUPER_ADMIN, RoleConstant.ADMIN])
#Controller("/home")
class HomeController {
#Get("/")
#View("/home/index")
public Map index(#Nullable Principal principal) {
return [username: principal.name]
}
}
Refer documentation of Mirconaut, also make sure you upgrade to latest 1.1.1 version as few bugs are fixed in latest release for thymeleaf & cookie path used in security & session.

how to refer one jsp page on another jsp page?

I want to have references on my welcomePage.jsp page to other jsp pages - loginPage.jsp and registerPage.jsp. I tried to use simple like this:
<head>
<title>${title}</title>
</head>
<body>
<jsp:include page="header.jsp"/>
<jsp:include page="_menu.jsp" />
<h1>Welcome to the page!</h1>
Register
<p>or</p>
Log In
<p>if you already have an account</p>
<jsp:include page="footer.jsp"/>
</body>
</html>
But I keep getting HTTP Status 404 The requested resource is not available.
I also tried but as a result the contents of the pages I was referencing too just apperead on this welcomePage. Although I need them to be accessible through links only.
All the mentioned files are located in WEB-INF/pages.
This is my first project with Spring MVC so any help is welcomed.
Suppose, in your configuration, you have set the location of views e.g. /WEB-INF/view/ where you put all of your .jsp files - loginpage.jsp, registerPage.jsp etc. Now, you can simply access the location of view i.e. /WEB-INF/view/ via pageContext.servletContext.contextPath.
//For example
href="${pageContext.servletContext.contextPath}/loginpage"
I suggest you to go to a controller first, than call a ModelAndView in this controller. This also keeps the relations clear between the JSP files.
To apply this your controller class should be like this:
#Controller
public class LoginPageController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView printLoginPage() {
ModelAndView modelAndView = new ModelAndView("loginPage");
return modelAndView;
}
}
You can also pass parameters from a JSP page to another by going through a controller method.

Play! 2.3.1 - displaying HTML source code instead of page

My Application class looks like this:
public class Application extends Controller {
public static Result index() {
return ok(index.render("<p>This is a paragraph</p>"));
}
and my index.scala.html file looks like:
#(htmlcode: String)
#main("Example") {
#htmlcode
}
and my main.scala.html file is fairly simple, with the standard !DOCTYPE declaration, html, head, body tags, etc.
...
<body>#content</body>
...
But when I run my application, the index page displays the source code <p>This is a paragraph</p> instead of just This is a paragraph. The source file looks like
...
<body>
<p>This is a paragraph</p>
</body>
...
How would I have the page render the code instead of just displaying it?
It is simply converting/protecting the values you are giving it. All the HTML markup should be done in the template (scala.html) file and not in the controller.
BTW this question comes pretty closes to this other question : How to pass raw html to Play framework view?
Simply use the Html() function
#main("Example") {
#Html(htmlcode)
}

Static html Code in Java Servlet

I am new at programming Web applications and have a question about Java HttpServlet. How do I use long static html code? I have a Webpage with dynamic parts so I can not use html only, but it´s only a small part of the page who is dynamic the Rest is static. In the moment I write the static part of the page like this:
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<head><title>Hello World Servlet</title></head>");
writer.println("<body>");
writer.println(" <h1>Hello World</h1>");
writer.println("<body>");
writer.println("</html>");
But I am quit sure that this isn´t an god style. I looked for a better solution for a while but didn´t find a better solution, which is caused by the fact I didn´t for what I have to look. Can someone please post a Link where I read something about this.
At the end I have to apologize for my bad English, but I´m not a native speaker.
Than you very much
Johannes
Use the servlets as controller in your MVC application, and use JSP to handle the view. So, instead printing a lot of HTML code to the response, do a forward to the next view (jsp file). Here's a basic example of a servlet and a JSP file as view.
#WebServlet("/hello")
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("salute", "Hello world from Servlet!");
request.getRequestDispatcher("/realView.jsp").forward(request, response);
}
}
And in your realView.jsp file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Real View</title>
</head>
<body>
${salute}
</body>
</html>
So, just access to this URL: http://yourserverip/yourAppName/hello in your browser and you will get the a HTML 5 page with content posted from your servlet.
You can find more details about this explanation and another sample in StackOverflow Servlets wiki.
If Facelets - which is designed to work with JSF, but can work on top of pure Servlets and a whole set of web frameworks - is not an option and you don't want to use JSP as suggested by #Luiggi, there are several standalone template engines (maybe that was the term you were missing) for Java:
StringTemplate
FreeMarker
Velocity
Chunk Template
Rythmn
Thymeleaf
Casper
(Just to mention a few)
Of course that sooner or latter you will may realize that you need more than a template engine + servlets. Once you do, let me Google that for you.

Categories

Resources