POST Operation is failing with an error 405 Method not allowed - s4sdk

I developed a Java application using the S4SDK as described in the link below and deployed it to the SAP Cloud platform cloud foundry environment.
https://blogs.sap.com/2017/12/07/step-20-with-s4hana-cloud-sdk-create-and-deep-insert-with-the-virtual-data-model-for-odata/
Then I accessed the application using POSTMAN tool. First, I made a GET request for application URL/businesspartners and fetched x-csrf-token. I used this x-csrf-token for POST operation for application URL/businesspartners with body as explained in the blog( above link).
So, when I make a post request, it gave an error: 405 METHOD NOT ALLOWED
Below is the servlet:
#WebServlet("/businesspartners")
public class BusinessPartnerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger logger = CloudLoggerFactory.getLogger(BusinessPartnerServlet.class);
private static final String CATEGORY_PERSON = "1";
#Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
try {
final List<BusinessPartner> businessPartners =
new DefaultBusinessPartnerService()
.getAllBusinessPartner()
.select(BusinessPartner.BUSINESS_PARTNER,
BusinessPartner.LAST_NAME,
BusinessPartner.FIRST_NAME,
BusinessPartner.IS_MALE,
BusinessPartner.IS_FEMALE,
BusinessPartner.CREATION_DATE)
.filter(BusinessPartner.BUSINESS_PARTNER_CATEGORY.eq(CATEGORY_PERSON))
.orderBy(BusinessPartner.LAST_NAME, Order.ASC)
.execute();
response.setContentType("application/json");
response.getWriter().write(new Gson().toJson(businessPartners));
} catch (final ODataException e) {
logger.error(e.getMessage(), e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String firstname = request.getParameter("firstname");
final String lastname = request.getParameter("lastname");
final String country = request.getParameter("country");
final String city = request.getParameter("city");
final String email = request.getParameter("email");
//do consistency checks here...
final AddressEmailAddress emailAddress = AddressEmailAddress.builder()
.emailAddress(email)
.build();
final BusinessPartnerAddress businessPartnerAddress = BusinessPartnerAddress.builder()
.country(country)
.cityName(city)
.toEmailAddress(Lists.newArrayList(emailAddress))
.build();
final BusinessPartnerRole businessPartnerRole = BusinessPartnerRole.builder()
.businessPartnerRole("FLCU01")
.build();
final BusinessPartner businessPartner = BusinessPartner.builder()
.firstName(firstname)
.lastName(lastname)
.businessPartnerCategory("1")
.correspondenceLanguage("EN")
.toBusinessPartnerAddress(Lists.newArrayList(businessPartnerAddress))
.toBusinessPartnerRole(Lists.newArrayList(businessPartnerRole))
.build();
String responseBody;
try {
final BusinessPartner storedBusinessPartner = new StoreBusinessPartnerCommand(new ErpConfigContext(), new DefaultBusinessPartnerService(), businessPartner).execute();
responseBody = new Gson().toJson(storedBusinessPartner);
response.setStatus(HttpServletResponse.SC_CREATED);
} catch(final HystrixBadRequestException e) {
responseBody = e.getMessage();
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
logger.error(e.getMessage(), e);
}
response.setContentType("application/json");
response.getOutputStream().print(responseBody);
}
}
And here my web.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<session-config>
<session-timeout>20</session-timeout>
</session-config>
<!--
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-security.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
-->
<filter>
<filter-name>RestCsrfPreventionFilter</filter-name>
<filter-class>org.apache.catalina.filters.RestCsrfPreventionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RestCsrfPreventionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>HttpSecurityHeadersFilter</filter-name>
<filter-class>com.sap.cloud.sdk.cloudplatform.security.servlet.HttpSecurityHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpSecurityHeadersFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>HttpCachingHeaderFilter</filter-name>
<filter-class>com.sap.cloud.sdk.cloudplatform.security.servlet.HttpCachingHeaderFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpCachingHeaderFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Could someone please help me?

Have you checked that your servlet implements the doPost method correctly? The following question on SO seems quite good on this: Java Servlet return error 405 (Method Not Allowed) for POST request.

