Beans not 'managed' using SpringBoot - spring

I use JSF with Spring Boot.
My problem is, that if I use the #javax.faces.bean.ManagedBean annotation I receive
javax.el.PropertyNotFoundException: Target Unreachable, identifier
[numberTest] resolved to null
I resolved the issue with put also the #Component annotation on the managed bean.
The other way was to put the Java classes in the WEB-INF.
My question is: both above-mentioned way seems to be bad and I think that they will cause trouble. What would be the solution to this problem?
I Googled a lot and tried every solution found.
(An additional fact, is that with #javax.annotation.ManagedBean the core JSP functions work (I didn't receive the error) but for example EL doesn't.)
Here is the code, in which with I receive the PropertyNotFoundException:
Configuration.java
import javax.faces.webapp.FacesServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#SpringBootApplication
#EnableAutoConfiguration
#EnableTransactionManagement
#EnableWebMvc
#Configuration
#EnableJpaRepositories(basePackageClasses = {})
#ComponentScan(basePackageClasses = { CLASSES_ARE_HERE })
public class Configuration {
public static void main(String[] args) {
SpringApplication.run(Configuration.class, args);
}
#Bean
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.xhtml");
return servletRegistrationBean;
}
}
The managed bean:
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
#ManagedBean
#ApplicationScoped
public class NumberTest {
private int theNumber=0;
public NumberTest() {
}
public void addOne() {
theNumber++;
}
public void addN(int n) {
theNumber+=n;
}
public int getTheNumber() {
return theNumber;
}
public void setTheNumber(int theNumber) {
this.theNumber = theNumber;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<!-- Time in seconds that facelets should be checked for changes since last
request. A value of -1 disables refresh checking. -->
<context-param>
<param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
<param-value>1</param-value>
</context-param>
<!-- Set the project stage to "Development", "UnitTest", "SystemTest", or
"Production". -->
<!-- An optional parameter that makes troubleshooting errors much easier. -->
<!-- You should remove this context parameter before deploying to production! -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
</web-app>
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
The .xhtml
<!DOCTYPE html>
<f:view xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui" encoding="UTF-8">
<html>
<h:head>
</h:head>
<h:body>
<h1>Szám</h1>
<h3>#{numberTest.theNumber}</h3>
<h:form>
<br></br>
<h:commandButton action="#{numberTest.addOne()}" value="Add one"></h:commandButton>
</h:form>
<h:form>
<br></br>
<h:inputText binding="#{input1}" />
<h:commandButton value="Add N" action="#{numberTest.addN(input1.value)}" />
</h:form>
</h:body>
</html>
</f:view>

Related

in xhtml page jsf attribute are not rendering

how to render xhtml page , in springboot...,where should i put xhtml file
this is my project structure..what url should i hit for getting xhtml file.
how to call xhtml page
this is my xhtml page
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<body>
<form>
<p:panel header="Login Page">
<h:outputText value="id" />
<h:inputText id="id" value="#{a.id}" required="true"></h:inputText>
<h:message for="id" style="color:blue"></h:message>
<br></br>
<br></br>
<h:outputText value="name" />
<h:inputText id="name" value="#{a.name}" required="true"></h:inputText>
<h:message for="name" style="color:blue"></h:message>
<p:commandButton
action="#{a.validate()}"
value="login"></p:commandButton>
</p:panel>
<br></br>
<br></br>
</form>
</body>
</html>
even http:localhost:8080/hello url does not render and give index page
package login.example;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#Controller
#ComponentScan
public class UserController {
#RequestMapping("/hello")
#ResponseBody
public String sayhii() {
return "index";
}
#Autowired
UserService userService;
#GetMapping("login-register/index")
public String index() {
return "index";
}
#GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
#GetMapping("/user/{id}")
private User getUser(#PathVariable("id") long id) {
return userService.getUserById(id);
}
#DeleteMapping("/user/{id}")
public void deleteUser(#PathVariable("id") long id) {
userService.delete(id);
}
#PostMapping("/users")
public long saveUser(#RequestBody User user) {
userService.saveOrUpdate(user);
return user.getId();
}
#PutMapping("/users")
public User Update(#RequestBody User users) {
userService.saveOrUpdate(users);
return users;
}
}
this is usercontroller class,
how to work with this
i have added this in springboot main class
#Bean
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
return new ServletRegistrationBean(servlet, "*.xhtml");
}
added this in web.xml
<servlet>
<servlet-name>facesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>facesServlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
and this in my index.xhtml file
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
now,it is working
and using this url http://localhost:8080/index.xhtml

JSF xhtml page not found

I've been trying to follow various articles on setting up my first JSF application and can't get my first xhtml page to be found. I keep getting the error "This application has no explicit mapping for /error, so you are seeing this as a fallback" in the browser.
In the browser, I type http://localhost:8080/modelSimulation.xhtml to get this error, and in the console, I see:
... :GET "/modelSimulation.xhtml", parameters={}
... :No mapping for GET /modelSimulation.xhtml
My spring boot application has added the various things required to setup JSF with spring boot, but clearly I'm missing something to be able to view my modelSimulation.xhtml page. What am I missing? Thanks!
I also tried http://localhost:8080 but get corresponding no mapping error too.
src/main/webapp/WEB-INF/modelSimulation.xhtml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:p="http://primefaces.org/ui">
<ui:composition template="layout.xhtml">
<ui:define name="content">
<h:form id="mainForm">
<p:panel header="Details">
<h:panelGrid columns="1">
<p:outputLabel for="symbol" value="Symbol: " />
<p:inputText id="symbol" value="#{tradingModelSimulationController.symbol}" />
<p:outputLabel for="ranking" value="ranking: " />
<p:inputNumber id="ranking" value="#{tradingModelSimulationController.ranking}" />
<h:commandButton value="apply" action="#{tradingModelSimulationController.apply}" />
</h:panelGrid>
</p:panel>
</h:form>
</ui:define>
</ui:composition>
</html>
src/main/webapp/WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<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>*.jsf</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</web-app>
I added the 2 required beans to the SpringBootApplication class:
#Bean
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
return new ServletRegistrationBean(servlet, "*.jsf");
}
#Bean
public FilterRegistrationBean rewriteFilter() {
FilterRegistrationBean rwFilter = new FilterRegistrationBean(new RewriteFilter());
rwFilter.setDispatcherTypes(EnumSet.of(DispatcherType.FORWARD, DispatcherType.REQUEST,
DispatcherType.ASYNC, DispatcherType.ERROR));
rwFilter.addUrlPatterns("/*");
return rwFilter;
}
Here's the backing bean (I don't understand the #Join...)
#Scope(value = "session")
#Component(value = "tradingModelSimulationController")
#ELBeanName(value = "tradingModelSimulationController")
#Join(path = "/modelSimulation", to = "/modelSimulation.jsf")
public class TradingModelSimulationController {
ModelSimulation modelSimulation = new ModelSimulation();
String symbol;
int ranking;
public void apply() {
System.out.println("Applied: " + modelSimulation.toString());
RequestContext.getCurrentInstance()
.execute("handleMsg('applied!');");
}
public ModelSimulation getModelSimulation() {
return modelSimulation;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
}

Xhtml page mapping from ManagedBean

Here Is Managed Bean Class
package Controller;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import Model.Employee;
#ManagedBean(name="employeeController")
#SessionScoped
public class Employeecontroller implements Serializable{
public String show(){
System.out.println("hello");
return "Login";
}
}
Here Is web.xml file
<?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" id="WebApp_ID" version="3.1">
<display-name>Secondproject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<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>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>homepage.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Here id home.xhtml page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:rich="http://richfaces.org/rich"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:h="http://java.sun.com/jsf/html">
<h:head></h:head>
<body>
<rich:panel>
<f:facet name="header">
Write your own custom rich components with built-in AJAX support
</f:facet>
<h:outputText value="Panel Body" />
<h:form>
<h:commandButton action="#{employeeController.show()}" value="Login" />
</h:form>
</rich:panel>
</body>
</html>
Here is the code for mapping xhtml page from ManagedBean.
I just want when the button is clicked then the login page will show....But when the button is clicked there is only home.xhtml page reloading...Login page is not loading....
The selection of the next view depends on the value of the action attribute of the UICommand components. If the navigation handler finds a navigation rule for this page with this outcome, the next view will be the element content. If there is no any rule like this it looks for a page with the value (or it appended with ".xhtml" file extension).
The variations:
1., Direct view definition:
<h:commandButton action="next_page_name"/>
It must be a full qualified name (page names + file name), but the xhtml could be omitted.
2., Indirect view definition:
In this case the action value is contains a bean method invocation:
<h:commandButton action="#{myBean.methodName}"/>
This method should be a function without any parameter and passes back a String value. This result will be the income for the navigation handler. It could return a page name or a navigation rule.
Now let us see your problem. If the name of your current view is id_home.xhml and you want to navigate to the login.xhtml page (both are in the x package):
1., Direct view definition. Return value "x/login" or "x/login.xhtml" from the show() method:
public String show()
{
//...
return "x/login";
}
2., Indirect view definition. Define a page navigation rule in the faces-config.xml like this:
<navigation-rule>
<from-view-id>/x/id_home.xhtml</from-view-id>
<navigation-case>
<from-outcome>go_to_login</from-outcome>
<to-view-id>x/login.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
In this case myBean.methodName passes back the content of the form-outcome element:
public String show()
{
//...
return "go_to_login";
}

init #PostConstruct doesnt work

I have created a web dynamic project using hibernate4 and spring4.
here are my files:
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">
<display-name>posts</display-name>
<welcome-file-list>
<welcome-file>users.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-context.xml</param-value>
</context-param>
</web-app>
here is the bean where I invoked init() method
package com.posts.beans;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.posts.models.Users;
import com.posts.services.UsersService;
#SuppressWarnings("serial")
#Component("Usersbean")
#Scope("session")
public class UsersBean implements Serializable{
#Autowired
private transient UsersService us;
private List<Users> lu;
public UsersBean() {
}
#PostConstruct
public void init(){
lu=us.getAllUsers();
System.out.println("hello");//doesn't shw up=init() doesnt work
}
public String getMyname(){
return "mohamed";
}
public List<Users> getLu() {
return lu;
}
public void setLu(List<Users> lu) {
this.lu = lu;
}
}
here is my jsp file ; I tried to show just one field:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<!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 list users</title>
</head>
<body>
<jsp:useBean id="users" class="com.posts.beans.UsersBean" />
<table border="1">
<tr><th>id</th><th>nom</th><th>prenom</th><th>login</th><th>password</th></tr>
</table>
<c:forEach var="user" items="${users.lu}">
<p><c:out value="${user.nom}" /></p>
</c:forEach>
</body>
</html>
so the console doesnt show the message "hello" in method init which means that id doesnt work.
maybe it is because that i didnt declare servlet element in web.xm, but i dont have any idea on how it works ..
NB: I tested Services With JUnit, worked fine
i have solved that problem with annotating UserBean class with #Service("userbean") and adding :
<bean id="usersBean" class="com.posts.beans.UsersBean" init-method="init" />
in application-context.xml file ..
when I run my application , i see hibernate generated code of SELECT and the message hello
Hello
Hibernate: select users0_.id as id1_2_, users0_.login as login2_2_, users0_.nom as nom3_2_, users0_.password as password4_2_, users0_.prenom as prenom5_2_ from public.users users0_
" in the console which means that init() method have been executed.
You can make it work in three different ways:
add to your application-context.xml bean that is responsible to work out #PostConstruct annotation:
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
add namespase that already has CommonAnnotationBeanPostProcessor inside:
<context:annotation-config />
or
<context:component-scan base-package="package.with.beans" /> <!-- scans components and adds <context:annotation-config /> -->
define init method in the tag bean of your class for argument "init-method"

No WebApplicationContext found: no ContextLoaderListener registered?

I'm trying to create a simple Spring 3 application and have the following files. Please tell me the reason for this error
Below is my 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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Spring2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Below is my index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Index Page<br/>
<form:form commandName="loginBean" method="POST" action="login">
<form:input path="userName" id="userName"/><br/>
<form:input path="password" id="password"/><br/>
<input type="submit" value="submit"/>
</form:form>
Go to Registration Page
</body>
</html>
Below is my 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean name="/login" class="com.infy.controller.LoginController"/>
</beans>
This is the LoginController.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LoginController {
#RequestMapping(value="/login", method=RequestMethod.POST)
public ModelAndView loginAction(#ModelAttribute("loginBean")LoginBean bean){
return new ModelAndView("success", "success", "Successful Login");
}
}
And finally my LoginBean
public class LoginBean {
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;
}
}
You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to understand the difference between Web application context and root application context .
In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which
inherits all the beans already defined in the root WebApplicationContext. These inherited
beans defined can be overridden in the servlet-specific scope, and new scope-specific
beans can be defined local to a given servlet instance.
The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .
Read the spring reference here for spring mvc .
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener,
then see -> https://stackoverflow.com/a/40694787/3004747

Resources