Can't match css file with segment uri Spring Framewwork 4 - java

Hei guys! I have a servlet config as below.
vietjob-servlet
<mvc:annotation-driven />
<context:component-scan base-package="vjb.de.vietjob" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:view-controller path="/" view-name="index" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:lang" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>
And in web xml i declare the uri for servlet
web.xml
<servlet>
<servlet-name>vietjob</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>vietjob</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
If i write all controller request mapping under /, everything is ok, servlet can load all libraries inside resources folder. But when i give controller a segment, i got error with
WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI
For details the link localhost:8001/vjb.de/ehdokas.do is working but localhost:8001/vjb.de/employee/ehdokas.do not work. I guess that when i give a segment, the servlet will scan employee/resources instead /resources, so the error occurred.
And another issue: when user login into system, the link was changed from http://localhost:8001/vjb.de/ehdokas.do to http://localhost:8001/vjb.de/employee/ehdokas.do. How can i config a same controller with all urls, i mean controller can run without relative to url address. Every link abc/def/ehdokas.do or abc/ehdokas.do also call to controller ehdokas.do?!
Controller class
#Controller
#RequestMapping(value = "/employee")
public class EhdokasController {
#Inject
private EhdokasDao ehdokasdao;
#Inject
private AlaDao aladao;
public AlaDao getAlaDao(){
return aladao;
}
public void setAlaDao(AlaDao aladao){
this.aladao=aladao;
}
public EhdokasDao getEhdokasDao() {
return ehdokasdao;
}
public void setEhdokasDao(EhdokasDao ehdokasdao) {
this.ehdokasdao = ehdokasdao;
}
#RequestMapping(value="/", method=RequestMethod.GET)
public String showEmployeePage(#RequestParam(value="tunnus") String tunnus, Model model){
System.out.println("ehdokasdao: "+ehdokasdao);
EhdokasImpl ehdokas = (EhdokasImpl) ehdokasdao.getEhdokasByTunnus(tunnus);
model.addAttribute("ehdokas", ehdokas);
return "ehdokas/ehdokas_home";
}
// Siirtää ehdokas lomake sivulle
#RequestMapping(value = "/lomake.do", method = RequestMethod.GET)
public String forwardToLomake(Model model) {
Ehdokas ehdokas = new EhdokasImpl();
List<Integer> listId = aladao.getListAlaId();
model.addAttribute("listId", listId);
model.addAttribute("ehdokas", ehdokas);
return "lomake/lomake_ehdokas";
}
// ota syötetyt tiedot lomakkeesta
#RequestMapping(value = "/lomake.do", method = RequestMethod.POST)
public String getTietoLomake(
#ModelAttribute(value = "ehdokas") #Valid EhdokasImpl ehdokas, BindingResult result, Model model) {
if (result.hasErrors()) {
return "lomake/lomake_ehdokas";
} else {
ehdokasdao.postEhdokas(ehdokas);
return "redirect:/ehdokas.do";
}
}
// näytä kaikki ehdokkaat tietokannasta
#RequestMapping(value = "/ehdokas.do", method = RequestMethod.GET)
public String showEhdokkaat(Model model) {
List<String> kaupunkiList = ehdokasdao.getKotiKaupunki();
List<Ehdokas> ehdokkaat = ehdokasdao.showEhdokas();
model.addAttribute("ehdokkaat", ehdokkaat);
model.addAttribute("kaupunkiList", kaupunkiList);
model.addAttribute("ehdokas", new EhdokasImpl());
return "ehdokas/ehdokas_list";
}
#RequestMapping(value = "/ehdokas.do", method = RequestMethod.POST)
public String showEhdokkaat(
#ModelAttribute(value = "ehdokas") EhdokasImpl ehdokas,#PathVariable(value="kaupunki") String kaupunki, #PathVariable(value="id") int id,#RequestParam(value="submit") String submit, Model model) {
System.out.println(submit);
if(submit.equals("Hae") || submit.equals("Search")){
List<String> kaupunkiList = ehdokasdao.getKotiKaupunki();
List<Ehdokas> ehdokkaat = ehdokasdao.getEhdokasByKaupunki(kaupunki);
model.addAttribute("ehdokkaat", ehdokkaat);
model.addAttribute("kaupunkiList", kaupunkiList);
return "ehdokas/ehdokas_list";
} else if (submit.equals("More") || submit.equals("Lisätieto")){
model.addAttribute("id",id);
return "redirect:yksiehdokas.do";
} else
return "redirect:ehdokas.do";
}
#RequestMapping(value="/yksiehdokas.do", method=RequestMethod.GET)
public String showYksiEhdokas(#RequestParam(value="id") int id, Model model ){
Ehdokas ehdokas = ehdokasdao.searchEhdokasById(id);
model.addAttribute("ehdokas", ehdokas);
return "ehdokas/ehdokas_yksi";
}
/*siirrä apply sivulle*/
#RequestMapping(value="/apply.do", method= RequestMethod.GET)
public String forwardToApply(Model model){
Kayttaja kayttaja = new KayttajaImpl();
Ehdokas ehdokas = new EhdokasImpl();
model.addAttribute("kayttaja", kayttaja);
model.addAttribute("ehdokas", ehdokas);
return "apply";
}
#RequestMapping(value="/apply.do", method= RequestMethod.POST)
public String getInfoEmployee(#ModelAttribute(value="ehdokas") EhdokasImpl ehdokas){
ehdokasdao.postEhdokas(ehdokas);
return "redirect:ehdokas.do";
}
#ModelAttribute("kieliList")
public List<String> getKieli() {
List<String> list = new ArrayList<String>();
list.add("English");
list.add("Finnish");
list.add("Germany");
return list;
}
#ModelAttribute("tutkinnot")
public List<String> getTutkinto() {
List<String> list = new ArrayList<String>();
list.add("Päiväkoti");
list.add("Peruskoulu");
list.add("Lukio");
list.add("AMK");
list.add("Yliopisto");
return list;
}
}
Jsp file
<%# page session="false"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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">
<%# include file="/WEB-INF/views/templates/navbar-bootstrap.jsp"%>
<%# include file="/WEB-INF/views/templates/logo-banner.jsp"%>
<%# include file="/WEB-INF/views/templates/menu-bootstrap.jsp"%>
<script src="<c:url value="resources/bootstrap-3.3.6/js/bootstrap.min.js" />"></script>
<link href="resources/bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="resources/js/jquery-1.12.2.min.js"></script>
<style>
/* Set black background color, white text and some padding */
.container-fluid {
width: 1000px;
margin: auto;
}
.form-control{
width: 30px;
}
</style>
<title><spring:message code="employee.page.list" /></title>
</head>
<body>
<div class="container-fluid text-center">
<div class="row content">
<div class="col-sm-2 sidenav">
<p>Link</p>
<p>Link</p>
<p>Link</p>
</div>
<div class="col-sm-8 text-left">
<form:form class="form-inline" action="ehdokas.do" modelAttribute="ehdokas" method="POST">
<form:select class="form-control" path="kaupunki">
<form:option value="">select city</form:option>
<form:options items="${kaupunkiList}"></form:options>
</form:select>
<spring:message code="button.search" var="search" />
<input type="submit" name="submit" value="${search }" />
</form:form>
<h3><spring:message code="kaikki.ehdokas"></spring:message></h3>
<hr>
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Gender</th>
<th>City</th>
</tr>
</thead>
<tbody>
<c:forEach var="ehdokas" items="${ehdokkaat}">
<tr>
<td><c:out value="${ehdokas.suku} "></c:out></td>
<td><c:out value="${ehdokas.etu} "></c:out></td>
<td><c:out value="${ehdokas.sukupuoli} "></c:out></td>
<td><c:out value="${ehdokas.kaupunki} "></c:out></td>
<form:form action="ehdokas.do" method="post">
<input type="hidden" name="id" value="${ehdokas.id }" />
<spring:message code="button.more" var="more"/>
<td><input type="submit" name="submit" class="btn btn-info" value="${more }" /></td>
</form:form>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div class="col-sm-2 sidenav">
<div class="well">
<p>ADS</p>
</div>
<div class="well">
<p>ADS</p>
</div>
</div>
</div>
</div>
<%# include file="/WEB-INF/views/templates/footer-bootstrap.jsp"%>
</body>
</html>