Have you tried to add the #Override annotation to the doPost method?

Related

How to have jersey inject a param based on the http header?

I have an interface and would like to open it as a REST API.
Interface:
string createToken(String username, String scopes);
REST web API:
#GET
#Path("/createToken")
#Override
public string createToken(#InjectParam String username, String scopes) {
...
}
As a simple Java API,, the interface itself makes sense - creating an access token by a specific (unique) user.
But, as an REST web API, I need a previous step to retrieve the username, based on some user data that is passed in the http header, like an SSO key.
How do I inject a value into the username - extracted from the HTTP header? Thanks.
Created a Provider to inject the value into a custom annotation. See small working example here. See source inline below as well.
The example extracts the username from an sso token. It's a dummy extraction.
* I didn't use #InjectParam.
Invocation example:
curl -X POST -H "ssoToken: 1234" http://localhost:8080/JerseyCustomParamInjection-1.0-SNAPSHOT/oauth2/createAccessToken
Custom annotation:
#Target({ElementType.PARAMETER})
#Retention(RetentionPolicy.RUNTIME)
public #interface LoggedUser {
}
Provider to do the injection:
#Provider
public class LoggedUserProvider implements
Injectable<String>,
InjectableProvider<LoggedUser, Parameter> {
#Context
private HttpServletRequest request;
public LoggedUserProvider() {
}
#Override
public Injectable<String> getInjectable(ComponentContext cc, LoggedUser a, com.sun.jersey.api.model.Parameter c) {
return this;
}
#Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}
#Override
public String getValue() {
String sso = request.getHeader("ssoToken");
if (sso == null) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
// Retreive username from soo
String username = " <extracted username from sso="+sso+">";
return username;
}
}
Resource that defines the wants to inject the value:
#Path("/oauth2")
public class Resource {
#POST
#Path("/createAccessToken")
public String createAccessToken(
#LoggedUser String username
) {
return username + " <created access token using the logged in injected username>";
}
}
Servlet configuration (web.xml):
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>info.fastpace.jerseycustomparaminjection</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
You should use HeaderParam. See this
#GET
#Path("/createToken")
#Override
public string createToken(#HeaderParam("username") String username, String scopes) {
...
}
If you have to extract username and have to inject it, you will have to implement a provider:
#Provider
public class UsernameProvider
extends AbstractHttpContextInjectable<Locale>
implements InjectableProvider<Context, Type> {
#Override
public Injectable<E> getInjectable(ComponentContext compCntxt, Context cntxt, Type typ) {
if (typ.equals(String.class)) {
return this;
}
return null;
}
#Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}
#Override
public String getValue(HttpContext httpCntxt) {
final Request rqst = httpCntxt.getRequest();
String username = null;
//Extract 'username' from Headers
return username;
}
}
Detailed explanation here

How to redirect any url that do not match any #RequestMapping parameter in the application

