Wicket human-readable URLs - java

Started learning Wicket after ASP.NET MVC and feel a little bit confused about managing its URLs. Here's the code:
Application:
package com.test.wicketapp1;
import org.apache.wicket.protocol.http.WebApplication;
public class WicketApplication extends WebApplication {
public WicketApplication() {
mountPage("/page1", HomePage.class);
mountPage("/page2", Page2.class);
}
#Override public Class<HomePage> getHomePage() {
return HomePage.class;
}
}
HomePage:
package com.test.wicketapp1;
import java.io.IOException;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.WebPage;
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
public HomePage(final PageParameters parameters) throws IOException {
BookmarkablePageLink<Page2> bookmarkablePageLink = new BookmarkablePageLink<Page2>("gopage2link", Page2.class);
add(bookmarkablePageLink);
}
}
HomePage markup:
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<title>Apache Wicket Quickstart</title>
</head>
<body>
go page 2
</body>
</html>
What I wanted to have is pretty simple. I expected that there would be 2 urls: "/page1" for HomePage.class and "/page2" for Page2.class, then my HomePage has a link that navigates to Page2 and when HomePage is rendered, that link should have an URL of "/page2".
When I run the application and go to home page, it is rendered like this:
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<title>Apache Wicket Quickstart</title>
</head>
<body>
go page 2
</body>
</html>
I expected to have something like:
go page 2
instead. What did I miss?

The problem is - I should use app's init method instead of ctor to define the mappings.

have a look at this. It might help
https://cwiki.apache.org/WICKET/request-mapping.html

Related

How to hide/show thymeleaf fields based on controller condition?

I have a Spring MVC application with thymeleaf.
Depending on a condition tested in the controller method I want to show or hide an html element from the view (input, span, div, button...).
How to do that? For instance, in asp.net you can do myButton.Visible = false (or true) if you want or don't want to display it.
Anything like that available in thymeleaf with spring? Thanks.
You can achieve it by passing the attribute via
org.springframework.ui.Model and use Thymeleaf's th:if attribute
Demo:
package com.example.demo.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class MealController {
#GetMapping("/order")
public String getCondition(#RequestParam(required = false) String myMeal, Model model) {
model.addAttribute("meal", myMeal);
return "meal/meal-site";
}
}
resources/templates/meal-site.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hot Dog?</title>
</head>
<body>
<div th:if="'hotdog' == ${meal}">A hotdog! 🌭</div>
<div th:if="'hotdog' != ${meal}">Not a hotdog 😢</div>
</body>
</html>

Spring does not show home.html

I am learning Spring Framework. I added home.html in resources/templates/home.html. But it is not visible when I visit http://localhost:8080. I have the following structure:
taco-cloud\src\main\java\tacos\TacoCloudApplication.java
package tacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TacoCloudApplication {
public static void main(String[] args) {
SpringApplication.run(TacoCloudApplication.class, args);
}
}
taco-cloud\src\main\java\tacos\HomeController.java
package tacos;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class HomeController
{
#GetMapping("/")
public String home()
{
return "home.html";
}
}
taco-cloud\src\main\resources\static\home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Taco Cloud</title>
</head>
<body>
<h1>Welcome to...</h1>
<img th:src="#{/images/TacoCloud.png}"/>
</body>
</html>
Output
Whitelable error page
localhost:8080/home.html
show home.html
You have to change the location of your home page to be in the static folder :
resources/static/home.html
^^^^^^
instead of
resources/templates/home.html
and specify the extension in your controller :
return "home.html";
^^^^^
else you have to create a view resolver to avoid using extensions and to specify the other locations of your pages take a look at Configure ViewResolver with Spring Boot and annotations gives No mapping found for HTTP request with URI error
You can try this.
#GetMapping("/")
public String home()
{
return "templates/home.html";
}
Check more details
Below are few different ways you can place html files in your project.(Note it is from highest to lowest precedence)
src/main/resources/resources/home.html
src/main/resources/static/home.html
src/main/resources/public/home.html
Go through this to get an idea about spring mvc project structure

