不用下载的行情网站,找事做搜索网站,一个外贸网站要多大的空间比较好,百度网站建设多少钱注意
如果静态资源放到了静态资源文件夹下却无法访问#xff0c;请检查一下是不是在自定义的配置类上加了EnableWebMvc注解templete文件夹不是静态资源的文件夹#xff0c;默认是无法访问的#xff0c;所以要添加视图映射
package cn.xxxxxx.hellospringbootweb.config;imp…注意
如果静态资源放到了静态资源文件夹下却无法访问请检查一下是不是在自定义的配置类上加了EnableWebMvc注解templete文件夹不是静态资源的文件夹默认是无法访问的所以要添加视图映射
package cn.xxxxxx.hellospringbootweb.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;Configuration
public class MyMvcConfig implements WebMvcConfigurer {Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController(/).setViewName(login);registry.addViewController(/index).setViewName(login);registry.addViewController(/index.html).setViewName(login);}
} i18n国际化 编写国际化配置文件抽取页面需要显示的国际化消息 创建i18n文件夹存放配置文件文件名格式为基础名(login)语言代码(zh)国家代码(CN) 在配置文件中添加国际化文件的位置和基础名如果配置文件中没有配置基础名就在类路径下找基础名为message的配置文件 spring.messages.basenamei18n.login 点击切换语言 修改页面点击连接携带语言参数a classbtn btn-sm href?lzh_CN中文/a
a classbtn btn-sm href?len_USEnglish/a
实现登陆功能
1提供登陆的Controller
Controller
public class UserController {PostMapping(/user/login)public String login(RequestParam String username, RequestParam String password, HttpSession session, Model model) {if (!StringUtils.isEmpty(username) 123456.equals(password)) {//登录成功把用户信息方法哦session中防止表单重复提交重定向到后台页面session.setAttribute(loginUser, username);return redirect:/main.html;}//登录失败,返回到登录页面model.addAttribute(msg, 用户名或密码错误);return login;}
}2修改表单的提交地址输入框添加name值与参数名称相对应 form classform-signin actiondashboard.html th:action{/user/login} methodpostimg classmb-4 srcasserts/img/bootstrap-solid.svg alt width72 height72h1 classh3 mb-3 font-weight-normal th:text#{login.tip}Please sign in/h1label classsr-onlyUsername/labelinput typetext nameusername classform-control th:placeholder#{login.username} placeholderUsername autofocuslabel classsr-onlyPassword/labelinput typepassword namepassword classform-control th:placeholder#{login.password} placeholderPassword requireddiv classcheckbox mb-3labelinput typecheckbox valueremember-me [[#{login.remember}]]/label/divbutton classbtn btn-lg btn-primary btn-block typesubmit th:text#{login.btn}Sign in/buttonp classmt-5 mb-3 text-muted© 2017-2018/pa classbtn btn-sm href?lzh_CN中文/aa classbtn btn-sm href?len_USEnglish/a/form3由于登陆失败是转发所以得修改静态资源的请求路径在其中添加模版引擎
link hrefasserts/css/bootstrap.min.css th:href{/asserts/css/bootstrap.min.css} relstylesheet
!-- Custom styles for this template --
link hrefasserts/css/signin.css th:href{/asserts/css/signin.css} relstylesheet
4添加登陆页面的显示将msg传回主页面
h1 classh3 mb-3 font-weight-normal th:text#{login.tip}Please sign in/h1
!--msg存在才显示该p标签--
p th:text${msg} th:if${not #strings.isEmpty(msg)} stylecolor: red/p
修改页面使其立即生效
在配置文件里面添加如下的命令在页面修改完成之后按快捷键ctrlf9重新编译
# 禁用缓存
spring.thymeleaf.cachefalse
拦截器进行登陆检查
1实现拦截器
package cn.xxxxxx.hellospringbootweb.interceptor;import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class LoginHandlerInterceptor implements HandlerInterceptor {Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Object loginUser request.getSession().getAttribute(loginUser);if (loginUser null) {//未登录拦截并转发到登录页面request.setAttribute(msg, 您还没有登录请先登录);request.getRequestDispatcher(/index).forward(request, response);return false;}return true;}Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
}
2注册拦截器
package cn.clboy.hellospringbootweb.config;import cn.clboy.hellospringbootweb.interceptor.LoginHandlerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;Configuration
public class MyMvcConfig implements WebMvcConfigurer {//定义不拦截路径private static final String[] excludePaths {/, /index, /index.html, /user/login, /asserts/**};Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController(/).setViewName(login);registry.addViewController(/index).setViewName(login);registry.addViewController(/index.html).setViewName(login);registry.addViewController(/main.html).setViewName(dashboard);}Beanpublic LocaleResolver localeResolver() {return new MyLocaleResolver();}Overridepublic void addInterceptors(InterceptorRegistry registry) {//添加不拦截的路径SpringBoot已经做好了静态资源映射所以我们不用管registry.addInterceptor(new LoginHandlerInterceptor()).excludePathPatterns(excludePaths);}
}
注意在spring2.0的版本中只要用户自定义了拦截器则静态资源会被拦截。但是在spring1.0的版本中是不会拦截静态资源的。因此我们需要将静态资源排除到拦截器的拦截路径之外
案例实现员工的增删改查
实验功能请求URI请求方式查询所有员工empsGET查询某个员工(来到修改页面)emp/1GET来到添加页面empGET添加员工empPOST来到修改页面查出员工进行信息回显emp/1GET修改员工empPUT删除员工emp/1DELETE为了页面结构清晰在template文件夹下新建emp文件夹将list.html移动到emp文件夹下 将dao层和实体层java代码复制到项目中daoentities 添加员工controller实现查询员工列表的方法 Controller
public class EmpController {Autowiredprivate EmployeeDao employeeDao;GetMapping(/emps)public String emps(Model model) {CollectionEmployee empList employeeDao.getAll();model.addAttribute(emps, empList);return emp/list;}} 修改后台页面更改左侧的侧边栏并修改请求路径 li classnav-itema classnav-link th:href{/emps}svg .........../svg员工列表/a
/li
thymeleaf公共页面元素抽取参考官方文档
~{templatename::selector}模板名::选择器~{templatename::fragmentname}:模板名::片段名
/*公共代码片段*/
footer th:fragmentcopycopy; 2011 The Good Thymes Virtual Grocery
/footer/*引用代码片段*/
div th:insert~{footer :: copy}/di/*〜{...}包围是完全可选的所以上⾯的代码 将等价于*/
div th:insertfooter :: copy/di
三种引入公共片段的th属性
th:insert将公共片段整个插入到声明引入的元素中th:replace将声明引入的元素替换为公共片段th:include将被引入的片段的内容包含进这个标签中
后台页面的抽取
1将后台主页中的顶部导航栏作为片段在list中引入 nav th:fragmenttopbar classnavbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0a classnavbar-brand col-sm-3 col-md-2 mr-0 hrefhttp://getbootstrap.com/docs/4.0/examples/dashboard/#Company name/ainput classform-control form-control-dark w-100 typetext placeholderSearch aria-labelSearchul classnavbar-nav px-3li classnav-item text-nowrapa classnav-link hrefhttp://getbootstrap.com/docs/4.0/examples/dashboard/#Sign out/a/li/ul/nav
2list.html
bodydiv th:replacedashboard::topbar/div......
3使用选择器的方式抽取左侧边栏的代码就是我们将不同html文件的公共部分抽取出来作为一个模版其余需要的html文件只需要引入即可使用。比如现在我们将名称为sidebar的模版放在dashboard.html里面而在list.html里面进行复用。
!--dashboard.html--
div classcontainer-fluiddiv classrownav idsidebar classcol-md-2 d-none d-md-block bg-light sidebar ......
!--list.html--
div classcontainer-fluiddiv classrowdiv th:replacedashboard::#sidebar/div......
4显示员工数据添加增删改按钮 main rolemain classcol-md-9 ml-sm-auto col-lg-10 pt-3 px-4h2button classbtn btn-sm btn-success添加员工/button/h2div classtable-responsivetable classtable table-striped table-smtheadtrth员工号/thth姓名/thth邮箱/thth性别/thth部门/thth生日/thth操作/th/tr/theadtbodytr th:eachemp:${emps}td th:text${emp.id}/tdtd th:text${emp.lastName}/tdtd th:text${emp.email}/tdtd th:text${emp.gender}1?男:女/tdtd th:text${emp.department.departmentName}/tdtd th:text${#dates.format(emp.birth,yyyy-MM-dd)}/tdtdbutton classbtn btn-sm btn-primary修改/buttonbutton classbtn btn-sm btn-danger删除/button/td/tr/tbody/table/div/main
5员工添加页面 add.html
......
body
div th:replacecommons/topbar::topbar/divdiv classcontainer-fluiddiv classrowdiv th:replacecommons/sidebar::#sidebar(currentURIemps)/divmain rolemain classcol-md-9 ml-sm-auto col-lg-10 pt-3 px-4formdiv classform-grouplabelLastName/labelinput namelastName typetext classform-control placeholderzhangsan/divdiv classform-grouplabelEmail/labelinput nameemail typeemail classform-control placeholderzhangsanatguigu.com/divdiv classform-grouplabelGender/labelbr/div classform-check form-check-inlineinput classform-check-input typeradio namegender value1label classform-check-label男/label/divdiv classform-check form-check-inlineinput classform-check-input typeradio namegender value0label classform-check-label女/label/div/divdiv classform-grouplabeldepartment/labelselect namedepartment.id classform-controloption th:eachdept:${departments} th:text${dept.departmentName} th:value${dept.id}/option/select/divdiv classform-grouplabelBirth/labelinput namebirth typetext classform-control placeholderzhangsan/divbutton typesubmit classbtn btn-primary添加/button/form/main/div
/div
......
6点击链接跳转到添加页面
a href/emp th:href{/emp} classbtn btn-sm btn-success添加员工/a
7EmpController添加映射方法 Autowiredprivate DepartmentDao departmentDao;GetMapping(/emp)public String toAddPage(Model model) {//准备部门下拉框数据CollectionDepartment departments departmentDao.getDepartments();model.addAttribute(departments,departments);return emp/add;}
8 修改页面遍历添加下拉选项
select classform-controloption th:eachdept:${departments} th:text${dept.departmentName}/option
/select
9表单提交添加员工
form th:action{/emp} methodpost PostMapping(/emp)public String add(Employee employee) {System.out.println(employee);//模拟添加到数据库employeeDao.save(employee);//添加成功重定向到列表页面return redirect:/emps;}
10日期格式的修改
表单提交的格式必须是yyyy/MM/dd的格式可以在配置文件中修改格式
spring.mvc.date-formatyyyy-MM-dd
员工修改
点击按钮跳转到编辑页面 a th:href{/emp/}${emp.id} classbtn btn-sm btn-primary修改/a 添加编辑页面将表单的提交方式设置为post方式提供_method参数 body
div th:replacecommons/topbar::topbar/divdiv classcontainer-fluiddiv classrowdiv th:replacecommons/sidebar::#sidebar(currentURIemps)/divmain rolemain classcol-md-9 ml-sm-auto col-lg-10 pt-3 px-4form th:action{/emp} methodpost!--员工id--input typehidden nameid th:value${emp.id}!--http请求方式--input typehidden name_method valueputdiv classform-grouplabelLastName/labelinput namelastName th:value${emp.lastName} typetext classform-control placeholderzhangsan/divdiv classform-grouplabelEmail/labelinput nameemail th:value${emp.email} typeemail classform-control placeholderzhangsanatguigu.com/divdiv classform-grouplabelGender/labelbr/div classform-check form-check-inlineinput classform-check-input typeradio namegender value1 th:checked${emp.gender1}label classform-check-label男/label/divdiv classform-check form-check-inlineinput classform-check-input typeradio namegender value0 th:checked${emp.gender0}label classform-check-label女/label/div/divdiv classform-grouplabeldepartment/labelselect namedepartment.id classform-controloption th:eachdept:${departments} th:value${dept.id} th:selected${dept.id}${emp.department.id} th:text${dept.departmentName}/option/select/divdiv classform-grouplabelBirth/labelinput namebirth typetext classform-control placeholderzhangsan th:value${#dates.format(emp.birth,yyyy-MM-dd)}/divbutton typesubmit classbtn btn-primary添加/button/form/main/div
/div...... controller转发到编辑页面回显员工信息 GetMapping(/emp/{id})public String toEditPage(PathVariable Integer id, Model model) {Employee employee employeeDao.get(id);//准备部门下拉框数据CollectionDepartment departments departmentDao.getDepartments();model.addAttribute(emp, employee).addAttribute(departments, departments);return emp/edit;} 提交表单修改员工的信息 PutMapping(/emp)public String update(Employee employee) {employeeDao.save(employee);return redirect:/emps;}
员工删除
点击删除提交发出delete请求 DeleteMapping(/emp/{id})public String delete(PathVariable String id){employeeDao.delete(id);return redirect:/emps;} 如果提示不支持POST请求在确保代码无误的情况下查看是否配置启动HiddenHttpMethodFilter 这个好像是2.0版本以后修改的
spring.mvc.hiddenmethod.filter.enabledtrue 如果删除不掉请修改EmployeeDao把String转为Integer类型 public void delete(String id) {employees.remove(Integer.parseInt(id));}