WhitelabelError Page - spring

While I am doing simple spring boot application that showing a message in jsp page, I am getting the white label error page, what can be the reason?
in my application.java page:
package net.aswathy.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringbootWebAppJspApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootWebAppJspApplication.class, args);
}
}
appplication properties:
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
in my controller:
package net.aswathy.springboot;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class scontroller {
#GetMapping("/welcome")
public String welcome(Model model) {
model.addAttribute("message","Helloworld..!");
return "welcome";
}
}
in my jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>

Related

Can't see a message form modelAndView Object in JSP representation page

Good afternoon, sorry if the question has already been asked but ... I did not find the answer in those versions.
I’m studying spring by tuturial (https://www.youtube.com/watch?v=JfeCmn8NT88), trying to write a simple CRUD (I haven’t even reached to logic of the program)and i face the problem: Can't see a message form modelAndView Object in JSP representation page, IDEA tells that cannot resolve variable.
I understand that this may be redundant but here are all my files.
my project hierarchy
WebAppInitializer
package com.customermanager.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(WebMVCConfig.class);
ServletRegistration.Dynamic dispacher = servletContext.addServlet("SpringDispacher", new DispatcherServlet(applicationContext));
dispacher.setLoadOnStartup(1);
dispacher.addMapping("/");
}
}
WebMVCConfig
package com.customermanager.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.customermanager.*")
public class WebMVCConfig {
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
CustomerController
package com.customermanager.customer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class CustomerController {
#RequestMapping(value = "/")
public ModelAndView home() {
ModelAndView model = new ModelAndView("index");
model.addObject("message", "hello world");
return model;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
</web-app>
index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Customer Manager</title>
</head>
<body>
<H1>${message}</H1>
<p>Message: ${message}</p>
Hello
</body>
</html>
In output i dont see my message: Hello from Spring MVC
thanks in advance for your help

Spring boot authentication issue?

As you can see on : http://website-live-245110.appspot.com/ (gccloud hosted site) following the code logic, any username with 4 characters should be able to log in. Although this is not the case at the moment and i have trouble understanding why.
You should try logging in multiple times to grasp the issue.
CustomAuthenticationProvider.java
package com.spring.authprovider;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider{
#Autowired
private ThirdPartyAuthProviderClient thirdPartyAuthProviderClient;
// one a user logs in, the authentication variable is filled with the details of the authentication
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// when the user logs in to the application, our object will be filled by spring
String name = authentication.getName();
Object password = authentication.getCredentials(); //object that encapsulates password that user types
// not printing or storing password anyone
if(thirdPartyAuthProviderClient.shouldAuthenticate(name,password)) {
// the array list is for roles, because we are not using it now, we are sending it an empty one
return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>());
} else {
System.out.println("authentication failed for user: " + name);
}
return null;
}
#Override
public boolean supports(Class<?> authentication) {
// there are multiple ways of authentication, use use username and password
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
ThirdPartyAuthProviderClient.java
package com.spring.authprovider;
import org.springframework.stereotype.Component;
#Component
public class ThirdPartyAuthProviderClient {
//emulates request to third party application
public boolean shouldAuthenticate(String username, Object password) {
// 3rd party request to see if user is correct or no or should be logged in
// user with username with 4 digits can be logged in to the application
return username.length() == 4;
}
}
WebSecurityConfig.java
package com.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import com.spring.authprovider.CustomAuthenticationProvider;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomAuthenticationProvider authProvider;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home", "/time").permitAll() // any request matching /, /home, /time
// can be accessed by anyone
.anyRequest().authenticated() // any other request needs to be authenticated
.and().authorizeRequests().antMatchers("/admin/**") // only admin can access /admin/anything
.hasRole("ADMIN")
.and().formLogin().loginPage("/login") // permit all to form login--- we use loginPage to use custom page
.permitAll()
.and().logout() // permit all to form logout
.permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//specify auth provider
auth.authenticationProvider(authProvider);
}
// configuration of static resources
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/templates/**", "/assets/**");
}
}
MvcConfig.java
package com.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
Templates
hello.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="#{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>
home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href="#{/hello}">here</a> to see a greeting.</p>
</body>
</html>
login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="#{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
I expect it to either log me in when a username with 4 characters is entered, Or output Invalid username and password. Error.
Code is here : https://github.com/jeffpascal/Spring-and-springboot/tree/devs/SpringSecurity

Spring Boot - unable to resolve JSP page

application.yml
spring:
mvc.view:
prefix: /
suffix: .jsp
SampleController.java
package springboot_demo;
import javax.annotation.Resource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import springboot_demo.service.StudentService;
#Controller
#SpringBootApplication
public class SampleController extends SpringBootServletInitializer{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleController.class);
}
#Resource
private StudentService studentService;
#RequestMapping("/")
public String home(Model model) {
model.addAttribute("data", studentService.list());
return "index";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
The 'data' is correctly fetched from database, but the JSP page seems not compiled. I visit http://localhost:8080 and the browser shows me like this:
<%#page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h2>Hello World!</h2>
<c:forEach items="${data }" var="i">
<h2>${i.id }${i.name }</h2>
</c:forEach>
</body>
</html>

Passing String from jsp to Controller in Spring

I created a project with Spring + JPA + Hibernate. I want to pass a string from jsp to controller(removeUtente method). If I click on the link I delete the row from the database .. Where am I doing wrong? Excuse me for my english..The controller receives the string from jsp and calls the method to remove it.
Thanks
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>
<h2>Lista utenti</h2>
<table border="1">
<c:forEach var="utente" items="${lista }">
<tr>
<td>
<c:out value="${utente.id}"/>
</td>
<td>
<c:out value="${utente.cognome}"/>
</td>
<td>
<c:out value="${utente.nome}"/>
</td>
<td>
<c:out value="${utente.eta}"/>
</td>
<td>
<c:url var="url" value="/remove">
<c:param name="id" value="${utente.id }"/>
</c:url>
click to delete
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
UtenteController.java
package controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import persistence.UtenteDAO;
import bean.Utente;
#Controller
public class UtenteController {
#Autowired
UtenteDAO utenteDAO;
#RequestMapping(value="/add",method=RequestMethod.POST)
public String addUtente(#ModelAttribute Utente u){
utenteDAO.inserisciUtente(u);
return "index";
}//addUtente
#RequestMapping(value="/show",method=RequestMethod.GET)
public String getUtenti(ModelMap model){
List<Utente> lista=utenteDAO.listaUtenti();
model.addAttribute("lista", lista);
return "showlista";
}//getUtenti
#RequestMapping(value="/remove",method=RequestMethod.GET)
public String removeUtente(#RequestParam String id){
utenteDAO.rimuovi(id);
return "showlista";
}//removeUtente
}//UtenteController
Utente.java
package bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="utente")
public class Utente {
#Id
#GeneratedValue
#Column(name="id")
private Integer id;
#Column(name="cognome")
private String cognome;
#Column(name="nome")
private String nome;
#Column(name="eta")
private Integer eta;
public Integer getId(){return id;}//getId
public void setId(Integer id){this.id=id;}//setId
public String getCognome(){return cognome;}//getCognome
public void setCognome(String cognome){this.cognome=cognome;}//setCognome
public String getNome(){return nome;}//getNome
public void setNome(String nome){this.nome=nome;}//setNome
public Integer getEta(){return eta;}//getEta
public void setEta(Integer eta){this.eta=eta;}//setEta
#Override
public String toString(){
return "id:"+id+" cogn:"+cognome+" nome:"+nome+" eta:"+eta;
}//toString
}//Utente
UtenteDAOImpl.java
package persistence;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import bean.Utente;
#Transactional
public class UtenteDAOImpl implements UtenteDAO {
#PersistenceContext
EntityManager em;
public void inserisciUtente(Utente u){
em.persist(u);
}//inserisciUtente
#SuppressWarnings("unchecked")
public List<Utente> listaUtenti(){
Query q=em.createQuery("SELECT u FROM Utente u");
List<Utente> ris=q.getResultList();
return ris;
}//listaUtenti
public void rimuovi(String idUtente){
Query q=em.createQuery("DELETE FROM Utente AS u WHERE u.id =:id");
q.setParameter("id", idUtente);
q.executeUpdate();
}//rimuovi
}//inserisciUtente

Image not coming from servlet when called from jsp

I am trying to fetch image from oracle database.
Flow is : JSP (to read photo_id) -> JSP -> which internally calls Servlet from src attribute of HTML image tag.
ImageGetter.jsp (Asking for photo id)
<%# 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>your Pic</title>
</head>
<body>
<form id="form2" enctype="multipart/form-data" action="getPhoto.jsp" method="get">
<table>
<tr>
<td>Enter Photo Id :</td>
<td><input type="text" name="id"/></td>
</tr>
</table>
<p/>
<input type="submit" value="fetch Photo"/>
</form>
</body>
</html>
getPhoto.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>Your photo</title>
</head>
<body>
<% String p_id=request.getParameter("id");%>
<table>
<tr><td><%=p_id%></td></tr>
<tr><td><img src="/getPic?photoid=<%=p_id%>" /></td></tr>
</table>
</body>
</html>
getPic in src attribute of img tag is servlet.
getPic.java
package com.kp.imagehandler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kp.imagehandler.Image;
/**
* Servlet implementation class getPic
*/
public class getPic extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public getPic() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String imageId = request.getParameter("photoid");
System.out.println(imageId);
InputStream photoStream = (new Image()).getImageStream(imageId);
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams
input = new BufferedInputStream(photoStream, 200000);
output = new BufferedOutputStream(response.getOutputStream(),
200000);
// Write file contents to response.
byte[] buffer = new byte[200000];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
output.close();
input.close();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Image.java:
package com.kp.imagehandler;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Image {
// Init ---------------------------------------------------------------------------------------
public InputStream getImageStream(String pid)
{
InputStream IS=null;
try {
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#10.75.122.69:1521:devdb",
"s3", "s3");
Statement stmt = connection.createStatement ();
ResultSet rset = stmt.executeQuery ("SELECT photo FROM photo_holder where id="+pid);
while(rset.next())
{
IS=rset.getBinaryStream("photo");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return IS;
}
// Implement default getters and setters here.
}
web.xml :
<servlet>
<description>getPic</description>
<display-name>getPic</display-name>
<servlet-name>getPic</servlet-name>
<servlet-class>com.kp.imagehandler.getPic</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getPic</servlet-name>
<url-pattern>/getPic</url-pattern>
</servlet-mapping>
Table definition:
create table PHOTO_HOLDER
(
ID NUMBER(5) not null,
TITLE VARCHAR2(50),
PHOTO BLOB
)
but after hitting fetch photo I am just getting photo id but not image.
Here I am not sure whether servlet is getting fired or not.
please help.thanks in advance.
There may be an issue with the URL formed for the image.
Please validate it again by simply looking at the source code of the generated JSP in the browser.
Just debug your code or use logging to investigate the issue.
Try it again after appending context path before the Servlet/JSP path as shown below:
<form id="form2" enctype="multipart/form-data" action="<%=request.getContextPath() %>/getPhoto.jsp" method="get">
<img src="<%=request.getContextPath() %>/getPic?photoid=<%=p_id%>" />

Resources