I use Spring MVC in my web application. I am trying to redirect any url that match the pattern http://localhost:8080/my-app/* to a specific controller. But if the url is something like the following, http://localhost:8080/my-app/test and if there is a controller as follows:
#Controller
#RequestMapping("test")
public class TestClass
{
#RequestMapping(value = "/landing", method = RequestMethod.GET)
public String selectHomePage(ModelMap model)
{
//do something
}
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String listFaqCollections(#ModelAttribute("ownedby") String ownedBy, ModelMap model)
{
//do something
}
}
And I have another class as follows:
#Controller
public class InvalidUrslRedirect
{
#RequestMapping(method = RequestMethod.GET)
public String redirectInvalidUrls(Model model)
{
//do something
}
All the urls that are invalid will be redirected to the above controller class.
The valid urls would be as follows:
http://localhost:8080/my-app/test/landing
http://localhost:8080/my-app/test/list?ownedby=me
But if the url is something like:
http://localhost:8080/my-app/test/list?ownedbys=me
the normal tomcat 404 error page is displayed and the it is not getting redirected to the InvalidUrslRedirect class
In my web.xml file, I have the following:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/core/root-context.xml, classpath:spring/core/spring-security.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
In the spring-security.xml, I have:
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/**" access="isFullyAuthenticated()"/>
I have been searching the net for some time now, but could not find much help. is there any way i can achieve such a functionality. Thanks in advance
If i understood you correctly, you want to redirect every request other than e.g. "/test". In this case you'll need two methods:
#RequestMapping(method = RequestMethod.GET)
public String redirectEverythingOtherThanTest(){
return "redirect:/pageToRedirectTo.html"
}
#RequestMapping(value="/test", method = RequestMethod.GET)
public String testRequest(){
//some stuff
return "somepage.html";
}
Also remember about #Controller annotation on your class.
How is your web application setup? Which URLs is Spring looking for? Do you have an AbstractAnnotationConfigDispatcherServletInitializer?
public class WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
/**
* Configure Spring MVC to handle ALL requests
*/
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Class<?>[] getRootConfigClasses() {
....
}
#Override
protected Class<?>[] getServletConfigClasses() {
....
}
#Override
public void onStartup(ServletContext container) throws ServletException {
...
}
}

Spring + Hibernate DAO injection fails in Netbeans

I have controller class LoginData.java
#Controller
#ManagedBean(name = "login")
#SessionScoped
public class LoginData implements Serializable{
#Autowired
private LoginDAO loginDao;
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void validateUser(){
try{
loginDao.login(username, password);
}catch(BusinessException e){
}
}
}
I am trying to autowire this Dao and its implementation:
LoginDAO
public interface LoginDAO {
public boolean login(String username, String password)throws BusinessException;
public boolean register(String username, String password, UserType type)throws BusinessException;
}
LoginDAOImpl
public class LoginDAOImpl implements LoginDAO{
private String username;
private String password;
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public boolean login(String username, String password) throws BusinessException{
Query query = sessionFactory.getCurrentSession().createQuery(
"SELECT u FROM User u WHERE u.username=:un");
query.setParameter("un", username);
if(query.list().size()==0)throw new BusinessException("No user in database!");
User user = (User)(query.list().get(0));
return getHashMD5(password).equals(user.getPassword());
}
#Override
public boolean register(String username, String password, UserType type) throws BusinessException{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public static String getHashMD5(String string) throws BusinessException{
try {
MessageDigest md = MessageDigest.getInstance("MD5");
BigInteger bi = new BigInteger(1, md.digest(string.getBytes()));
return bi.toString(16);
} catch (Exception ex) {
throw new BusinessException(ex.getMessage());
}
}
}
I am also trying to inject sessionFactory in DAO implementation, I don't know if this code will work. My xml for configuration:
dispatcher-servlet.xml
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<bean id="loginDAO" class="rs.ac.bg.etf.services.LoginDAOImpl"/>
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</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>
<load-on-startup>2</load-on-startup>
</servlet>
<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>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
I get null pointer exception when dao method is called in controller from JSF form. Anyone knows what could be the problem?
PS: xml files are mostly generated by Netbeans IDE.
You're missing the #Repository annotation for the autowiring to work.
Try this:
#Repository("LoginDAO")
public class LoginDAOImpl implements LoginDAO

getting empty form session bean in jsf

I have set session bean after login, and print the value from session bean it prints in xhtml file but while i go to the next page or bean session bean return empty it automatically reset the value.
I am using the primeface 4.0, jsf 2.0 and ejb 3.0 for web application.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<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>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value> </context-param> -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>ui-lightness</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.CHECK_ID_PRODUCTION_MODE</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.VIEW_UNIQUE_IDS_CACHE_ENABLED</param-name>
<param-value>true</param-value>
</context-param>
<mime-mapping>
<extension>xlsx</extension>
<mime-type>text/xlsx</mime-type>
</mime-mapping>
</web-app>
//Setting user from loginMB having viewscope bean.
UserMB
#SessionScoped
#ManagedBean(name = "userMB")
public class UserMB extends AbstractMB implements Serializable {
public static final String INJECTION_NAME = "#{userMB}";
private static final long serialVersionUID = 1L;
private User user;
#EJB
private UserEJB userEJB;
public String logOut() {
getRequest().getSession().invalidate();
return "/index.xhtml?faces-redirect=true";
}
private HttpServletRequest getRequest() {
return (HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
}
public User getUser() {
if (user == null) {
user = new User();
}
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getUserList() {
if (userList == null) {
userList = userEJB.findAll();
}
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}
CampMB
#ManagedBean
#ViewScoped
public class CampMB extends AbstractMB implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty("#{userMB}")
private UserMB userMB;
public UserMB getUserMB() {
return userMB;
}
public void setUserMB(UserMB userMB) {
this.userMB = userMB;
}
private User user;
private Camp camp;
private List<CampDTO> listCamp;
#EJB
private CampEJB campEJB;
#EJB
private MemberEJB memberEJB;
#EJB
private CodeValueEJB codeEJB;
TimeZone timeZone = TimeZone.getDefault();
public TimeZone getTimeZone() {
return timeZone;
}
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
public List<CampDTO> getListCamp() {
Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
UserMB managedBean = (UserMB) sessionMap.get("userMB");
System.out.println("test use==" + managedBean.getUser().getId());
System.err.println("Session"+getUserMB().getUser().getId());
if (listCamp == null) {
listCamp = new ArrayList<CampDTO>();
}
listCamp = ConvertUtils.convertCampToDTO(campEJB.findAll());
return listCamp;
}
public void setListCamp(List<CampDTO> listCamp) {
this.listCamp = listCamp;
}
public User getUser() {
if (user == null) {
user = new User();
}
return user;
}
public void setUser(User user) {
this.user = user;
}
}
I am trying different techniques getting from search but no one works for me?
Is there any configuration for it or how to set/get session bean properly.

how to use org.springframework.web.filter.CharacterEncodingFilter to correct character encoding?

I need some help.
I placed the code snippet below in my web.xml.
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
and in my server.xml:
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
My jsp pages are encoded as UTF-8 and my mysql table is encoded as utf8_general_ci.
My problem is that whenever I save a ñ it becomes ?.
When I tried to manually save ñ in the mysql terminal its saving properly. I suspect the problem lies within my server or my program. Please help.
I tried successfully with this in web.xml !
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
To work in spring boot you can use
#Bean
public FilterRegistrationBean filterRegistrationBean() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(filter);
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
another response
Make sure you have the following snippet in your jsp
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" language="java" %>
and also make sure that the encodingFilter is the first filter in web.xml file
My solution, using Spring (3.2.x) AnnotationConfigWebApplicationContext, based on Spring Framework Reference:
public class StudentApplicationConfig extends AbstractDispatcherServletInitializer {
#Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext dispatcherContext
= new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
return dispatcherContext;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext appContext
= new AnnotationConfigWebApplicationContext();
return appContext;
}
#Override
protected Filter[] getServletFilters() {
Filter[] filters;
CharacterEncodingFilter encFilter;
HiddenHttpMethodFilter httpMethodFilter = new HiddenHttpMethodFilter();
encFilter = new CharacterEncodingFilter();
encFilter.setEncoding("UTF-8");
encFilter.setForceEncoding(true);
filters = new Filter[] {httpMethodFilter, encFilter};
return filters;
}
it might be little be late, but it´s better to configure it in tomcat conf/web.xml (or for project in web.xml)
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
See http://wiki.apache.org/tomcat/FAQ/CharacterEncoding or tomcat´s web.xml
Or for jetty like this:
public class StartEmbeddedJetty{
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletContextHandler sch = new ServletContextHandler();
sch.addFilter(CharacterEncodingFilter .class, "/*", EnumSet.of(DispatcherType.REQUEST));
...
server.start();
server.join();
}
public static class CharacterEncodingFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
// set encoding to utf-8
req.setCharacterEncoding("UTF-8");
res.setCharacterEncoding("UTF-8");
}
#Override
public void init(FilterConfig arg0) throws ServletException {
/* empty */
}
#Override
public void destroy() {
/* empty */
}
}
}

Resources