form.fill() not working in one project, works fine in another

I have 2 projects with the names:
old
new
I made a form in "old" with a radiobutton and some textfields to enter age, weight, ...
Then I made a new project (activator new new) and developed the form further. The controller pre-fills the form, pre-selects the radiobutton etc.
Now I wanted to update "old" and copied the code from "new" into "old".
In ALL controller-classes, in ALL model-classes, in ALL views-classes is the EXACT same code! I even checked the file sizes manually several times, BUT in "old" the form does not get pre-filled! No matter what I do, nothing happens. I have no clue why this happens and what do to.
My code:
Application.java:
package controllers;
import models.User;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
public class Application extends Controller {
static Form<User> userForm = Form.form(User.class);
public static Result index() {
User user = new User();
Form<User> preFilledForm = userForm.fill(user);
return ok(views.html.index.render(preFilledForm));
}
}
User.java:
package models;
public class User {
public Integer gewicht;
public Integer groesse;
public Integer alter;
public Float grundUmsatz;
public String geschlecht = "Mann";
public User(){
gewicht = 0;
groesse = 0;
alter = 0;
geschlecht = "Mann";
}
}
index.scala.html:
#(userForm : Form[User])
#import helper._
#import helper.twitterBootstrap._
#main("App - index") {
#helper.form(action = routes.Application.submit(), 'id -> "userForm"){
<fieldset>
#helper.inputRadioGroup(
userForm("Geschlecht"),
options = options("Mann"->"Mann","Frau"->"Frau"),
'_label -> "Gender",
'_error -> userForm("Geschlecht").error.map(_.withMessage("select gender"))
)
</fieldset>
#helper.inputText(userForm("Gewicht"))
#helper.inputText(userForm("Groesse"))
#helper.inputText(userForm("Alter"))
<input type="submit" class="btn primary" value="Send">
}
}
main.scala.html:
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/hello.js")" type="text/javascript"></script>
</head>
<body>
#content
</body>
</html>
routes-file:
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index()
POST /auswertung/ controllers.Application.submit()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
Peanut reminded me of activator clean and then activator run. Seems like I've worked too long on this to see the solution. Thank you for the reminder!

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.

Javascript/Javabean: co-operation not working for counter

I have to make a simple webapplication using javascript and javabeans. The actual assignment is a bit different (including dropcoordinates and such), but here's my testing file problem:
Whenever the red square is clicked, it should add 1 to the value in my javabean and output it to a textfield. It shows it correctly, but then it somehow reverts back to its original value. When I debug, it doesn't even go into my method addUp(). Second problem: when I refresh the page, it DOES go into the method, no matter if I've clicked the square or not.
Here is my code:
Website index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<title>Facelet Title</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</h:head>
<h:body>
<form>
<DIV id="move" style="width:150px;height:150px;background-color:pink;border:1px solid #999999"> </DIV>
<input id="test" value="${countController.counter}" />
<SCRIPT type="text/javascript">
$(document).ready(function(){
$("#move").click(function(event, ui){
alert(${countController.counter});
});
$("#droppable").click(function(event, ui){
alert(${countController.counter});
${countController.telOp()};
document.getElementById("test").value = ${countController.counter};
alert(${countController.counter});
//window.location.reload();
});
});
</SCRIPT>
<div id="droppable" style="width:150px;height:150px;background-color:red;border:1px solid #999999">Drop here</div>
</form>
</h:body>
</html>
CountController.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
*
* #author Laurent
*/
#ManagedBean
#SessionScoped
public class CountController implements Serializable{
/** Creates a new instance of countController */
public CountController() {
}
private int counter = 0;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public void telOp(){
counter++;
}
}
You need to add an event listener in your managed bean such as
buttonClicked(ActionEvent event){
}
and then from the ui, you implement a h:commandLink or h:commandButton to invoke the action event.

Categories

Resources