What's the best way to set HTTP headers (based on filename patterns) in Jetty 6.1? Is it possible via jetty.xml (or jetty-web.xml)? Or do I have to modify web.xml?
You can add headers by configuration. In jetty.xml, put the following example :
<New id="RewriteHandler" class="org.eclipse.jetty.rewrite.handler.RewriteHandler">
<Set name="rules">
<Array type="org.eclipse.jetty.rewrite.handler.Rule">
<Item>
<New id="header" class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
<Set name="pattern">*.jsp</Set>
<Set name="name">myheader</Set>
<Set name="value">the value of myheader</Set>
</New>
</Item>
</Array>
</Set>
</New>
<Set name="handler">
<New id="Handlers" class="org.eclipse.jetty.server.handler.HandlerCollection">
<Set name="handlers">
<Array type="org.eclipse.jetty.server.Handler">
<Item>
<Ref id="RewriteHandler"/>
</Item>
</Array>
</Set>
</New>
</Set>
See RewriteHandler api for more examples of what is possible (it was already available in Jetty 6 RewriteHandler)
For information, here is my maven configuration of jetty plugin :
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.5.v20120716</version>
<configuration>
<jettyXml>${basedir}/src/main/etc/jetty.xml</jettyXml>
</configuration>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-http</artifactId>
<version>8.1.5.v20120716</version>
<type>jar</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-rewrite</artifactId>
<version>8.1.5.v20120716</version>
<type>jar</type>
<scope>runtime</scope>
</dependency>
</dependencies>
</plugin>
The generic answer to my question is of course this:
<web-app>
<filter>
<filter-name>headersFilter</filter-name>
<filter-class>com.example.MyHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>headersFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
...
</web-app>
public class MyHeadersFilter implements Filter {
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException,
ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
final String requestUri = httpRequest.getRequestURI();
if (requestUri.matches(...)) {
httpResponse.addHeader(...);
}
chain.doFilter(request, response);
}
}
This should work in any JavaEE web container (and can be made more configurable with <init-param>s).
But isn't there a way to do this purely declaratively in Jetty?
There is a way to adding header in jetty.
using java.lang.instrument and javassist. refer following link for details:
http://hunmr.blogspot.com/2012/12/mock-jetty-behavior-adding-customized.html
Related
I have a weblogic server that I run into Inlellij Idea for audit work of an application.
I made web-app based on SpringBoot 2.x. I am using Intellij Idea 2019 and there I configure a deploy my webapplication on weblogic 12.x.
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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.weblogic</groupId>
<artifactId>weblogic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>weblogic</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<version.apache.maven.plugins>3.8.1</version.apache.maven.plugins>
<version.mapstruct>1.3.0.Final</version.mapstruct>
<version.apache.common.lang3>3.9</version.apache.common.lang3>
<version.apache.commons.text>1.8</version.apache.commons.text>
<version.apache.commons.beanutils>1.9.4</version.apache.commons.beanutils>
<version.datasource.proxy>1.6</version.datasource.proxy>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</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-data-rest</artifactId>
</dependency>
<!--исключаем из компиляции встроенный Tomcat-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>false</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
version="4.0">
</web-app>
src/main/webapp/WEB-INF/weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app
http://xmlns.oracle.com/weblogic/weblogic-web-app/1.9/weblogic-web-app.xsd">
<wls:weblogic-version>12.2.1.4.0</wls:weblogic-version>
<wls:context-root>/api</wls:context-root>
<wls:container-descriptor>
<wls:prefer-application-packages>
<wls:package-name>org.slf4j.*</wls:package-name>
<wls:package-name>org.springframework.*</wls:package-name>
<wls:package-name>javax.persistence.*</wls:package-name>
</wls:prefer-application-packages>
</wls:container-descriptor>
</wls:weblogic-web-app>
src/main/webapp/index.html
When I run weblogic by Intellij Idea I get index.html by url - http://localhost:7001/api
So, It works.
But I need more complex static content and I want to place it into an application classpath.
I made so…
src/main/resources/templates/pages/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello Weblogic!!!</title>
<link type="text/css" href="/static/css/style.css" rel="stylesheet"/>
</head>
<body>
<div class="st">
Hello Weblogic!!!
</div>
</body>
</html>
src/main/resources/static/css/style.css
.st{
color: red;
font-size: 35px;
}
And then…
src/main/java/com/weblogic/weblogic/mvc/config/MyMvcConfig.java
package com.weblogic.weblogic.mvc.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class MyMvcConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(
"/static/css/**",
"/templates/pages/**")
.addResourceLocations(
"classpath:/",
"classpath:/static/css/",
"classpath:/templates/pages/");
}
}
But I get … Error 500--Internal Server Error
java.lang.NullPointerException at
weblogic.servlet.internal.ServletResponseImpl.sendContentError(ServletResponseImpl.java:738)
at
weblogic.servlet.internal.ServletResponseImpl.sendError(ServletResponseImpl.java:796)
at
weblogic.servlet.internal.ServletResponseImpl.sendError(ServletResponseImpl.java:713)
at
org.springframework.boot.web.servlet.support.ErrorPageFilter$ErrorWrapperResponse.sendErrorIfNecessary(ErrorPageFilter.java:349)
at
org.springframework.boot.web.servlet.support.ErrorPageFilter$ErrorWrapperResponse.getWriter(ErrorPageFilter.java:363)
at
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$StaticView.render(ErrorMvcAutoConfiguration.java:227)
at
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373)
at
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
who has any ideas how to fix this ?
You must use "template engine" – Thymeleaf. It doesn't work any other way (I would like to use pure (html + bootstrap), but it's not clear how to configure it).
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>web.spring.boot.jar</groupId>
<artifactId>web-spring-boot-jar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>web-spring-boot-jar</name>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The structure of the static resources
src/main/resources/static/css/style.css
src/main/resources/templates/index.html
src/main/resources/templates/pages/login/login.html
*.properties
src/main/resources/application.properties
These settings don't work.
spring.mvc.servlet.path=/api
server.servlet.context-path=/api
server.servlet.contextPath=/api
These settings could not be applied.
Configuration files - *.xml
src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
version="4.0">
</web-app>
If this file is missing, then the deployment occurs with errors ( in the development environment, you can see this in the console).
src/main/webapp/WEB-INF/weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app
xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
https://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd
http://xmlns.oracle.com/weblogic/weblogic-web-app
https://xmlns.oracle.com/weblogic/weblogic-web-app/1.9/weblogic-web-app.xsd">
<wls:context-root>rst</wls:context-root>
<wls:container-descriptor>
<wls:prefer-application-packages>
<wls:package-name>org.slf4j</wls:package-name>
</wls:prefer-application-packages>
</wls:container-descriptor>
</wls:weblogic-web-app>
<wls:context-root>rst</wls:context-root>
Here you need to be careful with choosing a name for the root context of the application (for example, if you chose a name for the context - /web, - > there will be an error, since this name is reserved somewhere).
Entry point
#SpringBootConfiguration
#EnableAutoConfiguration
#ComponentScan
public class WebSpringBootJarApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
public static void main(String[] args) {
SpringApplication.run(WebSpringBootJarApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(WebSpringBootJarApplication.class);
}
}
#SpringBootConfiguration
#EnableAutoConfiguration
#ComponentScan
You must have these 3 annotations, otherwise nothing will work.
The documentation says that #SpringBootConfiguration, replaces annotations:
#Configuration,
#EnableAutoConfiguration
#ComponentScan
#SpringBootConfiguration - indicates that this class provides an application
SpringBoot
It can also be used as an alternative to the #Configuration annotation, because the configuration can be found automatically.
#EnableAutoConfiguration - enables automatic configuration of Spring ApplicationContext by scanning class path components and registering beans that match different conditions.
That is, this annotation tries to guess and configure the beans that you may need.
Auto-configuration of classes, usually applied based on classpath
your application and on those beans that you have defined.
When using the #SpringBootConfiguration annotation, the context configuration is enabled automatically and the annotation is added, which will not have any additional effect…
But what I see here is quite different…
Without this annotation, nothing works... That is, we don't get the requested resources.
#ComponentScan - Directive configures component scanning for the classes marked with #Configuration.
Provides support in parallel using the configuration described in XML format in the element:
... But I didn't even specify the packages to scan....
And without specifying this annotation, I also can't access resources... ???
Why is that? I don't know…
What do I need to implement WebApplicationInitializer , - I don't know…
https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-weblogic
Contollers
src/main/java/web/spring/boot/jar/webspringbootjar/controller/index/IndexController.java
IndexController
#Controller
public class IndexController {
#RequestMapping(value="/", method= RequestMethod.GET)
public String index() {
return "index";
}
}
src/main/java/web/spring/boot/jar/webspringbootjar/controller/login/LoginController.java
LoginController
#Controller
public class LoginController {
#GetMapping(value = {"/log"})
public ModelAndView showUsersPage() {
return new ModelAndView("pages/login/login.html");
}
}
The creation of an artifact (Intellij Idea)
- Project Structure/Artifacts
- Alt + Insert
- Web Application: Exploded -> From module
There is the path to the directory with your project will be specified.
You can also configure
- Project Structure/Facets
And then…
Run\Edit Configuration
Here you configure - weblogic…
URL to the app(in my case)
http://localhost:7001/rst/
The same access will be available when you migrate .*war from the development environment and deploy it to an external weblogic server.
If you start an external server, you get an error
This means that you need to run maven and it must will make a *.war-file…
Also It doesn't work...
#Configuration
#EnableWebMvc
#ComponentScan(basePackageClasses = { ServletContextConfig.class })
public class ServletContextConfig implements WebMvcConfigurer {
#Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
webServerFactoryCustomizer() {
return factory -> factory.setContextPath("/rootweb");
}
}
I suppose we only can use xml-configuration for servlet-context here.
If someone can add something, please specify what is wrong....
Can who has what ideas, about my issues which arose during this messages ....
I am trying to create my own eshop. I have problem on the creation of beans.
My packages are the following:
Controller
package com.emusicstore.controller;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.emusicstore.dao.ProductDao;
import com.emusicstore.model.Product;
#Controller
public class HomeController {
#Autowired
private ProductDao productDao;
#RequestMapping("/")
public String home(){
return "home";
}
#RequestMapping("/productList")
public String getProducts(Model model) {
List<Product> products = productDao.getAllProducts();
model.addAttribute("products", products);
return "productList";
}
ProductDao
package com.emusicstore.dao;
import java.util.List;
import com.emusicstore.model.Product;
public interface ProductDao
{
void addProduct(Product product);
Product getProductById (String id);
List<Product> getAllProducts();
void deleteProduct (String id);
}
ProductDaoImpl
package com.emusicstore.impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.emusicstore.dao.ProductDao;
import com.emusicstore.model.Product;
#Component
#Transactional
public class ProductDaoImpl implements ProductDao {
#Autowired
private SessionFactory sessionFactory;
public void addProduct(Product product) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(product);
session.flush();
}
public Product getProductById(String id) {
Session session = sessionFactory.getCurrentSession();
Product product = (Product) session.get(Product.class, id);
session.flush();
return product;
}
public List<Product> getAllProducts() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Product");
List<Product> products = query.list();
session.flush();
return products;
}
public void deleteProduct(String id) {
Session session = sessionFactory.getCurrentSession();
session.delete(getProductById(id));
session.flush();
}
}
Product
package com.emusicstore.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String productId;
private String productName;
private String productCategory;
private String productDescription;
private double productPrice;
private String productCondition;
private String productStatus;
private int unitInStock;
private String productManufacture;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCategory() {
return productCategory;
}
public void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public double getProductPrice() {
return productPrice;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public String getProductCondition() {
return productCondition;
}
public void setProductCondition(String productCondition) {
this.productCondition = productCondition;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
public int getUnitInStock() {
return unitInStock;
}
public void setUnitInStock(int unitInStock) {
this.unitInStock = unitInStock;
}
public String getProductManufacture() {
return productManufacture;
}
public void setProductManufacture(String productManufacture) {
this.productManufacture = productManufacture;
}
}
Also I have a jdbc.properties file with info about username, password etc to connect wit MySQL.
I think that the above files are correct.
applicationContext.xml (part of my code)
<beans profile="dev">
<context:property-placeholder location="jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.emusicstore.*</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- Is <tx:annotation-driven /> is necessary in this file?? -->
</beans>
dispatcher-servlet.xml (part of my code)
<context:annotation-config></context:annotation-config>
<context:annotation-config />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<tx:annotation-driven />
web.xml (part of my code)
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcher-servlet.xml
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
When I try to run my project all the errors associated with:
org.springframework.beans.factory.BeanCreationException
org.springframework.beans.factory.NoSuchBeanCreationDefinitionException
The first error is on the creation of bean 'homeController'.
Could not autowire field: private com.emusicstore.dao.ProductDao com.emusicstore.controller.HomeController.productDao;
My questions.
1) applicationContext.xml
On the which file (or files) I have to put? Is the existing path right or I have to modify it specifically (e.g com.emusicstore.dao)? At this list, I have to put the whole path for my dao, model ?
2) dispatcher-servlet.xml
Same question for the right path of context:component-scan. On the base-package may I specify the package only to my controller (com.emusicstore.controller)?
I searched to older posts but I do not solve my problem.
Thank you in advance, Mike
EDIT
Summary of (our) changes
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<beans profile="dev">
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.emusicstore.dao, com.emusicstore.impl"></context:component-scan>
<context:property-placeholder location="jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
<!-- MY CHANGES -->
<!-- LocalSessionFactoryBean for hibernate4 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<!-- CHANGE HERE FOR MySQL -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<!-- To know where is ProductDao -->
<property name="packagesToScan">
<list>
<value>com.emusicstore.dao</value>
<value>com.emusicstore.impl</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
</beans>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<context:component-scan base-package="com.emusicstore." />
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<tx:annotation-driven />
</beans>
Web.xml Exactly the same code as you wrote
The same errors continues to exist but the "homepage" on Eclipse has changed to this
HTTP Status 500 - Servlet.init() for servlet dispatcher threw exception
type Exception report
message Servlet.init() for servlet dispatcher threw exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet dispatcher threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
And then the previous errors again...
EDIT
web.xml (first lines)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
pom.xml (all my file)
<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.mywebsite</groupId>
<artifactId>eMusicStore</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- To work with Hibernate -->
<!-- All Hibernate in single dependency -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.2.Final</version>
</dependency>
<!-- MySql -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- To connect with the jdbc.properties file -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Traditionnaly we have 2 contexts in a Spring MVC application. The root context (here your applicationContext.xml) where we define all beans not dedicated to web stuff like DAO, Securtity, etc... And the DispatcherServlet context (dispatcher-servlet.xml) where we define all beans related to web operations like controllers.
So, put your DAO bean in applicationContext.xml like this : <context:component-scan base-package="com.emusicstore.dao"/> and your transaction manager <tx:annotation-driven transaction-manager="transactionManager"/>
For your 2nd question, you can just put the super package like this : <context:component-scan base-package="com.emusicstore."/>
EDIT
Here how your web.xml should look like :
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcher-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I your configuration you mixed the 2 contexts.
I am using log4j2 with this 2 dependencies:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-1.2-api</artifactId>
<version>2.6.2</version>
</dependency>
When I try to log for example an error with a throwable like:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.annotations.Test;
public class Test {
private static final Logger logger = LogManager.getLogger(Test.class);
#Test
public void testSendMessage() throws Exception {
Exception exception = new Exception("some exception");
logger.error("error with exception", exception);
}
}
using patternlayout:
<Configuration>
<properties>
<property name="filters">org.testng,org.apache.maven,sun.reflect,java.lang.reflect</property>
</properties>
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT" direct="true">
<PatternLayout pattern="%maxLen{%d{DEFAULT} [%p] %c{-3}:%L - %enc{%m} %xEx{filters(${filters})}%n}{200}"/>
</Console>
</Appenders>
<Loggers>
<logger name="my.test.class.path" level="trace" additivity="false">
<AppenderRef ref="ConsoleAppender" />
</logger>
</Loggers>
</Configuration>
Then the filtered packages won't disappear from the stacktrace, I can't even manipulate the stacktrace in any way like maximizing the lines:
%xEx{5}
Highlightning also don't work in eclipse nor in Kibana(ELK environment).
Can anybody help?
Could it be that the %xEx PatternLayout converter doesn't support property substitution in its options?
What if you put the packages you want to filter directly in the filters list?
It may be worth raising a Jira ticket on the Log4j 2 issue tracker for this.
try to remove the ending{200}. i think there is an issue using more sub parameters.
here is a snippet which works. please note if you add additional things like separator(|) it will stop working [tested in version 2.8.1 and 2.9.1]
<Properties>
<Property name="exfilters">org.jboss,java.lang.reflect,sun.reflect</Property>
<Property name="log-pattern">%d %-5p %m%n%xEx{filters(${exfilters})}/Property>
</Properties>
...
<PatternLayout pattern="${sys:log-pattern}"/>
Works for me on Log4j2 v 2.17 (and also for rThrowable):
<Properties>
<Property name="PACKAGE_FILTER">org.jboss,java.lang.reflect,sun.reflect</Property>
<Property name="LOG_PATTERN">%xThrowable{filters(${PACKAGE_FILTER})}</Property>
</Properties>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
</Appenders>
I'm working on a Swing application with JPA and Hibernate. But every time I try to call following code to get EntityManager
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
EntityManagerFactory emf = Persistence.createEntityManagerFactory("abcd");
EntityManager em = emf.createEntityManager();
I get following exceptions:
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named abcd: Provider named org.hibernate.jpa.HibernatePersistenceProvider threw unexpected exception at create EntityManagerFactory:
javax.persistence.PersistenceException
javax.persistence.PersistenceException: Unable to build entity manager factory
and
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Path to persistence.xml is my.jar/meta-inf/persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="abcd" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.url" value="xxx"/>
<property name="hibernate.connection.password" value="xxx"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.user" value="xxx"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
</properties>
</persistence-unit>
</persistence>
Dependencies:
All dependencies except junit are in a classpath
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
<scope>compile</scope>
</dependency>
It seems, it cannot find your persistence.xml file. The correct folder for the persistence.xml file is META-INF and not meta-inf.
I want to generate a JSON response of my object I write code for that but not getting success it is giving error 406 I am not using maven I am using ant
This is my controller
#Controller
public class LoginRestCtrl {
#RequestMapping(value = "/test", method=RequestMethod.GET)
#ResponseBody
public Employee checklogin(){
Employee e=new Employee();
e.setEmailId("sdosi#cur.com");
e.setId(1);
e.setPassword("a");
return e;
}
}
This is my configuration file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="viewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
<bean
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>
I am calling as http://localhost:8080/SpringMVC/test but getting error 406
You can try following to produce JSON Rsponse. You would require Gson library, and the controller would look as follows:
#Controller
public class LoginRestCtrl {
#RequestMapping(value = "/test", method=RequestMethod.GET)
#ResponseBody
public String checklogin(){
Employee e=new Employee();
e.setEmailId("sdosi#cur.com");
e.setId(1);
e.setPassword("a");
Gson gson=new Gson();
String jsonResponse=gson.toJson(e);
return jsonResponse;
}
}
Json response looks as following:
{"emailId":"sdosi#cur.com","id":1,"password":"a"}
I suggest to put jackson dependencies in your pom.xml if they are not already there.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.3</version>
</dependency>
If they are already there can you update your RequestMapping with
#RequestMapping(value = "/test", method=RequestMethod.GET, produces = "application/json;charset=utf-8")
This will ensure that we return a response with a json header.
add the following dependencies in your pom.xml file
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
with in your spring configuration xml files add the following beans
<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter" />
</list>
</property>
</bean>
now you can use your controller as it is
#Controller
public class LoginRestCtrl {
#RequestMapping(value = "/test", method=RequestMethod.GET)
#ResponseBody
public Employee checklogin() {
Employee e=new Employee();
e.setEmailId("sdosi#cur.com");
e.setId(1);
e.setPassword("a");
return e;
}
}