I am starting to use dropzone.js and I wanted to uploaded a file and unfortunately this job doesn't work. I mention that I've been inspired from a working project.
So this is my controller class:
#Controller
public class FileUploadController {
private FileUploadService uploadService = (FileUploadService) SpringContext.CONTEXT
.getContext().getBean(FileUploadService.class);
#RequestMapping(value = { "/file" })
public String home() {
return "fileUploader";
}
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public #ResponseBody List<UploadedFile> upload(
MultipartHttpServletRequest request, HttpServletResponse response)
throws IOException {
System.out.println("Enter in upload.....");
// Getting uploaded files from the request object
Map<String, MultipartFile> fileMap = request.getFileMap();
// Maintain a list to send back the files info. to the client side
List<UploadedFile> uploadedFiles = new ArrayList<UploadedFile>();
// Iterate through the map
for (MultipartFile multipartFile : fileMap.values()) {
// Save the file to local disk
saveFileToLocalDisk(multipartFile);
UploadedFile fileInfo = getUploadedFileInfo(multipartFile);
// Save the file info to database
fileInfo = saveFileToDatabase(fileInfo);
// adding the file info to the list
uploadedFiles.add(fileInfo);
}
return uploadedFiles;
}
#RequestMapping(value = { "/list" })
public String listBooks(Map<String, Object> map) {
map.put("fileList", uploadService.listFiles());
return "/listFiles";
}
#RequestMapping(value = "/get/{fileId}", method = RequestMethod.GET)
public void getFile(HttpServletResponse response, #PathVariable int fileId) {
UploadedFile dataFile = uploadService.getFile(fileId);
File file = new File(dataFile.getLocation(), dataFile.getName());
try {
response.setContentType(dataFile.getType());
response.setHeader("Content-disposition", "attachment; filename=\""
+ dataFile.getName() + "\"");
FileCopyUtils.copy(FileUtils.readFileToByteArray(file),
response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveFileToLocalDisk(MultipartFile multipartFile)
throws IOException, FileNotFoundException {
String outputFileName = getOutputFilename(multipartFile);
FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(
outputFileName));
}
private UploadedFile saveFileToDatabase(UploadedFile uploadedFile) {
return uploadService.saveFile(uploadedFile);
}
private String getOutputFilename(MultipartFile multipartFile) {
return getDestinationLocation() + multipartFile.getOriginalFilename();
}
private UploadedFile getUploadedFileInfo(MultipartFile multipartFile)
throws IOException {
UploadedFile fileInfo = new UploadedFile();
fileInfo.setName(multipartFile.getOriginalFilename());
fileInfo.setSize(multipartFile.getSize());
fileInfo.setType(multipartFile.getContentType());
fileInfo.setLocation(getDestinationLocation());
fileInfo.setActuality("previous");
return fileInfo;
}
private String getDestinationLocation() {
return "D:/uploaded-files/";
}
}`
In upload method I put a message (System.out.println("Enter in upload.....")) to check if entered in this method but don't enters.
The 'fileUploader' jsp is:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" name="viewport"
content="width=device-width, initial-scale=1">
<title>Spring MVC + Dropzone.js Example</title>
<link rel="stylesheet" type="text/css"
href='<c:url value="/web-resources/libs/bootstrap-3.1.1/css/bootstrap.min.css"/>'>
<link rel="stylesheet" type="text/css"
href='<c:url value="/web-resources/libs/bootstrap-dialog/css/bootstrap-dialog.min.css"/>'>
<link rel="stylesheet" type="text/css"
href='<c:url value="/web-resources/css/style.css"/>'>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading text-center">
<h3>Spring MVC + Dropzone.js Example</h3>
</div>
<div class="panel-body">
<div>
<form id="dropzone-form" class="dropzone"
enctype="multipart/form-data">
<div
class="dz-default dz-message file-dropzone text-center well col-sm-12">
<span class="glyphicon glyphicon-paperclip"></span> <span>
To attach files, drag and drop here</span><br> <span>OR</span><br>
<span>Just Click</span>
</div>
<!-- this is were the previews should be shown. -->
<div class="dropzone-previews"></div>
</form>
<hr>
<button id="upload-button" class="btn btn-primary">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
<a class="btn btn-primary pull-right" href="list">
<span class="glyphicon glyphicon-eye-open"></span> View All Uploads
</a>
</div>
</div>
</div>
</div>
<script type="text/javascript"
src='<c:url value="/web-resources/libs/jquery/jquery-2.1.1.js"/>'></script>
<script type="text/javascript"
src='<c:url value="/web-resources/libs/bootstrap-3.1.1/js/bootstrap.js"/>'></script>
<script type="text/javascript"
src='<c:url value="/web-resources/libs/bootstrap-dialog/js/bootstrap-dialog.min.js"/>'></script>
<script type="text/javascript"
src='<c:url value="/web-resources/libs/dropzone.js"/>'></script>
<script type="text/javascript"
src='<c:url value="/web-resources/js/app.js"/>'></script>
</body>
</html>`
Now the problem is an error that appears when I press the 'upload' button after I selected a file.The error is :
<html><head><title>Apache Tomcat/7.0.57 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 405 - Request method 'POST' not supported</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>Request method 'POST' not supported</u></p><p><b>description</b> <u>The specified HTTP method is not allowed for the requested resource.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.57</h3></body></html>
Above error appears in browser, in console doesn't appear anything.
My servlet cod is the following:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Handles HTTP GET requests for /web-resources/** by efficiently serving
up static resources in the ${webappRoot}/resources/ directory -->
<!-- Defines a resolver implementation bean. It gets applied to all requests
handled by that DispatcherServlet -->
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<beans:bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<beans:property name="useTrailingSlashMatch" value="true" />
</beans:bean>
<resources mapping="/web-resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.license.web.*" />
</beans:beans>
Thanks a lot in advance!
Related
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.
I'm working on a simple java web app that displays a page in which you can add a new client and then it shows another pages that presents the client newly added but i keep getting this error:
HTTP Status 404 - /LearningJSP/AddClient
type Status report
message /LearningJSP/AddClient
description The requested resource is not available.
I don't get where the problem is.
Here are the files of my app.
the "add new client" .jsp
<%# page pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Création d'un client</title>
</head>
<body>
<div>
<form method="get" action="AddClient">
<fieldset>
<legend>Informations client</legend>
<label for="nomClient">Nom <span class="requis">*</span></label>
<input type="text" id="nomClient" name="nomClient" value="" size="20" maxlength="20" />
<br />
<label for="prenomClient">Prénom </label>
<input type="text" id="prenomClient" name="prenomClient" value="" size="20" maxlength="20" />
<br />
<label for="adresseClient">Adresse de livraison <span class="requis">*</span></label>
<input type="text" id="adresseClient" name="adresseClient" value="" size="20" maxlength="20" />
<br />
<label for="telephoneClient">Numéro de téléphone <span class="requis">*</span></label>
<input type="text" id="telephoneClient" name="telephoneClient" value="" size="20" maxlength="20" />
<br />
<label for="emailClient">Adresse email</label>
<input type="email" id="emailClient" name="emailClient" value="" size="20" maxlength="60" />
<br />
</fieldset>
<input type="submit" value="Valider" />
<input type="reset" value="Remettre à zéro" /> <br />
</form>
</div>
</body>
</html>
Servlet
package Controllers;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Client;
/**
* Servlet implementation class ClientServ
*/
public class ClientServ extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String Add = "/affichierClient.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String Nom = request.getParameter("nomClient");
String Prenom = request.getParameter("prenomClient");
String Adresse = request.getParameter("adresseClient");
String Telephone = request.getParameter("telephoneClient");
String Email = request.getParameter("emailClient");
String message;
if(Nom.trim().isEmpty() || Adresse.trim().isEmpty() ||
Telephone.trim().isEmpty()) {
message="Vous n'avez pas rempli tous les champs";
}
else {
message="Client crée avec succès";
}
Client client = new Client();
client.setNom(Nom);
client.setPrenom(Prenom);
client.setAdresse(Adresse);
client.setEmail(Email);
client.setTelephone(Telephone);
request.setAttribute("client", client);
request.setAttribute("message", message);
this.getServletContext().getRequestDispatcher(Add).forward(request, response);
}
}
The jsp page to display the newly added client
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="UTF-8"%>
<!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>Affichage de client</title>
</head>
<body>
<p class="info"> ${message} </p>
<p>Nom: ${client.Nom}</p>
<p>Prenom: ${client.Prenom}</p>
<p>Adresse: ${client.Adresse}</p>
<p>Numéro de télephone: ${client.Telephone}</p>
<p>Email: ${client.Email}</p>
</body>
</html>
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
<display-name>WebApp</display-name>
<servlet>
<servlet-name>AddClient</servlet-name>
<servlet-class>Controllers.ClientServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddClient</servlet-name>
<url-pattern>/AddClient</url-pattern>
</servlet-mapping>
</web-app>
It is likely that the problem comes from that line:
<form method="get" action="AddClient">
As you give a relative URL instead of an absolute one, it is used to build a full URL starting from the current one.
So if the previous URL was /LearningJSP the following request is sent to /LearningJSP/AddClient when it should use /AddClient ending in a normal 404 error.
Fix: just use an absolute URL:
<form method="get" action="/AddClient">
Read about how to create breakpoints in eclipse.
Place a breakpoint here
String Nom = request.getParameter("nomClient");
Read about how to start a debugging session in eclipse.
Start one. If The execution never stops at the breakpoint means the configuration is wrong. If it does stop, means that the 404 is thrown in a subsequent request.
If you only have doGet(...) handling requests then you probably have url path issues
Excaption i am getting
HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
I am trying to implement spring security via custom login page
spring-security.xml
<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-4.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<!-- <http>
<intercept-url pattern ="/welcome*" access="hasRole('ROLE_USER')"/>
<http-basic/>
</http> -->
<!-- <http>
<intercept-url pattern ="/welcome*" access="hasRole('ROLE_USER')"/>
<form-login/>
<logout logout-success-url="/home"/>
</http> -->
<http>
<intercept-url pattern ="/welcome*" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/loginfailed"/>
<logout logout-success-url="/logout"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="rahul" password="123" authorities="ROLE_USER"/>
<user name="rohit" password="567" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
login.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
<!-- <style>
.errorblock
{
color : #f0000;
background-color : #ffEEEE;
border : 3px solid #ff0000;
padding : 8px;
margin : 16px;
}
</style> -->
</head>
<body onload='document.f.j_username.focus();' bgcolor="blue">
<h3>Login with Username andPassword (Custom page)</h3>
<%-- <c:if test="$SPRING_SECURITY_LAST_EXCEPTION !=null"}">
<div class="errorblock">
Your login atempt are not sucessfull,try again
<br/>Caused : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message }
</div>
</c:if> --%>
<%-- <form name='f' action="<c:url value='j_spring_security_logout'/>" method="POST">
--%>
<form name='f' action='/SpringSecurityApplication/login' method="POST">
<table>
<tr>
<td>User :</td><td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password :</td><td><input type='password' name='password'></td>
</tr>
<tr><td colspan ='2'><input name="submit" type="submit" value="submit" ></td></tr>
<tr><td colspan ='2'><input name="reset" type="reset" ></td></tr>
</table>
</form>
</body>
</html>
LoginController.java
package com.springtraining.security.controller;
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class LoginController {
public LoginController() {
System.out.println("LoginController constructor is called ");
}
#RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String printWelcome(ModelMap model, Principal principal) {
System.out.println("**********Login Controller is Called********");
String name = principal.getName();
model.addAttribute("username", name);
model.addAttribute("message", "Spring Security Custom Form Example");
return "hello";
}
#RequestMapping(value = "/*", method = RequestMethod.GET)
public String home(ModelMap model) {
return "home";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(ModelMap model) {
return "login";
}
#RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(ModelMap model) {
return "login";
}
#RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
public String loginError(ModelMap model) {
model.addAttribute("error","true");
return "login";
}
}
hello.jsp
home.jsp
I think not required
You need to submit the crsf token while login (and logout and every other
POST, PUT, DELETE request).
There are serveral ways to add this to your jsp:
use spring's jsp <form:form> tag (instead the standart form tag) or
you need to add the crsf token explicit, either by spring security tag <sec:csrfInput /> or:
by "standart jsp":
"standart jsp" example:
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
#see: Spring Security Reference Chapter 18.4.3 Include the CSRF Token
BTW: I strongly recommend to read the complete Chapter 18. Cross Site Request Forgery (CSRF)
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'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?