Receiving a 404 running spring boot - java

Hello i'm new to spring and i'm receiving a 404 error when attempting to use spring boot. When attempting to view the url in the browser i keep getting a 404 error. Please could someone assist and point me to what is wrong. I placed a debugger in the controller to print HH but i observed it never goes into the controller as it fails to print "HH" on the console.
I also noticed this from console:
:50.894 INFO 11249 --- [lication.main()] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2015-11-15 07:11:50.894 INFO 11249 --- [lication.main()] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.
Below is my controller:
#RestController
public class TestController {
#RequestMapping(value="/person")
public String intro(){
System.out.println("HH");
return "index";
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springExample.www</groupId>
<artifactId>Hotel-Management</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
MainApplication.java:
#SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
index.html is defined in src/main/resources/templates:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initialscale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5
elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the
page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/
3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/
1.4.2/respond.min.js"></script>
<![endif]-->
<style>
.box {
background-color:#d3d3d3
}
</style>
</head>
<body>
<h1>Hello, world!</h1>
<div class="container">
<div class="row">
<div class="col-md-6 box">Content</div>
<div class="col-md-6 box">Content</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/
jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>
</body>
</html>

There a few things to look at:
Use #Controller rather than #RestController. The first is designed to handle views, the second is designed to return raw data.
Move the views to src/main/java/webapp/WEB-INF/. This is the conventional location for views, rather than /src/main/resources.
Change the return value of the intro() method from index to templates/index. The entire path to the view matters.
Add a class annotated with #Configuration that defines a ViewResolver bean that looks for .html views (see this answer).

Related

Spring MVC with Thymeleaf + Bootstrap using webjars

I have a Spring project where I included the following webjars into pom.xml:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.1.1</version>
</dependency>
Then I included in my HTML view the following link and scripts:
<link rel="stylesheet" href="#{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
<script src="#{/webjars/jquery/3.1.1/jquery.min.js}"></script>
<script src="#{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
But it didn't work, no mapping found:
[org.springframework.web.servlet.PageNotFound] (default task-15) No mapping found for HTTP request with URI [/TestPublicWeb-0.0.1-SNAPSHOT/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css] in DispatcherServlet with name 'testapp'
...so I tried to include the following mapping into servlet.xml:
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
But with this, mapping for my /TestApplication is not found:
[org.springframework.web.servlet.PageNotFound] (default task-13) No mapping found for HTTP request with URI [/TestApplication/] in DispatcherServlet with name 'testapp'
How should webjars be included in a Spring project in a correct way?
The problem is that you are mixing the standard HTML href tag with Thymeleaf's syntax #{}. Change it as follows:
<link rel="stylesheet" th:href="#{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
<script th:src="#{/webjars/jquery/3.1.1/jquery.min.js}"></script>
<script th:src="#{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
And if you are using Spring Security you need also specify the authorization to your webjars in the configure(HttpSecurity http) method like:
http.authorizeRequests().antMatchers("/webjars/**").permitAll();
A couple things I could think of as to why the above is not working for you. Make sure you are using spring mvc namespace inside of your servlet.xml file. Looks something like:
<bean xmlns:mvc="http://www.springframework.org/schema/mvc"....
Also not sure why you are trying to access assets using #{..} when you have specified the classpath. Try removing the #{..} like so:
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
<script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>

not getting model filled from jsp in spring mvc

Same error even adding #ModelAttributeI am not able to get the model class filled while clicking on button on jsp. In Database a new field is created but value are going null(Because model is not getting filled).
Please help me out on this.
Thanks in advance.
My Model class is:
package model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "conversion")
public class Conversion {
#Id
#GeneratedValue
private int conversionId;
#Column(name = "conversionFrom")
private String conversionFrom;
#Column(name = "conversionFromValue")
private int conversionFromValue;
#Column(name = "conversionTo")
private String conversionTo;
#Column(name = "conversionToValue")
private int conversionToValue;
#Column(name = "conversionDate")
private Date conversionDate;
public int getConversionId() {
return conversionId;
}
public void setConversionId(int conversionId) {
this.conversionId = conversionId;
}
public String getConversionFrom() {
return conversionFrom;
}
public void setConversionFrom(String conversionFrom) {
this.conversionFrom = conversionFrom;
}
public int getConversionFromValue() {
return conversionFromValue;
}
public void setConversionFromValue(int conversionFromValue) {
this.conversionFromValue = conversionFromValue;
}
public String getConversionTo() {
return conversionTo;
}
public void setConversionTo(String conversionTo) {
this.conversionTo = conversionTo;
}
public int getConversionToValue() {
return conversionToValue;
}
public void setConversionToValue(int conversionToValue) {
this.conversionToValue = conversionToValue;
}
public Date getConversionDate() {
return conversionDate;
}
public void setConversionDate(Date conversionDate) {
this.conversionDate = conversionDate;
}
}
My controller method is:
#RequestMapping("/saveConversion")
public ModelAndView saveConversion(HttpServletRequest request, HttpServletResponse response, Model model,
Conversion conversion) throws ServletException, IOException, ParseException {
System.out.println("In saveConversion");
Boolean boolean1 = serviceDao.setConversion(conversion);
if (boolean1) {
model.addAttribute("conversionSaved", "Conversion saved successfully!");
} else {
model.addAttribute("conversionSaved", "Conversion Not saved!");
}
return new ModelAndView("setConversion");
}
My Jsp is:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%#page import="model.Test"%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Lexis Nexis Admin Set Conversion Page</title>
<!--css and js starts-->
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<script src="jQueryAssets/jquery_lib.js"></script>
<script>
function SaveConversion() {
var params = $("#Conversion_form").serialize();
alert(params);
$.ajax({
method : "POST",
url : "saveConversion",
data : {
'params' : params
},
success : function(result) {
alert(result);
$("#responseDiv").html(result);
messageDisplay();
return false;
}
})
}
function messageDisplay() {
alert("${conversionSaved}");
}
</script>
</head>
<body onload="clearData()">
<div class="mainpage">
<div class="add_admin_form">
<form id="Conversion_form" method="post" name="Conversion">
<div class="add_admin_form_label">
<spring:message code="CONVERSION_FROM" />
</div>
<div class="add_admin_form_field">
<select name="conversionFrom" id="conversionFrom" class="dropdown2">
<option value="USD"><spring:message code="USD" /></option>
<option value="INR"><spring:message code="INR" /></option>
</select> <input name="conversionFromValue" id="conversionFromValue"
type="text" class="textbox1" value="${conversion.conversionFromValue}" required />
</div>
<div class="add_admin_form_label">
<spring:message code="CONVERSION_TO" />
</div>
<div class="add_admin_form_field">
<select name="conversionTo" id="conversionTo" class="dropdown2">
<option value="INR"><spring:message code="INR" /></option>
<option value="USD"><spring:message code="USD" /></option>
</select> <input name="conversionToValue" id="conversionToValue" type="text"
class="textbox1" required />
</div>
<div class="add_admin_form_field">
<input type="button" value="" class="create"
onclick="SaveConversion()" />
</div>
</form>
</div>
</div>
<div class="clear"></div>
<div class="clear"></div>
</body>
</html>
My hibernate.cfg.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated file - Do not edit! -->
<hibernate-configuration>
<!-- a SessionFactory instance listed as /jndi/name -->
<session-factory>
<!-- User / Password -->
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- Database Settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- for performance reasons changed to MyISAM from org.hibernate.dialect.MySQLInnoDBDialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/quotebuilder</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<!-- Database Scheme Auto Update -->
<property name="hbm2ddl.auto">update</property>
<!-- properties -->
<property name="show_sql">true</property>
<property name="use_outer_join">false</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory</property>
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- <property name="connection.provider_class ">org.hibernate.connection.C3P0ConnectionProvider</property> -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hibernate.cache.use_query_cache">false</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="hibernate.generate_statistics">false</property>
<property name="hibernate.cache.use_structured_entries">false</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.timeout">100</property>
<!-- mapping files -->
<mapping class="model.User" />
<mapping class="model.Quotation" />
<mapping class="model.CustomerSize" />
<mapping class="model.CustomerSegment" />
<mapping class="model.Admin" />
<mapping class="model.Customer" />
<mapping class="model.CustomerTypeDiscount" />
<mapping class="model.EmployeeLevelDiscount" />
<mapping class="model.Product" />
<mapping class="model.ProductVolumeDiscount" />
<mapping class="model.TitleAuthorTag" />
<mapping class="model.TitleContentTag" />
<mapping class="model.Conversion" />
</session-factory>
</hibernate-configuration>
Dispatcher-servlet is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="login" class="controller.LoginController" />
<bean id="levelManagement" class="controller.LevelManagementController" />
<bean id="user" class="controller.UserController" />
<bean id="home" class="controller.HomeController" />
<bean id="report" class="controller.ReportController" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames" value="WEB-INF/properties/messages" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml is:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
pom.xml is:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.logiquebrain</groupId>
<artifactId>QuoteBuilderAdmin</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>QuoteBuilderAdmin Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- Hibernate core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.2.Final</version>
</dependency>
<!-- optional -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-osgi</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-proxool</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-infinispan</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.0.2.Final</version>
</dependency>
<!-- Add on 03-12-2015 -->
<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version> </dependency> <dependency> <groupId>dom4j</groupId>
<artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency>
<groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId>
<version>1.1.1</version> </dependency> <dependency> <groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency>
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version>
</dependency> <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId>
<version>3.1</version> </dependency> <dependency> <groupId>javax.transaction</groupId>
<artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency>
<groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId>
<version>2.5.1</version> </dependency> -->
<!-- Add on 03-12-2015 -->
<!-- Add on 04-12-2015 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<!-- Add on 04-12-2015 -->
<!-- Add on 07-12-2015 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<!-- Add on 07-12-2015 -->
</dependencies>
<build>
<finalName>QuoteBuilderAdmin</finalName>
<!-- Add on 07-12-2015 -->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
<!-- Add on 07-12-2015 -->
</build>
</project>
do the changes as mentioned by #alan and also make following changes to your js function:
function SaveConversion() {
var params = $("#Conversion_form").serialize();
alert(params);
$.ajax({
method : "POST",
url : "saveConversion",
data : params, //this line is changed
success : function(result) {
alert(result);
$("#responseDiv").html(result);
messageDisplay();
return false;
}
})
}
the js function as per the question was sending only one parameter "param" which had value of serialized form value. After making above change it should be working. I have verified the same using network tab of the browser. You can see it for yourself if needed.
If you want to Spring to automatically bind the submitted parameters to a Conversion instance then you need to use the #ModelAttribute annotation in your method signature.
#RequestMapping("/saveConversion")
public ModelAndView saveConversion(#ModelAttribute Conversion conversion, Model model) throws ServletException, IOException, ParseException {
System.out.println("In saveConversion");
Boolean boolean1 = serviceDao.setConversion(conversion);
if (boolean1) {
model.addAttribute("conversionSaved", "Conversion saved successfully!");
} else {
model.addAttribute("conversionSaved", "Conversion Not saved!");
}
return new ModelAndView("setConversion");
}
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-method-args
An #ModelAttribute on a method argument indicates the argument should
be retrieved from the model. If not present in the model, the argument
should be instantiated first and then added to the model. Once present
in the model, the argument’s fields should be populated from all
request parameters that have matching names. This is known as data
binding in Spring MVC, a very useful mechanism that saves you from
having to parse each form field individually.

Spring boot with authentication - login page not found (404)

I have a problem with my spring application since I've tried to include some security things.
After building a small working app including angularJS I followed this spring security tutorial but I can't get it started. When I try to access any part of the app, the security modul wants to redirect to http://localhost:8080/login... but can't find it.
There was an unexpected error (type=Not Found, status=404).
No message available
Maybe I'm just missing a small thing but I can't figure out what it is ^^
Here is my code...
folder structure:
src/main/java
+-Application.java
+-SecurityConfiguration.java
src/main/resources
+-static
+-index.html
+-templates
+-login.html
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.BUILD-SNAPSHOT</version>
</parent>
<!-- Additional lines to be added here... -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1100-jdbc4</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
</dependencies>
Application.java:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}
SecurityConfiguration.java:
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().anyRequest().authenticated();
http
.formLogin().failureUrl("/login?error")
.defaultSuccessUrl("/")
.loginPage("/login")
.permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login")
.permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
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 followed my own hint in the comment above and figured out I forgot extends WebMvcConfigurerAdapter at my Application.class
That solved the Problem!
Where is your login.html located? Can you get to /login directly in a browser? I suspect you don't have your ViewResolver set up properly. If you can't go directly to /login, that's your problem. Look at application.properties values spring.view.prefix and spring.view.suffix.
If you can get there directly, you might be dealing with a hidden error. Spring Boot includes an AutoConfiguration that swallows exceptions and throws a 404. You might want to exclude it (change #EnableAutoConfiguration to #EnableAutoConfiguration(exclude=ErrorMvcAutoConfiguration.class). That will enable you to see any errors that are thrown during the request processing.

JSP & EL conflict with JSF 1.x actionListener

I was working on a JSF 1.x example, which has some EL conflict in JSPs.
the line actionListener="#{helloBean.addControls} is shooting an issue.
The error is :
HTTP Status 500 - /JSP/hello.jsp (line: 37, column: 2) A literal value was specified for attribute actionListener that is defined as a deferred method with a return type of void. JSP.2.3.4 does not permit literal values in this case
My project Description is as follows :
Package Structure :
Maven Dependencies :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.achutha.labs</groupId>
<artifactId>02JsfExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>02JsfExample</name>
<dependencies>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>1.2_14</version>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>1.2_14</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<!-- EL -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>el-impl</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<build>
<finalName>JavaServerFaces</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<configuration>
<url>http://localhost:8090/manager/text</url>
<server>TomcatServer</server>
<path>/balaji</path>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Faces Configuration :
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
"http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config>
<managed-bean>
<description> The one and only HelloBean.</description>
<managed-bean-name>helloBean</managed-bean-name>
<managed-bean-class>com.achutha.bean.HelloBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<navigation-rule>
<description>Navigation From the Hello Page.</description>
<from-view-id>/JSP/hello.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/JSP/goodbye.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Deployment Descriptor (web.xml) :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Hello, World!</display-name>
<description>Welcome to JavaServer Faces</description>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/JSP/hello.jsp</welcome-file>
</welcome-file-list>
</web-app>
hello.jsp
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
<html>
<head>
<title>JSF In Action - Hello, world!</title>
</head>
<body>
<h:form id="welcomeForm">
<h:outputText id="welcomeOutput" value="Welcome to JavaServer Faces !"
style="font-family: Arial, sans-serif; font-size: 23; color: green;" />
<p>
<h:message id="errors" for="helloInput" style="color: red" />
</p>
<p>
<h:outputLabel for="helloInput">
<h:outputText id="helloInputLabel"
value="Enter Number of controls to display: ">
</h:outputText>
<h:inputText id="helloInput" value="#{helloBean.numControls}"
required="true">
<f:validateLongRange minimum="1" maximum="500" />
</h:inputText>
</h:outputLabel>
</p>
<p>
<h:panelGrid id="controlPanel" binding="#{helloBean.controlPanel}"
columns="20" border="1" cellspacing="0" />
</p>
<h:commandButton id="redisplayCommand" type="submit" value="Redisplay"
actionListener="#{helloBean.addControls}" />
<h:commandButton id="goodbyeCommand" type="submit" value="Goodbye"
actionListener="#{helloBean.goodbye}" immediate="true"/>
</h:form>
</body>
</html>
</f:view>
goodbye.jsp :
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<html>
<head>
<title>Jsf in Action - Hello World!</title>
</head>
<body>
<h:form id="goodbyeForm">
<p>
<h:outputText id="welcomeOutput" value="Good Bye"
style="font-family: Arial, sans-serif; font-size: 24; font-style: bold; color: green;" />
</p>
<p>
<h:outputText id="helloBeanOutputLabel"
value="Number of controls displayed: " />
<h:outputText id="helloBeanOutputLabel"
value="#{helloBean.numControls}" />
</p>
</h:form>
</body>
</html>
</f:view>
Bean class :
package com.achutha.bean;
import java.util.List;
import javax.faces.application.Application;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.component.html.HtmlPanelGrid;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
public class HelloBean {
private int numControls;
private HtmlPanelGrid controlPanel;
public int getNumControls() {
return numControls;
}
public void setNumControls(int numControls) {
this.numControls = numControls;
}
public HtmlPanelGrid getControlPanel() {
return controlPanel;
}
public void setControlPanel(HtmlPanelGrid controlPanel) {
this.controlPanel = controlPanel;
}
public void addControls(ActionEvent actionEvent) {
Application application = FacesContext.getCurrentInstance()
.getApplication();
List<UIComponent> children = controlPanel.getChildren();
children.clear();
for (int count = 0; count < numControls; count++) {
HtmlOutputText output = (HtmlOutputText) application
.createComponent(HtmlOutputText.COMPONENT_TYPE);
output.setValue(" " + count + " ");
output.setStyle("color: blue");
children.add(output);
}
}
public String goodbye() {
return "success";
}
}
Clean Deployment : The application is deploying itself fine on Tomcat 7. I checked the deployed package structure on &tomcat_home%/webapps and everything is in proper place as expected.
But when i run the application on a browser I get the following error :
HTTP Status 500 - /JSP/hello.jsp (line: 37, column: 2) A literal value was specified for attribute actionListener that is defined as a deferred method with a return type of void. JSP.2.3.4 does not permit literal values in this case
type Exception report
message /JSP/hello.jsp (line: 37, column: 2) A literal value was specified for attribute actionListener that is defined as a deferred method with a return type of void. JSP.2.3.4 does not permit literal values in this case
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: /JSP/hello.jsp (line: 37, column: 2) A literal value was specified for attribute actionListener that is defined as a deferred method with a return type of void. JSP.2.3.4 does not permit literal values in this case
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42)
org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:408)
org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:149)
org.apache.jasper.compiler.Validator$ValidateVisitor.checkXmlAttributes(Validator.java:1151)
org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:875)
org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1539)
org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376)
org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2428)
org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:894)
org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1539)
org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376)
org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2428)
org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:894)
org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1539)
org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376)
org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2428)
org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2434)
org.apache.jasper.compiler.Node$Root.accept(Node.java:475)
org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376)
org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1795)
org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:217)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:373)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
I am not finding a suitable one stop solution for this issue.
It is the EL used on the line actionListener="#{helloBean.addControls} which is raising the complications.
Please let me know the solution.
Change inside your web.xml
<webapp>
into
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
in addition to the above try adding
to your web-app...
like this
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID">

