i have downloaded template & add all of template file in "/WebContent" folder.but when template index.jsp file open it will show no css content/styling (i have change template index.html to index.jsp). & welcome page is template index.jsp
spring+hibenate.xml
<!-- Add AspectJ autoproxy support for AOP -->
<aop:aspectj-autoproxy/>
<!-- Add support for component scanning -->
<context:component-scan base-package="com.Restaurant" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- loading custome messages resource -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- where to find properties file -->
<property name="basenames" value="Resources/messages" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3300/restaurant?useSSL=false&serverTimezone=UTC" />
<property name="user" value="root" />
<property name="password" value="safwan" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" /> <!-- ref to DB in step 1 -->
<property name="packagesToScan" value="com.Restaurant.Entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
controller
package com.Restaurant.Controller;
import java.lang.ProcessBuilder.Redirect;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.Restaurant.Entity.Employee;
import com.Restaurant.Service.EmployeeService;
#Controller
#RequestMapping("/employee")
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
// for trimming white space
#InitBinder
public void initBinder(WebDataBinder binder) {
StringTrimmerEditor editor=new StringTrimmerEditor(true);
binder.registerCustomEditor(String.class, editor);
}
#GetMapping("/list")
public String listEmployee(Model model) {
List<Employee> employees = employeeService.getEmployees();
model.addAttribute("employees", employees);
return "list-employee";
}
#GetMapping("/addEmployee")
public String addEmployee(Model model) {
Employee employee=new Employee();
// empty object is passed for binding employee object to input field
model.addAttribute("employee", employee);
return "add-employee";
}
#PostMapping("/validateEmployee")
public String validateEmployee(#Valid #ModelAttribute Employee employee, BindingResult bindingResult) {
System.out.println(bindingResult);
if(bindingResult.hasErrors()) {
return "add-employee";
}else {
employeeService.saveOrEdit(employee);
return "redirect:/employee/list";
}
}
#GetMapping("/edit")
public String editEmployee(#RequestParam("employeeId") int empId, Model model ) {
Employee employee = employeeService.getEmployee(empId);
// to prefill input field, which is done automatically by 'modelAttribute' & <form: form> tag
model.addAttribute("employee", employee);
return "add-employee";
}
#GetMapping("/delete")
public String deleteEmployee(#RequestParam("employeeId") int empId, Model model) {
employeeService.deleteEmployee(empId);
return "redirect:list"; // "redirect:list" it is same as "redirect:/employee/list"
}
}
now i have used templates "index.jsp" as my welcome-page but when it will open it does not show any styling
index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<title>Feliciano - Free Bootstrap 4 Template by Colorlib</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/css?family=Poppins:100,200,300,400,500,600,700,800,900" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Great+Vibes&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/open-iconic-bootstrap.min.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/owl.carousel.min.css">
<link rel="stylesheet" href="css/owl.theme.default.min.css">
<link rel="stylesheet" href="css/magnific-popup.css">
<link rel="stylesheet" href="css/aos.css">
<link rel="stylesheet" href="css/ionicons.min.css">
<link rel="stylesheet" href="css/bootstrap-datepicker.css">
<link rel="stylesheet" href="css/jquery.timepicker.css">
<link rel="stylesheet" href="css/flaticon.css">
<link rel="stylesheet" href="css/icomoon.css">
<link rel="stylesheet" href="css/style.css">
</head>
/Restaurant/src/Resources/messages.properties
typeMismatch.employee.age= Invalid age
Related
i want send email with spring framework and thymeleaf .but when i run to the process, it doesn`t continue to run.
my Configuration:
<bean id="emailResolver"
class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
<property name="prefix" value="/template/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5"></property>
<property name="order" value="1"></property>
<property name="characterEncoding" value="UTF-8"></property>
<property name="cacheable" value="false"></property>
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolvers">
<set>
<ref bean="emailResolver" />
</set>
</property>
</bean>
java snippets:
#Autowired
SpringTemplateEngine templateEngine;
public void createThyTest()
{
Context con = new Context();
con.setVariable("name", "volcanno");
System.out.println(this.getClass().getClassLoader().getResource(""));
String string2 = templateEngine.process("Test.html", con);
System.out.println("-----");
System.out.println(string2);
}
when i run the codeļ¼there is no any "---" to be output.
output:
file:/D:/Neon_eclipse_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ProjectDemo/WEB-INF/classes/
No other error message is output.
and i use :
thymeleaf-spring3-3.0.9.RELEASE.jar
thymeleaf-3.0.9.RELEASE.jar
spring 3.1.2
thanks
my template:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="#{greeting(${name})}">
Hello, Peter Static!
</p>
</body>
</html>
Can anyone explain me how to use a session object in spring, for example a session has to be started when a user logged in and should be destroyed if the same user logs out.
Below is my code without sessions.
MainController:
#RequestMapping(value="/login", method=RequestMethod.GET)
public ModelAndView getLoginForm() {
ModelAndView loginView = new ModelAndView("login");
return loginView;
}
#RequestMapping(value="/check", method=RequestMethod.POST)
public ModelAndView processRequest(#RequestParam("email") String email, #RequestParam("password") String password, Student student) {
ModelAndView logsuccess = new ModelAndView("logsuccess");
ModelAndView loginView = new ModelAndView("login");
System.out.println("Entered email : " + email);
System.out.println("Entered password : " + password);
student.setEmail(email);
student.setPassword(password);
Student s = st.validatingStudent(student);
if(s==null) {
ModelAndView loginErrView = new ModelAndView("login","error","Username/password wrong");
return loginErrView;
} else {
return logsuccess;
}
}
Validating Method:
public Student validatingStudent(Student student) {
List validStdt = new ArrayList();
String sql = "select * from studentdb where email = '"+ student.getEmail()+"' and password = '"+ student.getPassword() +"'";
System.out.println("Entered Query: " + sql);
int i=jt.queryForInt("select count(*) from studentdb where email = '"+ student.getEmail()+"' and password = '"+ student.getPassword() +"'");
if(i!=0)
student = jt.queryForObject(sql, new ValidationRowMapper());
else
student=null;
return student;
}
I have seen #SessionAttributes annotation but some suggested that it is not the best solution to implement a Session.
You should use spring security to do all the login, here's a simple example, using a tymeleaf helloworld template.
<?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:context="http://www.springframework.org/schema/context" xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<security:http auto-config="true">
<security:intercept-url pattern="/keep-alive" access="permitAll" />
<security:intercept-url pattern="/*" access="hasRole('USER')" />
<security:form-login authentication-failure-url="/denied" />
<security:session-management>
<security:concurrency-control max-sessions="10" expired-url="/expired" error-if-maximum-exceeded="true" />
</security:session-management>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="greg" password="password" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
<context:component-scan base-package="net.isban" />
<context:property-placeholder location="classpath:application.properties" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>
</beans>
Tymeleaf template looks this this
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<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>Timeout POCC</title>
<link th:href="#{/resources/css/bootstrap.min.css}" rel="stylesheet" />
</head>
<body>
<div class="container">
<h2 th:text="${message}"></h2>
</div>
<!-- /container -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script th:src="#{/resources/js/bootstrap.min.js}"></script>
<script>
$('body').click(function() {
var request = $.ajax({
url : "keep-alive",
type : "GET"
});
});
</script>
</body>
</html>
Set the session timeout in your web.xml
<session-config>
<session-timeout>1</session-timeout>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
You'll need too implement your own [http://docs.spring.io/autorepo/docs/spring-security/4.1.0.RC1/apidocs/org/springframework/security/core/userdetails/UserDetailsService.html][UserDetailsService]
I integrate Spring 4 MVC and Thymeleaf. And i successfully get my active template based on my Controller.
But when i add request attribute to my View, my request attribute can't render the value.
I think it's automatically.
Here is my XML configuration file :
<context:component-scan base-package="com.fanjavaid" />
<mvc:annotation-driven />
<mvc:resources location="/resources/" mapping="/resources/**" />
<!-- THYMELEAF CONFIGURATION -->
<bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".html"></property>
<property name="templateMode" value="HTML5"></property>
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine"></property>
</bean>
Here is My Controller :
#Controller
public class JobseekerController {
#RequestMapping("/")
public String index(Model model) {
model.addAttribute("message", "Welcome to Spring 4 MVC");
return "index";
}
}
And here is my View :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Welcome Page</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
My View is HTML file.
fanjavaid,
I just think you need to add some code.
HTML
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TEST</title>
</head>
<body>
<h1 th:text="${message}">hi</h1>
</body>
</html>
You search thymeleaf tutorial
I cannot load the css files. Try almost all way to reach it. Could someone advice where should be the problem. Thanks in advance.
tiles-definitions where is defined tiles:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<definition name="defaultTemplate" template="/WEB-INF/template/default/template.jsp">
<put-attribute name="header" value="/WEB-INF/template/default/header.jsp" />
<put-attribute name="menu" value="/WEB-INF/template/default/menu.jsp" />
<put-attribute name="body" value="/WEB-INF/template/default/body.jsp" />
<put-attribute name="footer" value="/WEB-INF/template/default/footer.jsp" />
<put-attribute name="stylesheets" value="/src/main/resources/css/layout.css" />
</definition>
</tiles-definitions>
template.jsp is defalut template:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Default tiles template</title>
<c:forEach var="css" items="${stylesheets}">
<link rel="stylesheet" type="text/css" href="<c:url value="${css}"/>">
</c:forEach>
</head>
<body>
<div class="page">
<tiles:insertAttribute name="header" />
<div class="content">
<tiles:insertAttribute name="menu" />
<tiles:insertAttribute name="body" />
</div>
<tiles:insertAttribute name="footer" />
</div>
</body>
</html>
welcomepage.jsp using template.jsp:
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<tiles:importAttribute name="stylesheets"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Default tiles template</title>
<c:forEach var="css" items="${stylesheets}">
<link rel="stylesheet" type="text/css" href="<c:url value="${css}"/>">
</c:forEach>
</head>
<body>
<div class="page">
<tiles:insertAttribute name="header" />
<div class="content">
<tiles:insertAttribute name="menu" />
<tiles:insertAttribute name="body" />
</div>
<tiles:insertAttribute name="footer" />
</div>
</body>
</html>
dispatcher-sevrlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<tx:annotation-driven/>
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="intranetwebapp.*" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/intranetwebapp" />
<property name="username" value="root" />
<property name="password" value="gargamel" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="intranetwebapp.entity" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
<!-- Tiles configuration -->
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/tiles-definitions.xml</value>
</list>
</property>
</bean>
</beans>
can you try something like below,
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Default tiles template</title>
<link rel="stylesheet" href="<c:url value='/resources/css/layout.css'/>">
</head>
or you can set stylesheet variable to /resources/css/layout.css in spring model object and set the value in c:url to value='${stylesheet}' in jsp.
I'm working on integrating Tiles 2 with Spring, but have a problem. I have a simple tiles.jsp page. Rendering tiles view produce error: org.apache.tiles.template.NoSuchAttributeException: Attribute 'title' not found.My configuration and files below.
Tiles config:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:order="1">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver" p:order="0">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/defs/templates.xml</value>
</list>
</property>
</bean>
Definitions in /WEB-INF/defs/templates.xml:
<tiles-definitions>
<!-- Default Main Template -->
<definition name="base" template="/WEB-INF/pages/tiles.jsp">
<put-attribute name="title" value="Empty" type="string" />
<put-attribute name="header" value="/WEB-INF/tiles-templates/header.jsp" />
<put-attribute name="footer" value="/WEB-INF/tiles-templates/footer.jsp" />
<put-attribute name="body" value="/WEB-INF/tiles-templates/blank.jsp" />
</definition>
<definition name="tiles" extends="base">
<put-attribute name="title" value="Simple Tiles 2 Example"/>
</definition>
</tiles-definitions>
Controller:
#Controller
public class MainController {
#RequestMapping("/tiles")
public String tiles() {
return "tiles";
}
}
/WEB-INF/pages/tiles.jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<html>
<head>
<title><tiles:getAsString name="title" /></title>
<link rel="stylesheet" type="text/css" href="<c:url value="/css/main.css"/>" />
</head>
<body>
<div id="header">
<div id="headerTitle"><tiles:insertAttribute name="header" /></div>
</div>
<div id="content">
<tiles:insertAttribute name="body" />
</div>
<div id="footer">
<tiles:insertAttribute name="footer" />
</div>
</body>
</html>
Resolved! I've removed suffix and prefix properties from tilesViewResolver and everything began work.
<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver" p:order="0">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>