I have simple controller which must save my form in DB. I tried mapping command "/tests/review/saveChanges" in this controller but when I push button "save" I have "HTTP Status 400 – Bad Request".
My controller:
#Controller
#RequestMapping(value = "/tests")
public class TestController {
private TestInterfaceService testService;
#Autowired(required = true)
#Qualifier(value = "testService")
public void setTestService(TestInterfaceService testService) {
this.testService = testService;
}
//here we get list objects
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String listTests(Model model) {
model.addAttribute("test", new Test());
model.addAttribute("listTests", this.testService.listTests());
return "proposals";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addTest(Test t) {
if (t.getId() == 0) {
this.testService.addTest(t);
} else {
// existing person, call update
this.testService.updateTest(t);
}
return "redirect:/tests/list";
}
#RequestMapping(value = "/remove/{id}")
public String removeTest(#PathVariable("id") long id) {
this.testService.removeTest(id);
return "redirect:/tests/list";
}
//Here we start work with specific object
#RequestMapping("/review/{id}")
public String editTest(#PathVariable("id") long id, Model model) {
Test test = this.testService.getFullTestById(id);
model.addAttribute("candidateTest", test);
model.addAttribute("candidateQuestions", test.getQuestions());
model.addAttribute("candidateAnswers", test.getQuestions());
return "review";
}
//Here I'm try save all changes
#ModelAttribute("candidateTest")
#RequestMapping(value = "/review/saveChanges", method = RequestMethod.POST)
public String review(#PathVariable("candidateTest") Test candidateTest, Model model) {
testService.addTest(candidateTest);
return "redirect:/tests/list";
}
#RequestMapping(value = "/choise/{id}/{status}", method = RequestMethod.GET)
public String choise(#PathVariable("id") long id, #PathVariable("status") String status, Model model) {
Test test = this.testService.getTestById(id);
test.setStatus(TestStatus.Developing.getStatus(status));
this.testService.updateTest(test);
model.addAttribute("test", this.testService.getTestById(id));
model.addAttribute("questions", this.testService.getListQuestionsById(id));
return editTest(id, model);
}
#RequestMapping(value = "/previewTest/{id}")
public String previewTest(#PathVariable("id") long id, Model model) {
Test test = this.testService.getTestById(id);
model.addAttribute("ourTest", test);
return "previewTest";
}
}
My jsp review:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# page session="true"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="${contextPath}/resources/css/bootstrap.min.css">
<script src="${contextPath}/resources/js/jquery-3.2.1.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="left">
<c:url var="formTestUrl" value="/tests/list" />
<spring:message code="back.to.proposals" />
</h1>
<span style="float: right">ru | ua | en </span>
<br>
//And here we have something whorg I'm guest.
<form:form modelAttribute="candidateTest"
action="/tests/review/saveChanges" method="POST">
<table>
<tr>
<td><spring:message code="test.name" /></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><spring:message code="test.free" /></td>
<td><form:input path="free" /></td>
</tr>
<c:forEach items="${candidateTest.questions}" var="question"
varStatus="status">
<tr>
<td align="center">${status.count}</td>
<td><input name="questions[${status.index}].text"
value="${question.text}" /></td>
</tr>
<c:forEach items="${question.answers}" var="answer"
varStatus="interator">
<td align="center">${interator.count}</td>
<td><input name="answers[${interator.index}].answer"
value="${answer.answer}" /></td>
</c:forEach>
</c:forEach>
</table>
<br />
<input type="submit" value="Save" />
</form:form>
<div class="container">
<div class="btn-group">
<button type="button" class="btn btn-primary">
<spring:message code="choise" />
</button>
<button type="button" class="btn btn-primary dropdown-toggle"
data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a
href="<c:url value='/tests/choise/${ourTest.id}/${"app"}' />"><spring:message
code="aprove" /></a></li>
<li><a
href="<c:url value='/tests/choise/${ourTest.id}/${"pro"}' />"><spring:message
code="return" /></a></li>
<li><a
href="<c:url value='/tests/choise/${ourTest.id}/${"dis"}' />"><spring:message
code="refuse" /></a></li>
</ul>
</div>
</div>
</body>
</html>
When we start review one test we have specific link "http://localhost:8089/Diplom/tests/review/1", then when we push save-button we have this link "http://localhost:8089/tests/review/saveChanges" , "Diplom" it is our contextPath which lost. Of course we can change in jsp link like ${contextPath}/tests/review/saveChanges and I did it. And it didn't help.
========
UPD
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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<filter>
<filter-name>CharsetFilter</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>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
spring mvc config xml:
e<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<!--<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames"> <list> <value>classpath:validation</value> </list>
</property> </bean> -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/locales/messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>
<bean
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>
Though it was asked a long time ago...
Instead of
${contextPath}/tests/review/saveChanges
Try
${pageContext.request.contextPath}/tests/review/saveChanges
Let me know if it worked!
Related
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>
I've got a 403 ERROR when i'm trying to upload file in server! What the problem? Help me pls! Can't uderstand what a trouble. Thanx
This is my Controller
#Controller
#SessionAttributes("username")
public class UserPageController {
#Autowired
private UsersService usersService;
public String uploadFile(MultipartFile file)
{
String name="";
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
return "You successfully uploaded file=" + name;
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name
+ " because the file was empty.";
}
}
#RequestMapping(value="/user", method = RequestMethod.POST)
public #ResponseBody String postAvatar(#RequestParam("file") MultipartFile file)
{
uploadFile(file);
return"redirect:/user";
}
#RequestMapping(value="/user", method = RequestMethod.GET)
public String getUserInfo(Model model, Principal principal) {
String username=principal.getName();
model.addAttribute("users", new Users());
model.addAttribute("userInfo", this.usersService.userInfo(username));
return "user";
}
#RequestMapping(value="/user/search/{username}", method = RequestMethod.GET)
public String getAnotherUserInfo(#ModelAttribute("message") Message message, #PathVariable(value="username") String username, Model model, Principal principal) {
if(username.equals(principal.getName()))
{
model.addAttribute("users", new Users());
model.addAttribute("userInfo", this.usersService.userInfo(username));
return "redirect:/user";
}
else{
model.addAttribute("users", new Users());
model.addAttribute("userInfo", this.usersService.userInfo(username));
return "anotherUser";
}
}
And this is my .jsp page. My form is in the bottom of page
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://www.springframework.org/security/tags"
prefix="security"%>
<%#page language="java" session="true"%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
%>
<html>
<head>
<title>Профиль | Violence and Hate</title>
<link href="<c:url value="/resources/bootstrap/bootstrap.css"/>"
rel="stylesheet" type="text/css">
<link href="<c:url value="/resources/bootstrap/bootswatch.less.css"/>"
rel="stylesheet" type="text/css">
<link href="<c:url value="/resources/bootstrap/variables.less.css"/>"
rel="stylesheet" type="text/css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Violence and Hate</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>Профиль</li>
<li>Сообщения</li>
<li>Поиск оппонента</li>
<li class="dropdown">
Информация<span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Правила</li>
<li class="divider"></li>
<li>Написать администрации</li>
</ul>
</li>
<security:authorize ifAnyGranted="ROLE_ADMIN">
<li class="dropdown">
Администрирование<span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Админка/Список пользователей</li>
<li>Отзывы/Вопросы/Предложения</li>
</ul>
</li>
</security:authorize>
</ul>
<c:url var="logoutUrl" value="j_spring_security_logout" />
<form class="navbar-form navbar-right" action="${logoutUrl}" method="post">
<button class="btn btn-default" type="submit">Выйти</button>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
</div>
</div>
</nav>
<img class="img-responsive center-block" src="<c:url value="/resources/logo/logo.png"/>" />
<br>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading text-center">Личная информация</div>
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>Ник</th>
<th>Имя</th>
<th>Фамилия</th>
<th>E-mail</th>
<th>Пол</th>
<th>Вес(кг)</th>
<th>Рост(см)</th>
<th>Спортивные умения</th>
<th>Место</th>
</tr>
<tr>
<c:forEach items="${userInfo}" var="users">
<td>${users.username}</td>
<td>${users.name}</td>
<td>${users.surname}</td>
<td>${users.email}</td>
<td>${users.gender}</td>
<td>${users.weight}</td>
<td>${users.height}</td>
<td>${users.sport}</td>
<td>${users.place}</td>
</c:forEach>
</tr>
</table>
</div>
<form method="POST" action="user" enctype="multipart/form-data">
File to upload: <input type="file" name="file"><br />
<input type="submit" value="Аплоад"> Press here to upload the file!
</form>
<script src="<c:url value="/resources/Jquery/jquery-2.1.4.min.js"/>"
type="text/javascript"></script>
<script src="<c:url value="/resources/bootstrap/bootstrap.js"/>"
type="text/javascript"></script>
</body>
</html>
And here is my mvc-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
"
xmlns:tx="http://www.springframework.org/schema/tx">
<context:component-scan base-package="
com.vandh.app " />
<context:property-placeholder location="classpath:database.properties" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<!-- Mail Sending properties -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="violandhate#gmail.com" />
<property name="password" value="violenceandhate" />
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean
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>
Here i am using urlMap property of SimpleUrlHandlerMapping to map with controller but it does not map with Controller.Here I have put my code of dispatcher,Jsp and controller.
I have include following Jar Files--:
com.springsource.org.apache.commons.fileupload-1.2.0.jar
com.springsource.org.apache.commons.httpclient-3.1.0.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.log4j-1.2.15.jar
com.springsource.org.codehaus.jackson.mapper-1.0.0.jar
jmxtools-1.2.1.jar
jstl-1.2 (1).jar
org.springframework.asm-3.0.1.RELEASE-A.jar
org.springframework.beans-3.0.1.RELEASE-A.jar
org.springframework.context-3.0.1.RELEASE-A.jar
org.springframework.core-3.0.1.RELEASE-A.jar
org.springframework.expression-3.0.1.RELEASE-A.jar
org.springframework.oxm-3.0.1.RELEASE-A.jar
org.springframework.web-3.0.1.RELEASE-A.jar
org.springframework.web.portlet-3.0.1.RELEASE-A.jar
org.springframework.web.servlet-3.0.1.RELEASE-A.jar
org.springframework.web.struts-3.0.1.RELEASE-A.jar
spring-webmvc-3.0.5.RELEASE.jar
dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/JSPpages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/Registration.html">
<ref bean="RegistrationCon" />
</entry>
</map>
</property>
</bean>
<bean id="RegistrationCon" class="controllers.registrationController.RegistrationController">
<property name="commandName">
<value>RegistrationBean</value>
</property>
<property name="commandClass">
<value>formBeans.registrationBean.RegistrationBean</value>
</property>
<property name="sessionForm">
<value>false</value>
</property>
<property name="formView">
<value>Registration</value>
</property>
<property name="successView">
<value>RegistrationSuccess</value>
</property>
</bean>
</beans>
RegistrationController:
package controllers.registrationController;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import formBeans.registrationBean.RegistrationBean;
#SuppressWarnings("deprecation")
public class RegistrationController extends SimpleFormController {
protected ModelAndView onSubmit(HttpServletRequest req,HttpServletResponse res,Object command)throws ServletException //--OnSubmit Method Starts--//
{
System.out.println("In controller");
RegistrationBean regBean = (RegistrationBean) command;
String loginName=regBean.getLoginId();
System.out.println("Name---->"+loginName);
String pwd=req.getParameter("pwd");
System.out.println("PassWord---->"+pwd);
ArrayList<String> al=new ArrayList<String>();
al.add(loginName);
al.add(pwd);
ModelAndView mav=new ModelAndView("/RegistrationSuccess");
mav.addObject("ArrayList",al);
mav.addObject("regBean",regBean);
return mav;
}
}
Registration(JSP):
<%# taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head><title>User Personal Details</title>
<style>
table, th{
border: 1px solid black;
}
label{
font-family: "Trebuchet MS", Verdana, Halvetica, Arial;
font-size: 12px;
color: blue;
}
.textfield {
width: 250px;
border: 1px solid #AF9D72;
background-color: #F2ECD7;
}
</style></head>
<body bgcolor="#DDDDDD">
<h3>User Registration</h3>
<br/>
<form:form commandName="RegistrationBean" method="POST" name="RegistrationBean">
<div align="center" style="width:100%; height:100%">
<table style="height:250px; width:400px">
<tr>
<th>Heading</th>
<th>Input</th>
</tr>
<tr>
<td align="left"><label>Name:</label></td>
<td><form:input path="loginId" class="textfield"/></td>
</tr>
<tr>
<td align="left"><label>Password:</label></td>
<td><form:input path="pwd" class="textfield"/></td>
</tr>
<tr>
<td align="left"><label>Confirm Password:</label></td>
<td><form:input path="cpwd" class="textfield"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"/></td>
</tr>
</table>
</div>
</form:form>
</body>
</html>
try this:
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<props>
<prop key="/Registration.html">RegistrationCon</prop>
</props>
</property>
</bean>
if URL lookup should always use the full path within the current servlet context, you may need to set this:
<property name = "alwaysUseFullPath" value = "true" />
to urlMapping bean
Later edit:
Use this for urlMap, the above code was for mappings, sorry.
<property name="urlMap">
<map>
<entry key="/Registration.html" value-ref="RegistrationCon"/>
</map>
...
Issue Solved:
Jar Files That I have Used--:
aopalliance-1.0.jar
commons-logging-api-1.1.1.jar
jstl.jar
org.springframework.asm-3.0.4.RELEASE.jar
org.springframework.beans-3.0.4.RELEASE.jar
org.springframework.context-3.0.4.RELEASE.jar
org.springframework.context.support-3.0.4.RELEASE.jar
org.springframework.core-3.0.4.RELEASE.jar
org.springframework.expression-3.0.4.RELEASE.jar
org.springframework.web-3.0.4.RELEASE.jar
org.springframework.web.servlet-3.0.4.RELEASE.jar
standard.jar
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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>LogOutSystemChecking</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>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</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">
<!-- View Resolver Starts -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jspViews/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- View Resolver Starts -->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/UserRegistration.html">
<ref bean="RegCon" /> <!-- Controller-1 Mapping -->
</entry>
</map>
</property>
</bean>
<bean id="RegCon" class="controllers.registerController.RegistrationController"> <!-- Controller-1 Mapping -->
<property name="commandName">
<value>registration</value> <!--form:form commandName="registration" method="post" In UserRegistration.JSP-->
</property>
<property name="commandClass">
<value>formBeans.registerBean.RegistrationBean</value>
</property>
<property name="sessionForm">
<value>false</value>
</property>
<property name="formView">
<value>UserRegistration</value>
</property>
<property name="successView">
<value>UserRegistrationSuccess</value>
</property>
<property name="validator">
<bean class="validatorsPackage.registrationValidator.RegistrationValidations"/> <!-- Validate Page If user Does't enter Username,Password,CompanyAddress -->
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <!-- To show Message If error in a jsp page like Plz enter Username -->
<property name="basename" value="message" />
</bean>
</beans>
RegistrationBean.java--:
package formBeans.registerBean;
public class RegistrationBean {
//--global variable declaration Starts--//
private String name;
private String comAdd;
private String pwd;
private String cpwd;
private char gender;
private int empNumber;
//--global variable declaration Ends--//
//--Getter & Setter Starts--//
public String getComAdd() {
return comAdd;
}
public void setComAdd(String comAdd) {
this.comAdd = comAdd;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getCpwd() {
return cpwd;
}
public void setCpwd(String cpwd) {
this.cpwd = cpwd;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public int getEmpNumber() {
return empNumber;
}
public void setEmpNumber(int empNumber) {
this.empNumber = empNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
System.out.println("Name--:"+name);
}
//--Getter & Setter Ends--//
public RegistrationBean()
{
// TODO Auto-generated constructor stub
}
} //--Class Ends--//
RegistrationController.java--:
package controllers.registerController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import formBeans.registerBean.RegistrationBean;
public class RegistrationController extends SimpleFormController { //-- Class Starts--//
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception //--onSubmit() Method Starts--//
{
System.out.println("into the doSubmitAction() method.......");
RegistrationBean regBean = (RegistrationBean) command;
System.out.println("studentBea"+regBean.getName());
ModelAndView mv = new ModelAndView(this.getSuccessView());
mv.addObject("regBean", regBean);
return mv;
}//--onSubmit() Method Starts--//
public RegistrationController()
{
// TODO Auto-generated constructor stub
}
} //-- Class Ends --//
UserRegistration.jsp--:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1" isELIgnored="FALSE"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!-- error remove after add Standard.jar -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style>
table, th{
border: 1px solid black;
}
label{
font-family: "Trebuchet MS", Verdana, Halvetica, Arial;
font-size: 12px;
color: blue;
}
.textfield {
width: 250px;
border: 1px solid #AF9D72;
background-color: #F2ECD7;
}
.error {
color: #ff0000;
font-style: italic;
}
.errorblock{
color: #ff0000;
background-color: black;
width:400px;
text-align: center;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>SignUp</title>
</head>
<body bgcolor="#DDDDDD">
<form:form commandName="registration" method="post">
<div align="center" style="width:100%; height:100%"> <!-- Div tag ka data center me(meaning of aling) -->
<form:errors path="*" cssClass="errorblock" element="div"/>
<table style="height:250px; width:400px">
<tr>
<th>Heading</th>
<th>Input</th>
</tr>
<tr>
<td align="left"><label>Employee Name:</label></td>
<!--<td>Name:</td>-->
<td align="left"><form:input path="name" class="textfield"/></td> <!-- Insted of NAME Attribute we use PATH in Spring -->
<td><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td align="left"><label>Employee Number:</label></td>
<!--<td>Name:</td>-->
<td align="left"><form:input path="empNumber" class="textfield"/></td> <!-- Insted of NAME Attribute we use PATH in Spring -->
<td><form:errors path="empNumber" cssClass="error"/></td>
</tr>
<tr>
<td align="left"><label>Company Address:</label></td>
<!--<td>Name:</td>-->
<td align="left"><form:textarea path="comAdd" class="textfield"/></td> <!-- Insted of NAME Attribute we use PATH in Spring -->
<td><form:errors path="comAdd" cssClass="error"/></td>
</tr>
<tr>
<td align="left"><label>Gender:</label></td>
<td align="left">
<form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" />
</td>
<td><form:errors path="gender" cssClass="error"/></td>
</tr>
<tr>
<td align="left"><label>Password:</label></td>
<!--<td>Password:</td>-->
<td align="left"><form:password path="pwd" class="textfield"/></td>
<td><form:errors path="pwd" cssClass="error"/></td>
</tr>
<tr>
<td align="left"><label>Confirm Password:</label></td>
<!--<td>Password:</td>-->
<td align="left"><form:password path="cpwd" class="textfield"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Rigester/Save"/>
</td>
</tr>
</table>
</div>
</form:form>
</body>
</html>
I'm developing a Java application and I'm using Spring MVC. I'm a newbie and I'm trying to load some static content like css files and images in my home page. When I try to load some of these files I get a 405 error (GET method not allowed).
My project structure (for the web part) is
-WebContent
--MetaInf
--resources
--views
--WEB_INF
---web.xml
---springapp-dispatcher.xml
here's my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true">
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
my springapp-dispatcher.xml (without the initial part)
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**"
location="/resources/" />
<context:component-scan base-package="polibeacon.web"></context:component-scan>
<bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
I only have a controller, named HomeController.java
#Controller
public class HomeController {
#RequestMapping( value = "/", method = RequestMethod.GET )
public String index(Model model) {
model.addAttribute(new User());
return "index";
}
#RequestMapping(value="/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute(new User());
return "registration";
}
#RequestMapping(method=RequestMethod.POST)
public String registerUser(#Valid User user, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return "registration";
}
// save user
return "index";
}
}
and here's the index.jsp page
<!-- CSS -->
<link href="<c:url value="/resources/bootstrap/css/bootstrap.min.css" />" rel = "stylesheet">
<link href="<c:url value="/resources/css/style.css" />" rel = "stylesheet">
<!-- Scripts -->
</head>
<body>
<div class = "container">
<div class = "row">
<div class = "col-md-3"></div>
<div class = "col-md-6">
<div class = "jumbotron" style = "text-align: center;">
<img src = "images/logo.png" style = "display: block; margin-left: auto; margin-right: auto;">
<h2>Header</h2>
<form:form method="post" modelAttribute="user">
<form:input path="username" placeholder="Username"/>
<form:password path="password" placeholder="Password"/>
</form:form>
</div>
</div>
</div>
Sign Up
</div>
</body>
</html>
what's wrong?
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