#ControllerAdvice not catching Rest API exceptions - spring

I'm trying to implement Error handling into my Rest API and testing with Postman, when I give an incorrect path postman returns a 404 but its a 404 HTML. I am using the #ControllerAdvice for the global exception handler.
the #ControllerAdvice class is RestResponseEntityExceptionHandler.java
#ControllerAdvice
public class RestResponseEntityExceptionHandler
extends ResponseEntityExceptionHandler {
#ExceptionHandler(value = { IllegalArgumentException.class, IllegalStateException.class })
protected ResponseEntity<Object> handleConflict(
RuntimeException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse,
new HttpHeaders(), HttpStatus.CONFLICT, request);
}
}
I was told that by default spring boot should return something like this
{
"timestamp": 1436442596410,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/item"
}
the nonexistent path I give it is
http://localhost:8080/Assignment2C/breweriessdfsdf
the response I get is
<!doctype html>
<html lang="en">
<head>
<title>HTTP Status 404 – Not Found</title>
<style type="text/css">
h1 {
font-family: Tahoma, Arial, sans-serif;
color: white;
background-color: #525D76;
font-size: 22px;
}
h2 {
font-family: Tahoma, Arial, sans-serif;
color: white;
background-color: #525D76;
font-size: 16px;
}
h3 {
font-family: Tahoma, Arial, sans-serif;
color: white;
background-color: #525D76;
font-size: 14px;
}
body {
font-family: Tahoma, Arial, sans-serif;
color: black;
background-color: white;
}
b {
font-family: Tahoma, Arial, sans-serif;
color: white;
background-color: #525D76;
}
p {
font-family: Tahoma, Arial, sans-serif;
background: white;
color: black;
font-size: 12px;
}
a {
color: black;
}
a.name {
color: black;
}
.line {
height: 1px;
background-color: #525D76;
border: none;
}
</style>
</head>
<body>
<h1>HTTP Status 404 – Not Found</h1>
<hr class="line" />
<p><b>Type</b> Status Report</p>
<p><b>Description</b> The origin server did not find a current representation for the target resource or is not
willing to disclose that one exists.</p>
<hr class="line" />
<h3>Apache Tomcat/9.0.26</h3>
</body>
</html>
the spring boot dependency that I am using is
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
my controller class is Breweries_Controller
#RestController
#RequestMapping("/breweries")
public class Breweries_Controller {
#Autowired
Breweries_Service service;
#GetMapping(produces = MediaTypes.HAL_JSON_VALUE)
public Resources<Breweries> getAllBreweries(#RequestParam(name = "limit", required = false) Integer limit , #RequestParam(name = "offset", required = false) Integer offset) {
List<Breweries> allBreweries = service.getAllBreweries();
if(limit == null && offset == null){
limit = 20;
offset = 0;
}
List<Breweries> paginatedList = allBreweries.subList(offset, offset + limit);
for (Breweries b : allBreweries) {
int id = b.getResourceId();
Link self = linkTo(this.getClass()).slash(id).withSelfRel();
b.add(self);
linkTo(methodOn(this.getClass()).getBrewerie(id));
}
Link link = linkTo(this.getClass()).withSelfRel();
Resources<Breweries> result = new Resources<Breweries>(paginatedList, link);
return result;
}
#GetMapping(value = "/{id}", produces = MediaTypes.HAL_JSON_VALUE)
public Resource<Breweries> getBrewerie(#PathVariable("id") int id) {
Resource<Breweries> brewerie = new Resource<Breweries>(service.getBrewerieById(id));
ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).getAllBreweries(5, 50));
brewerie.add(linkTo.withRel("all-breweries"));
return brewerie;
}
#DeleteMapping(value = "/{id}")
#ResponseStatus(HttpStatus.OK)
public void delete(#PathVariable("id") int id) {
Breweries brewerie = service.getBrewerieById(id);
service.deleteBrewerie(brewerie);
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public void create(#RequestBody Breweries b) {
b.setResourceId(0);
b.setAddUser(0);
b.setLastMod(new Date());
service.addBrewerie(b);
}
#PutMapping(value = "/{id}")
#ResponseStatus(HttpStatus.OK)
public void update(#PathVariable("id") int id, #RequestBody Breweries b) {
b.setResourceId(id);
b.setAddUser(0);
b.setLastMod(new Date());
service.editBrewerie(b);
}
}

