Multiple DWR classes in web.xml (using annotations) - ajax

i want to use annotated DWR classes in my project. So i created 2 classes.
Assume Dwr1.java & Dwr2.java
in my web.xml i have the following entry to load the classes:
<servlet>
<display-name>DWR Servlet</display-name>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>activeReverseAjaxEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>classes</param-name>
<param-value>
de.package.Dwr1,
de.another.package.Dwr2
</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
The Proplem is that the Dwr2 Class does not get instantiated. If i remove Dwr1 from my web.xml, Dwr2 gets instantiated. But if i have both entries in my web.xml only Dwr1 gets instantiated.
Dwr1 is a very simple class:
#RemoteProxy
public class Dwr1 {
#RemoteMethod
public String getString(String key) {
return Util.GetString(key);
}
}
Dwr2 is a little bit more complex like:
#RemoteProxy
public class Dwr2 {
#RemoteMethod
public Dwr2() {
ServerUtil.registerOnFE(new UpdateClient());
}
private void updateBrowser(final String arg) {
Browser.withPage("/page.do", new Runnable() {
#Override
public void run() {
ScriptSessions.addFunctionCall("update", arg);
}
});
}
private class UpdateClient {
#Override
onRecieveUpdate(String arg) {
updateBrowser(arg);
}
}
}
Are there any Mistakes in my classes or in my web.xml? Or how can i instantiate multiple DWR Classes with Annotations?

I found a solution to fix this issue. It seems like DWR doesn´t instantiate every class on the server-startup. (But it apparently does if there is only one class defined in the config file). However, I just implemented a "dummy-method" in dwr-classes, called "start()". The Method does nothing, but when it get's called from javascript, the class gets instantiated. My solution looks like this:
<servlet>
<display-name>DWR Servlet</display-name>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>activeReverseAjaxEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>classes</param-name>
<param-value>
de.package.Dwr1,
de.another.package.Dwr2
</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
Dwr1
#RemoteProxy
public class Dwr1 {
#RemoteMethod
public String getString(String key) {
return Util.GetString(key);
}
}
Dwr2
#RemoteProxy
public class Dwr2 {
public Dwr2() {
ServerUtil.registerOnFE(new UpdateClient());
}
#RemoteMethod
public void start() {
//Do nothing
}
private void updateBrowser(final String arg) {
Browser.withPage("/page.do", new Runnable() {
#Override
public void run() {
ScriptSessions.addFunctionCall("update", arg);
}
});
}
private class UpdateClient {
#Override
onRecieveUpdate(String arg) {
updateBrowser(arg);
}
}
}
A call of the start()-method of Dwr2 class triggers the insantiation of it.

Related

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

Failed startup of context com.google.appengine.tools.development.DevAppEngineWebAppContext

I am using Spring MVC,google app engine, admin sdk, cloud sql.
I want to access (preferncesDao) dao class into Filter.
Below is my filter
public class NameSpaceGoogleSecurityFilter implements Filter
{
#Autowired
IPreferencesDao preferncesDao;
public void init( FilterConfig filterConfig ) throws ServletException{
SpringUtils.init(filterConfig.getServletContext());
preferncesDao = SpringUtils.getPreferncesDao();
}
}
Below is my SpringUtils class.
public class SpringUtils {
private static ApplicationContext appContext;
private static IPreferencesDao preferncesDao = null;
public static void init(final ServletConfig config) {
init(config.getServletContext());
}
public static void init(final ServletContext context) {
if(appContext==null){
appContext =
(ApplicationContext) context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
}
}
public static IPreferencesDao getPreferncesDao() {
if(preferncesDao==null){
preferncesDao=(IPreferencesDao) appContext.getBean("preferncesDao");
}
return preferncesDao;
}
protected SpringUtils() {
throw new UnsupportedOperationException();
}
}
When I start build process, It is throwing below exception
Failed startup of context com.google.appengine.tools.development.DevAppEngineWebAppContext
java.lang.NullPointerException.
Nullpointer at line preferncesDao=(IPreferencesDao) appContext.getBean("preferncesDao");
How can i resolve above error ? is it right way to get dao object into filter ? if not what is correct way.?
It is required to add below tag in web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
That purely indicate that ContextLoaderListener missing.
so add below code in web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
For more details refer this link

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