Related

how to save value from POST method into parameter of Java class?

I'm new in Java, and currently try to create my own project, but have a problem with displaying information about user in his main page. Now I need to save a value from my JSP page (/login) which use method POST into parameter of my Java class("Controller").
login.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Log in with your account</title>
<link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
<link href="${contextPath}/resources/css/common.css" rel="stylesheet">
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
</head>
<body>
<div class="container">
<form method="POST" action="${contextPath}/login" class="form-signin">
<h2 class="form-heading">Log in</h2>
<div class="form-group ${error != null ? 'has-error' : ''}">
<span>${message}</span>
<input name="email" type="text" class="form-control" placeholder="Email"
autofocus="true"/>
<input name="password" type="password" class="form-control" placeholder="Password"/>
<span>${error}</span>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<button class="btn btn-lg btn-primary btn-block" type="submit">Log In</button>
<h4 class="text-center">Create an account</h4>
</div>
</form>
</div>
<!-- /container -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
</body>
</html>
and UserController
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "registration";
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(#ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.save(userForm);
securityService.autoLogin(userForm.getEmail(), userForm.getConfirmPassword());
return "redirect:/fillingform";
}
#RequestMapping(value = "/login")
public String getEmail(#RequestParam("email") String email) {
return email;
}
appconfig-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true">
<intercept-url pattern="/" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')"/>
<intercept-url pattern="/welcome" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')"/>
<intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')"/>
<form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/login?error"
username-parameter="email" password-parameter="password"/>
<logout logout-success-url="/login?logout"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsServiceImpl">
<password-encoder ref="encoder"></password-encoder>
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsServiceImpl"
class="com.gmail.*">
</beans:bean>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11"/>
</beans:bean>
</beans:beans>
UserDetailsServImpl
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserDao userDao;
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userDao.findByEmail(email);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities);
}
}
Read a lot of information, if for real about it,heard recommendation about doPost() method, request.getParameter() and so on, but nothing help (
Please help, what logic code I need to put in method "public String getEmail" for getting user Emailfrom POST form.
Thank's.

Java Spring - IllegalStateException when retrieving data from jsp form

I have a pretty nasty and frustrating problem with a Maven Web Application, holding me back for some time.
Apparently, from my previous google searches, this is a common Spring MVC error, but i am not able to find the solution i need among the ones offered on the internet so far. Note that i am a beginner in Spring and in MVC concepts in general.
I have a web application which is supposed to manage a building administration (inhabitants, rent calculations, etc). I use Spring MVC, Hibernate, Java 1.8, Tomcat 8 server container, and SQL Server 2014.
Firstly, this is my POJO for the bulding residents, a type called Inhabitant:
#Entity
#Table (name = "INHABITANT")
public class Inhabitant {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "ID")
private long id;
#Column(name = "FIRSTNAME")
private String firstName;
#Column(name = "LASTNAME")
private String lastName;
#Column(name = "APARTAMENT_NUMBER")
private String apartamentNumber;
#Column(name = "APARTAMENT_OWNER")
private String apartamentOwner;
#Column(name = "TELEPHONE_NUMBER")
private String telephoneNumber;
#Column(name = "EMAIL_ADDRESS")
private String emailAddress;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getApartamentNumber() {
return apartamentNumber;
}
public void setApartamentNumber(String apartamentNumber) {
this.apartamentNumber = apartamentNumber;
}
public String getApartamentOwner() {
return apartamentOwner;
}
public void setApartamentOwner(String apartamentOwner) {
this.apartamentOwner = apartamentOwner;
}
public String getTelephoneNumber() {
return telephoneNumber;
}
public void setTelephoneNumber(String telephoneNumber) {
this.telephoneNumber = telephoneNumber;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
This is my dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd">
<context:component-scan base-package="laura.bachelordegree.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
This is my web.xml:
<?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" -->
<display-name>BuildingAdministration</display-name>
<welcome-file-list>
<welcome-file>login/index.jsp</welcome-file>
</welcome-file-list>
<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
This is my jsp registration form, which should map to the Inhabitant object:
<!DOCTYPE html>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%#page session="false" %>
<html>
<head>
<meta charset="utf-8" />
<title>Registration</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="login/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="login/font-awesome/css/font-awesome.min.css" />
<script type="text/javascript" src="login/js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="login/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<!-- Registration form - START -->
<div class="container">
<div class="row">
<%-- <form role="form"> --%>
<form:form method="post" modelAttribute="inhabitant" role="form" action="BuildingAdministration/src/main/webapp/login/result">
<div class="col-lg-6">
<div class="well well-sm"><strong><span class="glyphicon glyphicon-asterisk"></span>Required Field</strong></div>
<div class="form-group">
<label for="InputFirstName">Enter First Name</label>
<div class="input-group">
<form:input path="firstName" type="text" cssClass="form-control" id="InputFirstName" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputLastName">Enter Last Name</label>
<div class="input-group">
<form:input path="lastName" type="text" cssClass="form-control" id="InputLastName" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputApartmentNumber">Enter Apartment Number</label>
<div class="input-group">
<form:input path="apartmentNumber" type="text" cssClass="form-control" id="InputApartmentNumber" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputApartmentOwner">Enter Apartment Owner</label>
<div class="input-group">
<form:input path="apartmentOwner" type="text" cssClass="form-control" id="InputApartmentOwner" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputTelephoneNumber">Enter Telephone Number</label>
<div class="input-group">
<form:input path="telephoneNumber" type="text" cssClass="form-control" id="InputTelephoneNumber" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputEmail">Enter Email</label>
<div class="input-group">
<form:input path="emailAddress" type="email" cssClass="form-control" id="InputEmailFirst" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<div class="form-group">
<label for="InputEmail">Confirm Email</label>
<div class="input-group">
<form:input path="emailAddress" type="email" cssClass="form-control" id="InputEmailSecond" />
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">
</div>
</form:form>
<%-- </form> --%>
<div class="col-lg-5 col-md-push-1">
<div class="col-md-12">
<div class="alert alert-success">
<strong><span class="glyphicon glyphicon-ok"></span> Success! Message sent.</strong>
</div>
<div class="alert alert-danger">
<span class="glyphicon glyphicon-remove"></span><strong> Error! Please check all page inputs.</strong>
</div>
</div>
</div>
</div>
</div>
<!-- Registration form - END -->
</body>
</html>
And finally, the controller class, which should effectively map the data from the jsp form with the java entity, Inhabitant:
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String loadInhabitant(#ModelAttribute("inhabitant")Inhabitant inhabitant,
ModelMap model) {
model.addAttribute("firstName", inhabitant.getFirstName());
model.addAttribute("lastName", inhabitant.getLastName());
model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
model.addAttribute("apartmentOwner", inhabitant.getApartamentOwner());
model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
model.addAttribute("telephoneNumber", inhabitant.getTelephoneNumber());
model.addAttribute("emailAddress", inhabitant.getEmailAddress());
return "result";
}
Now, this is the error i get whenever i try to run my application on the server:
message java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'inhabitant' available as request attribute
description The server encountered an internal error that prevented it from fulfilling this request.
exception org.apache.jasper.JasperException:
java.lang.IllegalStateException: Neither BindingResult nor plain
target object for bean name 'inhabitant' available as request
attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:555)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:471)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause java.lang.IllegalStateException: Neither BindingResult nor
plain target object for bean name 'inhabitant' available as request
attribute
org.springframework.web.servlet.support.BindStatus.(BindStatus.java:144)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:117)
org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.login.index_jsp._jspx_meth_form_005finput_005f0(index_jsp.java:322)
org.apache.jsp.login.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:216)
org.apache.jsp.login.index_jsp._jspService(index_jsp.java:148)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I have tried a thousand things, but i just can't get it to work. So, please, can someone point out what i'm doing wrong? How can i correctly build the java object based on the information from the jsp form?
Thanks in advance!
It seems you need to understand more about spring mvc.
You are mapping your form request to a view. you must map your form request to a controller method not a view, your form should look like this :
<form:form action="${pageContext.request.contextPath}/inhabitant/create" method="post" modelAttribute="inhabitant" >
....
// have a look at spring form validation
// have a look at spring form elements eg. how error messages are displayed
</form:form>
You need two methods in controller to create and save inhabitant one for showing a form and another for saving form datas into database. Now your controller should look like this :
#Controller
#RequestMapping(value="/inhabitant")
public class PostController {
#Autowired
private InhabitantService inhabitantService;
//Method that displays the form page
#RequestMapping(value = "/create", method = RequestMethod.GET)
public String createForm(Model model ) {
model.addAttribute("inhabitant", new Inhabitant()); // identifier should be same as modelattribute in your form "inhabitant"
return "formpage"; // your form page name
}
// Method which will have the submitted data
// Validation is also done in this method
#RequestMapping(value="/create", method=RequestMethod.POST)
public String saveForm( #ModelAttribute("inhabitant") #Valid Inhabitant inhabitant, //#valid is used for validation use it If you are doing validation
BindingResult result // use only if you are doing validation)
{
// use only If you are doing validation
// If validation fails users must return to the same form view
if (result.hasErrors()){
return "formpage";
}
//and save the submitted form data
inahabitantService.saveInhabitant(inhabitant);
enter code here
return "success"; // success.jsp is a success page that you will see after creating a inhabitant
}
Do not use '/login' as a url patern in your web.xml Just dont do it.
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/login</url-pattern> //Just Use '/' instead of '/login'
</servlet-mapping>
I doubt that you have configured hibernate properly Post your hibernateConfiguration.xml file and persistence.xml file.
You must learn and understand these: Just take your time.
Spring Model Controller View and how does it really work
Spring Form elements, Spring Form Validation
Jpa / hibernate basics / association in hibernate
Jsp taglibs / JSP inside Jsp / Apache Tiles
Don't do that
model.addAttribute("firstName", inhabitant.getFirstName());
model.addAttribute("lastName", inhabitant.getLastName());
model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
model.addAttribute("apartmentOwner", inhabitant.getApartamentOwner());
model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
model.addAttribute("telephoneNumber", inhabitant.getTelephoneNumber());
model.addAttribute("emailAddress", inhabitant.getEmailAddress());
Do this instead
model.addAttribute("inhabitant", inhabitant);

i am trying to load my view from the controller in spring, net beans, with Glass fish server 4.0: following are the respective classes

MY ControllerClass:
I am trying to bind this controller class with its respective view called priceincrease.jsp
I am new to spring and i found out that this SimpleFormController class has been depricated since spring 3.0. How do i use controller to bind with my view?
Could anyone help me ?
public class PriceIncreaseController extends SimpleFormController {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private ProductManager productManager;
public ModelAndView onSubmit(Object command)
throws ServletException {
int increase = ((PriceIncrease) command).getPercentage();
logger.info("Increasing prices by " + increase + "%.");
productManager.increasePrice(increase);
logger.info("returning from PriceIncreaseForm view to " + getSuccessView());
return new ModelAndView(new RedirectView(getSuccessView()));
}
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(20);
return priceIncrease;
}
public void setProductManager(ProductManager productManager) {
this.productManager = productManager;
}
public ProductManager getProductManager() {
return productManager;
}
}
My priceincrease.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<title><fmt:message key="title"/></title>
<style>
.error { color: red; }
</style>
</head>
<body>
<h1><fmt:message key="priceincrease.heading"/></h1>
<form:form method="post" commandName="priceIncrease">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
<tr>
<td align="right" width="20%">Increase (%):</td>
<td width="20%">
<form:input path="percentage"/>
</td>
<td width="60%">
<form:errors path="percentage" cssClass="error"/>
</td>
</tr>
</table>
<br>
<input type="submit" align="center" value="Execute">
</form:form>
Home
</body>
</html>
My dispatcher-servelet.xml
<bean name="/priceincrease.htm" class="web.PriceIncreaseController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="priceIncrease"/>
<property name="commandClass" value="service.PriceIncrease"/>
<property name="validator">
<bean class="service.PriceIncreaseValidator"/>
</property>
<property name="formView" value="priceincrease"/>
<property name="successView" value="inventory.htm"/>
<property name="productManager" ref="productManager"/>
</bean>
This is the error i have received:
HTTP Status 500 - Internal Server Error
type Exception report
messageInternal Server Error
descriptionThe server encountered an internal error that prevented it
from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Handler
processing failed; nested exception is java.lang.NoClassDefFoundError:
org/springframework/web/util/ExpressionEvaluationUtils root cause
java.lang.NoClassDefFoundError:
org/springframework/web/util/ExpressionEvaluationUtils root cause
java.lang.ClassNotFoundException:
org.springframework.web.util.ExpressionEvaluationUtils note The full
stack traces of the exception and its root causes are available in the
GlassFish Server Open Source Edition 4.0 logs.
If you are familiar with Spring you can mark your controllers with #Controller annotations.
For eg.
#Controller
public class DispensaryController {
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String dispensary(Model model) {
// This can be used in the jsp as ${name} when you access it.
model.addAttribute("name", "Santosh");
return "testPage";
}
}
Also include this in your servlet if you want to return pages
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>

How to use the AJAX response to modify existing url in a Spring mvc project?

I am working on a Spring MVC project where the homepage has two input fields. Both input fields are of String type. But the regNo field gets number and if the user enters the regNo it should be taken to the corresponding method in controller. If the user enters the name, it should be taken to the corresponding method in controller.
web.xml
<web-app version="2.2" id="WebApp_ID">
<!-- <display-name>Archetype Created Web Application</display-name> -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appContext.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/spring/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/mvc/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/template.jsp</welcome-file>
</welcome-file-list>
</web-app>
1) What is the purpose of id="WebApp_ID"?
tiles.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
"http://tiles.apache.org/dtds/tiles-config_2_1.dtd">
<tiles-definitions>
<definition name="template" template="/WEB-INF/jsp/template.jsp">
<put-attribute name="title" value=""/>
<put-attribute name="header" value="/WEB-INF/jsp/header.jsp" />
<put-attribute name="body" value="/WEB-INF/jsp/ads.jsp "/>
<put-attribute name="center" value="/WEB-INF/jsp/ads.jsp" />
<put-attribute name="footer" value="/WEB-INF/jsp/footer.jsp" />
</definition>
<definition name="header" extends="template">
<put-attribute name="title" value="" />
<put-attribute name="body" value="/WEB-INF/jsp/ads.jsp" />
</definition>
<definition name="numberResult" extends="template">
<put-attribute name="title" value="" />
<put-attribute name="body" value="/WEB-INF/jsp/nResult.jsp" />
</definition>
<definition name="nameResult" extends="template">
<put-attribute name="title" value="" />
<put-attribute name="body" value="/WEB-INF/jsp/neResult.jsp" />
</definition>
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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.ProjectCtxt.www.controller"/>
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- <bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" /> -->
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesViewResolver"/>
<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
</beans>
ProjectController.java
#Controller("resultController")
public class ResultController {
private final ResultService resultService;
#Autowired
public ResultController(ResultService resultService) {
this.resultService = resultService;
}
#RequestMapping(value ="/template", method = RequestMethod.GET)
public String getPersonList(ModelMap model) {
System.out.println("We are coming into this place");
return "header";
}
#RequestMapping(value = "/search/s", method = RequestMethod.GET, params = { "regNo" })
public String getStudentResult(#RequestParam(value = "regNo", required = true) String regNo, ModelMap model){
System.out.println("I am coming here when I enter regNo and AJAX works");
model.addAttribute("studentResult",resultService.getStudentResult(regNo));
return "numberResult";
}
#RequestMapping(value = "/search/l/studentName={studentName}", method = RequestMethod.GET, params = { "studentName" })
public String anotherMethod(String studentName, ModelMap model){
return "nameResult";
}
}
header.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
</head>
<form method="GET" >
<input type="text" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"></input>
<input type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
<button onclick="processInput();">Search
</button>
</form>
<script>
function processInput(){
if (document.getElementById('regNo').value !=""){
$.ajax({
type : 'GET',
url : "search/s",
data : { "regNo":$("#regNo").val()},
success : function(studentResult) {
//show your result
// alert("Value");
$('#displayArea').html(studentResult); }
});
}else if (document.getElementById('studentName').value !=""){
$.ajax({
type : 'GET',
url : "search/l",
data : { "studentName":$("#studentName").val(),
success : function(result) {
//show your result
}}
});
}
}
</script>
template.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<center>
<table width="750" border="0" cellpadding="2" cellspacing="2" align="center">
<tr>
<td><tiles:insertAttribute name="header" />
</td>
</tr>
<tr>
<td><tiles:insertAttribute name="body" /></td>
</tr>
<tr>
<td height="225"><tiles:insertAttribute name="footer" />
</td>
</tr>
</table>
</center>
</html>
numberResult.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:out value="This is working"/>
<c:out value="${studentResult.name}"/><br/>
<c:out value="${studentResult.regNo}"/><br/>
<c:out value="${studentResult.deptName}"/><br/>
<c:out value="${studentResult.collName}"/><br/>
<div id="displayArea">
<c:out value="${studentResult.name}"/><br/>
<c:out value="${studentResult.regNo}"/><br/>
<c:out value="${studentResult.deptName}"/><br/>
<c:out value="${studentResult.collName}"/><br/>
</div>
2) User enters the regNo in header.jsp,and I want the result to be shown in numberResult.jsp
3) My first url is localhost:8080/ProjectCtxt/mvc/template goes to homepage. When I enter regNo in the input field, my url in browser shows localhost:8080/ProjectCtxt/mvc/template/regNo=123&studentName= . And I am reaching the getStudentResult method as I could see my System.out in console, but I am not able to see the output in browser.
Since I am using tiles, I am not sure the problem is with tiles resolver or the AJAX. Could you please help me? Thanks.
PS: Please answer all questions if possible with numbers so that it will help others. Thanks.
UPDATE: I changed my header.jsp as follows and now I see "numberResult" in UI. But I don't see the numberResult jsp as body of template.jsp. I guess the "numberResult" text is returned to success part of AJAX.
<input type="text" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"></input>
<input type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
<input id="inputFields" type="button" value="Search" />
<script>
$(document).ready(function(){
$('#inputFields').click(function(){
processInput();
});
});
function processInput(){
if (document.getElementById('regNo').value !=""){
$.ajax({
type : 'GET',
url : "search/s",
data : { "regNo":$("#regNo").val()},
success : function(studentResult) {
//show your result
alert("Value");
$('#displayArea').html(studentResult); //this line displays text //"numberResult". But it doesn't change the jsp as well as the url. Now my url looks as //localhost:8080/mvc/template and the body of the jsp doesn't have numberResult.jsp
}
});
}else if (document.getElementById('studentName').value !=""){
$.ajax({
type : 'GET',
url : "search/l",
data : { "studentName":$("#studentName").val(),
success : function(result) {
//show your result
}}
});
}
}
</script>
<div id="displayArea">
<c:out value="${studentResult.name}"/><br/>
<c:out value="${studentResult.regNo}"/><br/>
<c:out value="${studentResult.deptName}"/><br/>
<c:out value="${studentResult.collName}"/><br/>
</div>
Try put anotation #ResponseBody to your controller
#RequestMapping(value = "/search/s", method = RequestMethod.GET, params = { "regNo" })
#ResponseBody
public String getStudentResult(#RequestParam(value = "regNo", required = true) String regNo, ModelMap model){
System.out.println("I am coming here when I enter regNo and AJAX works");
model.addAttribute("studentResult",resultService.getStudentResult(regNo));
return "success";
}
EDIT
Okay, I think I misunderstood the initial problem and the expected result. There are a couple problems with your approach.
You are trying to attach an AJAX event to a button that submits a form in a non-asynchronous manner.
You are trying to display the response from the AJAX request in a JSP tag.
Both of these problems are issues of incompatible components. When you submit a form in a non-asynchronous manner, you are requesting a new page, which the browser loads, and your JavaScript does not have time to complete and display results. JSP tags can not be loaded and displayed asynchronously because they need to be processed on the server. This leaves you with two possible solutions:
1. Make the process completely asynchronous.
Remove the form tag, and leave the inputs and buttons:
<input type="text" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"></input>
<input type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
<button id="searchButton">Search</button>
Now there is no form to submit, so you don't have to worry about accidentally overriding your AJAX functionality. Update your JavaScript to read the input values, execute the proper AJAX request, and display the results:
$("#searchButton").on("click", function(){
if ($('#regNo').val() !=""){
$.ajax({
type : 'GET',
url : "search/s",
data : { "regNo":$("#regNo").val()},
success : function(studentResult) {
$('#displayArea').html("<p>" + studentResult.id + "</p><p>" + studentResult.name + "</p><p>etc...</p>); }
});
}else if (document.getElementById('studentName').value !=""){
$.ajax({
type : 'GET',
url : "search/l",
data : { "studentName":$("#studentName").val(),
success : function(result) {
//show your result
}}
});
}
});
Make sure that the controller handling your AJAX method is set up to return an object JavaScript can understand. Spring should be able to serialize most objects you give it:
#RequestMapping(value = "/search/s", method = RequestMethod.GET, params = { "regNo" })
public #ResponseBody StudentResult getStudentResult(#RequestParam(value = "regNo") String regNo){
return resultService.getStudentResult(regNo);
}
2. Make the process completely non-asynchronous
If you are set on using your JSP tag to display the data, you can scrap the AJAX and submit the form in the usual fashion:
<form method="POST">
<input type="text" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"></input>
<input type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
<button id="searchButton">Search</button>
</form>
You can supply an action attribute if you would like the form to POST or perform a GET to a different URL. Create a single controller method to handle the submission:
#RequestMapping(value = "/someUrl", method = RequestMethod.POST)
public String getStudentResult(#RequestParam(value = "regNo", required = false) String regNo, #RequestParam(value = "studentName", required = false) String studentName, ModelMap model){
if (regNo != null && !regNo.equals("")){
model.addAttribute("studentResult",resultService.getStudentResult(regNo));
return "numberResult";
} else if (studentName != null && !studentName.equals("")){
model.addAttribute("nameResult", someOtherObject);
return "nameResult";
} else {
model.addAttribute("errorMessage", "No form data supplied!");
return "someOtherView";
}
}
Now, as long as you have your views set up to accept the returned objects and map them in your JSTL, your tags should work just fine.

Spring application is giving two different URLs in two different time

I am developing a Spring application that will do a basic CRUD operation.The login and after login the population of information is working properly.But when i trying to forward to a page from the main page i.e from where all the information is coming.The URL that is coming is strange and i can not find a reason behind that.i am posting my full code here...
web.xml
<display-name>SpringWebCrudExample</display-name>
<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>/forms/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
">
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<context:component-scan base-package="com.gamma.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
login.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>
Login Page
<form:form action="forms/doLogin" commandName="loginForm">
<table>
<tr>
<td>UserName:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:input path="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
mainpage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
main page is here all details will be shown here...
<c:url var="addUrl" value="/add" />
<table style="border: 1px solid; width: 500px; text-align:center">
<thead style="background:#fcf">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Address</th>
<th colspan="3"></th>
</tr>
</thead>
<td>Add</td>
<tbody>
<c:forEach items="${mainpage}" var="student">
<tr>
<td><c:out value="${student.fname}" /></td>
<td><c:out value="${student.lname}" /></td>
<td><c:out value="${student.address}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
AppController
#Controller
public class AppController {
public static DbImpl dbImpl;
#RequestMapping(value = "/start", method = RequestMethod.GET)
public static ModelAndView getAllinfo() {
ModelAndView mav = new ModelAndView("/mainpage");
System.out.println("mainpage is here");
List<StudentVO> allInfo = dbImpl.populateInfo();
System.out.println("The List is " + allInfo.size());
mav.addObject("mainpage", allInfo);
return mav;
}
#RequestMapping(value = "/doLogin", method = RequestMethod.GET)
public String ShowForm(Map model) {
LoginForm loginForm = new LoginForm();
model.put("loginForm", loginForm);
return "login";
}
#RequestMapping(value = "/doLogin", method = RequestMethod.POST)
public ModelAndView ProcessForm(#Valid LoginForm loginForm,
BindingResult result, Map model) {
String userName = "Jeet";
String passWord = "gamma";
if (result.hasErrors()) {
return new ModelAndView("login", "loginDetails", loginForm);
}
loginForm = (LoginForm) model.get("loginForm");
if (!loginForm.getUsername().equals(userName)
|| !loginForm.getPassword().equals(passWord)) {
return new ModelAndView("login", "loginDetails", loginForm);
}
model.put("loginForm", loginForm);
System.out.println("----->" + loginForm.getUsername());
RedirectView redirectView = new RedirectView("start", true);
return new ModelAndView(redirectView);
}
#RequestMapping(value="/add",method=RequestMethod.GET)
public String aMethod2insert(Map model){
StudentVO studentVO=new StudentVO();
model.put("studentVO", studentVO);
return "insertpage";
}
Now the problem is that when i am doing the login it is working fine and it is generating the URL SpringWebCrudExample/forms/start and coming to this page (the picture i attached here).Now i have added a link call add in this page from which i will go to a page where i will insert some vlaues, but the problem is here when i click on this URL it is giving SpringWebCrudExample/add this URL.As the result the page is not coming.
It has nothing to do with spring but with basic URL generation.
When you are prefixing a href with a / it means that this is an absolute URL and it will be navigated from the root of your application. If you leave it out it will be relative to the current URL.
Now lets take an application deployed at /app which has a servlet mapped at /servlet. If you are in a page at /app/servlet/page and you have a href like /foo it will result in the actual location of /app/foo. Leaving the / would lead to /app/servlet/foo.
For more information see Absolute vs relative URLs

Categories

Resources