404 means that spring mvc has failed to find the appropriate end point (controller + method) to run your request.
#ControllerAdvice is relevant only if the method has actually been called and there was an exception. But in your case the flow doesn't even reach controller that's why controller advice doesn't work.
You can customize the error page by creating a controller the implements ErrorController.
This information does not strictly answer the question, but I realize that that's what you really need to resolve the issue so I'll just post a link to the relevant tutorial.

Related

ESPAsyncWebServer request->send_P problem

I am doing a simple example using ESPAsyncWebServer on ESP32. In this context I wrote a html file (there are a slider and a button) and tested it on a browser until the content look well. Then I integrate it in the C++ source code for ESP32. It works and look as expected until I don't add a callback to read the value of the slider.
This is the complete source code:
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
// Replace with your network credentials
const char ssid[] = "Vodafone-A40881218";
const char pswd[] = "rJbFMktHCcqN67Ye";
const int output = 2;
String sliderValue = "0";
// setting PWM properties
const int freq = 5000;
const int ledChannel = 0;
const int resolution = 8;
const char* PARAM_INPUT = "value";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
#if 0
const char old_index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP Web Server</title>
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
h2 {font-size: 2.3rem;}
p {font-size: 1.9rem;}
body {max-width: 400px; margin:0px auto; padding-bottom: 25px;}
.slider { -webkit-appearance: none; margin: 14px; width: 360px; height: 25px; background: #FFD65C; outline: none; -webkit-transition: .2s; transition: opacity .2s;}
.slider::-webkit-slider-thumb {-webkit-appearance: none; appearance: none; width: 35px; height: 35px; background: #003249; cursor: pointer;}
.slider::-moz-range-thumb { width: 35px; height: 35px; background: #003249; cursor: pointer; }
button { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:20%;color:white;font-size:130%; }
.buttons { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:15%;color:white;font-size:80%; }
.buttonsm { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:9%; color:white;font-size:70%; }
.buttonm { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:15%;color:white;font-size:70%; }
.buttonw { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:40%;color:white;font-size:70%; }
.buttong { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:40%;color:white;font-size:130%; }
</style>
</head>
<body>
<h2>ESP Web Server</h2>
<p><span id="textSliderValue">%SLIDERVALUE%</span></p>
<p><input type="range" onchange="updateSliderPWM(this)" id="pwmSlider" min="0" max="21" value="%SLIDERVALUE%" step="1" class="slider"></p>
<a href='/setup'><button class='button'>SETUP</button></a>
<script>
function updateSliderPWM(element) {
var sliderValue = document.getElementById("pwmSlider").value;
document.getElementById("textSliderValue").innerHTML = sliderValue;
console.log(sliderValue);
var xhr = new XMLHttpRequest();
xhr.open("GET", "/slider?value="+sliderValue, true);
xhr.send();
}
</script>
</body>
</html>
)rawliteral";
#endif
const char index_html[] = R"rawliteral(
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP Web Server</title>
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
h2 {font-size: 2.3rem;}
p {font-size: 1.9rem;}
body {max-width: 400px; margin:0px auto; padding-bottom: 25px;}
.slider { width: 360px; }
.slider::-webkit-slider-thumb { width: 50px; height: 50px; }
.slider::-moz-range-thumb { width: 50px; height: 50px; }
button { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:40%;color:white;font-size:130%; }
.buttons { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:15%;color:white;font-size:80%; }
.buttonx { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:9%; color:white;font-size:70%; }
.buttonm { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:15%;color:white;font-size:70%; }
.buttonw { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:40%;color:white;font-size:70%; }
.buttong { border-radius:0.5em;background:#C20000;padding:0.3em 0.3em;width:40%;color:white;font-size:130%; }
</style>
</head>
<body>
<h2>ESP Web Server</h2>
<p><span id="textSliderValue">%SLIDERVALUE%</span></p>
<p><input type="range" onchange="updateSliderPWM(this)" id="pwmSlider" min="0" max="21" value="%SLIDERVALUE%" step="1" class="slider"></p>
<a href='/setup'><button class='button'>SETUP</button></a>
<script>
function updateSliderPWM(element) {
var sliderValue = document.getElementById("pwmSlider").value;
document.getElementById("textSliderValue").innerHTML = sliderValue;
console.log(sliderValue);
var xhr = new XMLHttpRequest();
xhr.open("GET", "/slider?value="+sliderValue, true);
xhr.send();
}
</script>
</body>
</html>
)rawliteral";
// Replaces placeholder with button section in your web page
String processor(const String& var)
{
//Serial.println(var);
if (var == "SLIDERVALUE"){
return sliderValue;
}
return String();
}
#include <Preferences.h>
Preferences Pref;
int32_t g_iVolume = 0;
void setup()
{
// Serial port for debugging purposes
Serial.begin(115200);
Pref.begin("datasetup", false);
g_iVolume = Pref.getInt("volume", 5);
Serial.print("volume="); Serial.println(g_iVolume);
sliderValue = String(g_iVolume);
Pref.end();
// Connect to Wi-Fi
WiFi.begin(ssid, pswd);
Serial.println("Connecting ...");
while (WiFi.status() != WL_CONNECTED)
{ // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
delay(250);
Serial.print('.');
}
// Print ESP Local IP Address
Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
// Send a GET request to <ESP_IP>/slider?value=<inputMessage>
server.on("/slider", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
// GET input1 value on <ESP_IP>/slider?value=<inputMessage>
if (request->hasParam(PARAM_INPUT)) {
inputMessage = request->getParam(PARAM_INPUT)->value();
sliderValue = inputMessage;
int ival = sliderValue.toInt();
Serial.print("ival="); Serial.println(ival);
Pref.begin("datasetup", false);
size_t st = Pref.putInt("volume", ival);
Pref.end();
Serial.print("st="); Serial.println(st);
Pref.begin("datasetup", false);
int vol = Pref.getInt("volume", -1);
Serial.print("volume="); Serial.println(vol);
Pref.end();
}
else {
inputMessage = "No message sent";
}
Serial.println(inputMessage);
request->send(200, "text/plain", "OK");
});
// Start server
server.begin();
}
//------------------------------------------------------------------------
void loop()
{
// put your main code here, to run repeatedly:
}
//------------------------------------------------------------------------
the 1st image is with nullptr instead of processor and the 2nd with processor callback.
I found the problem. The author of ESPAsyncWebServer decided to use the % character as the delimiter for placeholders for the template processor. Unfortunately, the % is quite common in CSS and JavaScript so, writing CSS and JavaScript in HTML file(s) or Strings does not work as expected because the wrong interpretation of % as delimiters of chuncks of text that are not placeholders but CSS or JavaScript code. At the moment there is not a workaround, just do not use % in CSS and JavaScript.
I had the same problem and I fixed it by changing the delimiter character (%) to a ($).
To do this you have to modify the definition of "TEMPLATE_PLACEHOLDER" which is in the file "ESPAsyncWebServer\src\WebResponseImpl.h"
#ifndef TEMPLATE_PLACEHOLDER
#define TEMPLATE_PLACEHOLDER '$' <<<<
#endif

Spring Boot Rest api not producing json error

I'm trying to implement Error handling into my Rest API and testing with postman, when I give an incorrect path postman returns a 404 but its a 404 HTML.
I was told that by default spring boot should return something like this
{
"timestamp": 1436442596410,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/item"
}
the nonexistent path I give it is
http://localhost:8080/Assignment2C/breweriessdfsdf
the response I get is
<!doctype html>
<html lang="en">
<head>
<title>HTTP Status 404 – Not Found</title>
<style type="text/css">
h1 {
font-family: Tahoma, Arial, sans-serif;
color: white;
background-color: #525D76;
font-size: 22px;
}
h2 {
font-family: Tahoma, Arial, sans-serif;
color: white;
background-color: #525D76;
font-size: 16px;
}
h3 {
font-family: Tahoma, Arial, sans-serif;
color: white;
background-color: #525D76;
font-size: 14px;
}
body {
font-family: Tahoma, Arial, sans-serif;
color: black;
background-color: white;
}
b {
font-family: Tahoma, Arial, sans-serif;
color: white;
background-color: #525D76;
}
p {
font-family: Tahoma, Arial, sans-serif;
background: white;
color: black;
font-size: 12px;
}
a {
color: black;
}
a.name {
color: black;
}
.line {
height: 1px;
background-color: #525D76;
border: none;
}
</style>
</head>
<body>
<h1>HTTP Status 404 – Not Found</h1>
<hr class="line" />
<p><b>Type</b> Status Report</p>
<p><b>Description</b> The origin server did not find a current representation for the target resource or is not
willing to disclose that one exists.</p>
<hr class="line" />
<h3>Apache Tomcat/9.0.26</h3>
</body>
</html>
the spring boot dependency that I am using is
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
my controller class is breweries_Controller
#RestController
#RequestMapping("/breweries")
public class Breweries_Controller {
#Autowired
Breweries_Service service;
#GetMapping(produces = MediaTypes.HAL_JSON_VALUE)
public Resources<Breweries> getAllBreweries(#RequestParam(name = "limit", required = false) Integer limit , #RequestParam(name = "offset", required = false) Integer offset) {
List<Breweries> allBreweries = service.getAllBreweries();
if(limit == null && offset == null){
limit = 20;
offset = 0;
}
List<Breweries> paginatedList = allBreweries.subList(offset, offset + limit);
for (Breweries b : allBreweries) {
int id = b.getResourceId();
Link self = linkTo(this.getClass()).slash(id).withSelfRel();
b.add(self);
linkTo(methodOn(this.getClass()).getBrewerie(id));
}
Link link = linkTo(this.getClass()).withSelfRel();
Resources<Breweries> result = new Resources<Breweries>(paginatedList, link);
return result;
}
#GetMapping(value = "/{id}", produces = MediaTypes.HAL_JSON_VALUE)
public Resource<Breweries> getBrewerie(#PathVariable("id") int id) {
Resource<Breweries> brewerie = new Resource<Breweries>(service.getBrewerieById(id));
ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).getAllBreweries(5, 50));
brewerie.add(linkTo.withRel("all-breweries"));
return brewerie;
}
#DeleteMapping(value = "/{id}")
#ResponseStatus(HttpStatus.OK)
public void delete(#PathVariable("id") int id) {
Breweries brewerie = service.getBrewerieById(id);
service.deleteBrewerie(brewerie);
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public void create(#RequestBody Breweries b) {
b.setResourceId(0);
b.setAddUser(0);
b.setLastMod(new Date());
service.addBrewerie(b);
}
#PutMapping(value = "/{id}")
#ResponseStatus(HttpStatus.OK)
public void update(#PathVariable("id") int id, #RequestBody Breweries b) {
b.setResourceId(id);
b.setAddUser(0);
b.setLastMod(new Date());
service.editBrewerie(b);
}
}
Please check if your controller class is within source package (Package in which class with #SpringBootApplication exist ). If not, Add #ComponentScan annotation along with #SpringBootApplication to make sure your controller class is being scanned for endpoints. It's often an issue to me to!

Issue while calling web api controller from service in angular2

I am doing angular quick start tutorial.
So I am just Hero tutorial that specifies in angular2 quickstart on its website.
That runs fine for me. it binds static array data and perform CRUD.
But now I want to learn how to call web API method for getting data from database.
So I am calling webapi method in getHeroes() method of service and calling that method from init method-ngOnInit() of component but it gives error like this.
please correct if I am wrong.
Got this error, while calling Web api controller from my service in angular2
EXCEPTION:
Error: Uncaught (in promise): No provider for Http! (DashboardComponent -> HeroService -> Http)BrowserDomAdapter.logError # angular2.dev.js:23925
angular2.dev.js:23925 STACKTRACE:BrowserDomAdapter.logError # angular2.dev.js:23925
angular2.dev.js:23925 Error: Uncaught (in promise): No provider for Http! (DashboardComponent -> HeroService -> Http)
at resolvePromise (angular2-polyfills.js:602)
at angular2-polyfills.js:579
at ZoneDelegate.invoke (angular2-polyfills.js:390)
at Object.NgZoneImpl.inner.inner.fork.onInvoke (angular2.dev.js:2126)
at ZoneDelegate.invoke (angular2-polyfills.js:389)
at Zone.run (angular2-polyfills.js:283)
at angular2-polyfills.js:635
at ZoneDelegate.invokeTask (angular2-polyfills.js:423)
at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (angular2.dev.js:2118)
at ZoneDelegate.invokeTask (angular2-polyfills.js:422)BrowserDomAdapter.logError # angular2.dev.js:23925
angular2-polyfills.js:528 Unhandled Promise rejection: No provider for Http! (DashboardComponent -> HeroService -> Http) ; Zone: angular ; Task: Promise.then ; Value: NoProviderErrorconsoleError # angular2-polyfills.js:528
angular2-polyfills.js:530 Error: Uncaught (in promise): No provider for Http! (DashboardComponent -> HeroService -> Http)(…)consoleError # angular2-polyfills.js:530
Here is my Hero service:
import {Injectable} from 'angular2/core';
import {Http,Response,Headers} from 'angular2/http';
import 'rxjs/add/operator/map'
import {Observable} from 'rxjs/Observable';
import {Hero} from '/Scripts/FirstEx_Ts/Hero.ts';
import {HEROES} from '/Scripts/FirstEx_Ts/MockHeros.ts';
#Injectable()
export class HeroService {
private headers: Headers;
constructor(private _http:Http) {
}
getHeroes(){
return this._http.get("http://localhost:54046/api/Heromanage/GetAllHeroes")
.map((response: Response) => <Hero[]>response.json())
.catch(this.handleError);
}
getHeroesSlowly() {
return new Promise<Hero[]>(resolve =>
setTimeout(() => resolve(HEROES), 2000) // 2 seconds
);
}
getHero(id: number) {
return Promise.resolve(HEROES).then(
heroes => heroes.filter(hero => hero.id === id)[0]
);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
And here is my Component from where I am calling service method:
import {Component, OnInit} from 'angular2/core';
import {Http,Response,Headers} from 'angular2/http';
import { CORE_DIRECTIVES } from 'angular2/common';
import {Router} from 'angular2/router';
import {Hero} from '/Scripts/FirstEx_Ts/Hero.ts';
import {HeroService} from '/Scripts/FirstEx_Ts/HeroService.ts';
#Component({
selector: 'my-dashboard',
providers: [HeroService],
templateUrl: '/Templates/DashboardComponent.html',
directives: [CORE_DIRECTIVES],
styles: [ `
[class*='col-'] {
float: left;
}
*, *:after, *:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
h3 {
text-align: center; margin-bottom: 0;
}
[class*='col-'] {
padding-right: 20px;
padding-bottom: 20px;
}
[class*='col-']:last-of-type {
padding-right: 0;
}
.grid {
margin: 0;
}
.col-1-4 {
width: 25%;
}
.module {
padding: 20px;
text-align: center;
color: #eee;
max-height: 120px;
min-width: 120px;
background-color: #607D8B;
border-radius: 2px;
}
h4 {
position: relative;
}
.module:hover {
background-color: #EEE;
cursor: pointer;
color: #607d8b;
}
.grid-pad {
padding: 10px 0;
}
.grid-pad > [class*='col-']:last-of-type {
padding-right: 20px;
}
#media (max-width: 600px) {
.module {
font-size: 10px;
max-height: 75px; }
}
#media (max-width: 1024px) {
.grid {
margin: 0;
}
.module {
min-width: 60px;
}
}
`]
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(
private _router: Router,
private _heroService: HeroService) {
debugger;
}
**ngOnInit() {
alert('hi');
debugger;
this._heroService
.getHeroes()
.subscribe((heroes:Hero[]) => this.heroes = data,
error => console.log(error),
() => console.log('Get all Items complete'));
}**
gotoDetail(hero: Hero) {
let link = ['HeroDetail', { id: hero.id }];
this._router.navigate(link);
}
}
you may try below,
Angular version < RC5
include HTTP_PROVIDERS in the providers array of Component metadata.
Angular version >= RC5
import HttpModule in the Module containing your component.
Hope this helps!!

Laravel 5.2 Entrust: redirect user if he manually adds restricted URL

With Entrust, I implemented how user will be redirected to his own dashboard after login by adding this method in Authcontroller.php
protected function authenticated()
{
if(\Auth::user()->hasRole(['super_admin',]) ) {
return redirect('/dashboard');
} else if(\Auth::user()->hasRole(['staff_admin']) ) {
return redirect('/staff/dashboard');
} else if(\Auth::user()->hasRole(['subadmin_admin']) ) {
return redirect('/subadmin/dashboard');
}
}
What challenge I am facing right now is, for eg. if staff had logged in and redirected to his dashboard as
domain.com/staff/dashboard
but if he manually deletes the staff from url and tries to access Super-Admin Dashboard then Entrust throws 403 Error, but I want to redirect him to his dashboard, with message that " You are not authorized".
I tried to implement same code in RedirectIfAuthenticated middleware, but it gave error as hasRole called on Null.
Your DashboardController add constructor.
Example Code
class UserController extends Controller
{
public function __construct()
{
$this->middleware(['role:super_admin']);
}
public function index()
{
return view('dashboard');
}
}
Then, error folder add 403.blade.php like so:
<!DOCTYPE html>
<html>
<head>
<title>Be right back.</title>
<link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
color: #B0BEC5;
display: table;
font-weight: 100;
font-family: 'Lato', sans-serif;
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 72px;
margin-bottom: 40px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">You are not authorized.</div>
</div>
</div>
</body>
</html>

how to get particular search result in elastic using jest with spring mvc

here is my sample code but able get values but there may be a issue plz help me
when i search in search form i need that particular result..
#Controller
public class SearchController {
ModelAndView mv;
SearchModel log;
#RequestMapping("/Search.htm")
public #ResponseBody ModelAndView getSearchModelList() throws Exception
{
String clusterIP = "localhost";
String port = "9200";
//setup client
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig
.Builder("http://" + clusterIP + ":" + port)
.multiThreaded(true)
.build());
JestClient client = factory.getObject();
Search search = new Search.Builder("{ \"query\": { \"match\": {} } }")
.addIndex("eix")
.addType("articles")
.build();
//results print here
JestResult result = client.execute(search);
List<SearchModel> resultLogs = result.getSourceAsObjectList(SearchModel.class);
for(SearchModel log: resultLogs){
System.out.println(log);
mv.addObject("log", log);
}
return mv;
}}
and here my jsp code.just print search form
<%# 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>Eix</title>
<style type="text/css">
#tfheader{
background-color:#c3dfef;
}
#tfnewsearch{
float:right;
padding:20px;
}
.tftextinput{
margin: 0;
padding: 5px 15px;
font-family: Arial, Helvetica, sans-serif;
font-size:14px;
border:1px solid #0076a3; border-right:0px;
border-top-left-radius: 5px 5px;
border-bottom-left-radius: 5px 5px;
}
.tfbutton {
margin: 0;
padding: 5px 15px;
font-family: Arial, Helvetica, sans-serif;
font-size:14px;
outline: none;
cursor: pointer;
text-align: center;
text-decoration: none;
color: #ffffff;
border: solid 1px #0076a3; border-right:0px;
background: #0095cd;
background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5));
background: -moz-linear-gradient(top, #00adee, #0078a5);
border-top-right-radius: 5px 5px;
border-bottom-right-radius: 5px 5px;
}
.tfbutton:hover {
text-decoration: none;
background: #007ead;
background: -webkit-gradient(linear, left top, left bottom, from(#0095cc), to(#00678e));
background: -moz-linear-gradient(top, #0095cc, #00678e);
}
/* Fixes submit button height problem in Firefox */
.tfbutton::-moz-focus-inner {
border: 0;
}
.tfclear{
clear:both;
}
</style>
</head>
<body>
<form id="tfnewsearch" method="post" action="Search.htm">
<input type="text" class="tftextinput" name="q" size="21" maxlength="120">
<input type="submit" value="search" class="tfbutton">
</form>
<div class="tfclear"></div>
</body>
</html>
and here print search values in this jsp..
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Eix</title>
<style type="text/css">
</style>
</head>
<body>
<h2>${log}</h2>
</body>
</html>

Resources