Spring REST MultipartFile file is always null

I'm trying to set up a simple upload with html and Spring 3.0.6 using REST services. I've followed the tutorial online but the MultipartFile parameter is always null. Here's the config and code:
application-context.xml:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2000000"/>
</bean>
pom.xml:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
html:
<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="/site/restServices/artworkUpload/" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
REST Controller:
#POST
#Path("/artworkUpload")
public String uploadFile(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) {
try {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
} else {
return "redirect:uploadFailure";
}
}
catch (Exception ex)
{
}
return null;
}
I copied the example from Spring's tutorial but no matter what I change, the file parameter is always null. "name" will have the value in the text box but file will be null.
I have also tried using Jersey and I receive the InputStream for the file but the FormDataContentDisposition is null so I can't determine the file type.
This is running on Jetty as well.
What am I missing?
As I remember I solved same issue by putting additional libs to my build path:
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
I hope this will help you.
Edit.
Ok. At last I had time for this issue. First of all, why do you use standart java features for building rest service (annotations #POST, #Path)? Because with Spring it is better to use spring MVC futures for REST. There is a lot of information about this in internet. Here is special part in reference documentation. Also here is good article on IBM site. Also very good description on how to build REST controller with Spring MVC is in Spring in Action (last 3-d edition).
Here how I have implemented simple file uploading functionality:
Rest controller:
#Controller
#RequestMapping("/rest/files")
public class FilesController {
...
#RequestMapping(value="/rest/files", method=RequestMethod.POST)
public String uploadFile(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) {
try {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
} else {
return "redirect:uploadFailure";
}
}
catch (Exception ex)
{
}
return "/testFileDownload";
}
}
html:
<!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=UTF-8">
<title>Test file upload</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="rest/files" enctype="multipart/form-data">
<input type="text" name="name" /> <input type="file" name="file" /> <input
type="submit" />
</form>
</body>
</html>
View resolver configuration in dispatcher-servlet.xml:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="file" value="multipart/form-data"/>
<entry key="html" value="text/html"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
I hope I'm not wasted my time and this is still necessary for you. )
EDIT 2
Here is very good tutorial where described how to build RESTful web service with Spring 3.1.
It helped me to connect this library:
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
All libs:
<dependencies>
<!-- Spring 3 MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<!-- Apache Commons file upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- JSTL for c: tag -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
See http://viralpatel.net/blogs/spring-mvc-multiple-file-upload-example/

Categories

Resources