addViewController请求

attention:

想要把网站的图标换掉就在static下放一个 favicon.ico 的图标图片即可

Spring MVC 5.0.5官方文档

static和template

springboot整合了springmvc的拦截功能。拦截了所有的请求。默认放行的资源是:resources/static/ 目录下所有静态资源。(不走controller控制器就能直接访问到资源)。

html页面如果放在resources/templates目录下,则需要走controller控制器,controller放行,允许该资源访问,该资源才能被访问到。否则就会报404错误(它不可以直接被访问)。

因此默认时访问public目录下的index.html

通过配置类来extends WebMvcConfigurationSupport实现访问template目录下的login.html下

(当然通过controller来访问也是可以的,但是Spring Boot推荐采用配置类来实现)

重点提醒一下,一定要实现WebMvcConfigurer接口来访问,不要继承Support类

package com.example.webexpriment.config;import com.example.webexpriment.component.MyLocaleResolver;
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.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class MyMvcConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {//浏览器发送/gary请求,来到/success页面registry.addViewController("/").setViewName("login");System.out.println("WOC");registry.addViewController("/index.html").setViewName("login");}@Beanpublic LocaleResolver localeResolver(){return new MyLocaleResolver();}}

搞定玩就可以访问主页了

附上Controller的访问方法

   @RequestMapping({"/","/index.html"})//数组public String index(){return "login";}

实现国际化功能(中英文)

1.编写properties的国际化文件

在html先里面修改 记得先导入模板引擎的提示功能xmlns:th=“http://www.thymeleaf.org”

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-u2Ay0y1I-1592971582236)(C:\Users\Gary\AppData\Roaming\Typora\typora-user-images\image-20200623112714362.png)]

applicaltion.properties文件下加上


spring.messages.basename=i18n.login

2.导入thymeleaf模板引擎在html获取值

html标签

?l=zh_CN在thymeleaf中的写法:

The th:href attribute allows us to (optionally) have a working static href attribute in our template, so that our template links remained navigable by a browser when opened directly for prototyping purposes. (摘自官方文档)

<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm"th:href="@{/index.html(l='en_US')}">English</a>

thymeleaf模板引擎来取国际化的值

参见thymeleaf官方文档

Variable Expressions: ${...}
Selection Variable Expressions: *{...}
Message Expressions: #{...}
Link URL Expressions: @{...}
Fragment Expressions: ~{...}

修改example:

<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>

行内写法

     <label><input type="checkbox" value="remember-me" > [[#{login.remember}]]</label>

提醒一下,记得设置IDE把编码自动转化为ASCII码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="description" content=""><meta name="author" content=""><title>Signin Template for Bootstrap</title><!-- Bootstrap core CSS --><link href="asserts/css/bootstrap.min.css" rel="stylesheet"><!-- Custom styles for this template --><link href="asserts/css/signin.css" rel="stylesheet"></head><body class="text-center"><form class="form-signin" th:action="@{/user/login}" action="dashboard.html"><img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72"><h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1><label class="sr-only" th:text="#{login.username}">Username</label><input type="text" name="username" class="form-control" th:placeholder="#{login.username}" placeholder="Username" required="" autofocus=""><label class="sr-only"  th:text="#{login.password}">Password</label><input type="password" name="password" class="form-control" th:placeholder="#{login.password}" placeholder="Password" required=""><div class="checkbox mb-3"><label><input type="checkbox" value="remember-me" > [[#{login.remember}]]</label></div><button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button><p class="mt-5 mb-3 text-muted">© 2017-2018</p><a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a><a class="btn btn-sm"th:href="@{/index.html(l='en_US')}">English</a></form></body>
</html>

3.区域信息解析器,在链接上携带区域信息(Important)

需要自己写

package com.example.webexpriment.component;import org.apache.tomcat.jni.Local;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;/*** 可以在链接上携带区域信息*/
public class MyLocaleResolver implements LocaleResolver {@Overridepublic Locale resolveLocale(HttpServletRequest httpServletRequest) {String l = httpServletRequest.getParameter("l");System.out.println(l);//区域信息Locale locale= Locale.getDefault();//用StringUtils工具判断一下先if(!StringUtils.isEmpty(l)){String[] s = l.split("_");locale = new Locale(s[0], s[1]);}System.out.println(locale);return locale;}@Overridepublic void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {}
}

StringUtils

然后再配置类当中加入到容器当中 @Bean

package com.example.webexpriment.config;import com.example.webexpriment.component.MyLocaleResolver;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.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class MyMvcConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {//浏览器发送/gary请求,来到/success页面registry.addViewController("/").setViewName("login");System.out.println("WOC");registry.addViewController("/index.html").setViewName("login");}@Beanpublic LocaleResolver localeResolver(){return new MyLocaleResolver();}}

4.展示

系统默认:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-neI2zIcq-1592971582238)(C:\Users\Gary\AppData\Roaming\Typora\typora-user-images\image-20200623120325447.png)]

中文:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yFqi2MkG-1592971582239)(C:\Users\Gary\AppData\Roaming\Typora\typora-user-images\image-20200623120649430.png)]

English:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rV2CGQyR-1592971582241)(C:\Users\Gary\AppData\Roaming\Typora\typora-user-images\image-20200623120706716.png)]

登录访问dashboard.html

attention:

Map<String,Object>使用Object主要是为了方便赋值,无需强制类型转化。

修改访问的方式

<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">

先写LoginController 来处理访问请求(再访问页面我们就不搞配置类了)

!!!修改html,input上面加上name属性

<input type="text" name="username" class="form-control" th:placeholder="#{login.username}" placeholder="Username" required="" autofocus=""><input type="password" name="password" class="form-control" th:placeholder="#{login.password}" placeholder="Password" required="">

不加的话是编译器获取不到值

然后处理请求

package com.example.webexpriment.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;import java.util.Map;@Controller
public class LoginController {@PostMapping(value="/user/login")
//    @RequestMapping(value="/user/login",method = RequestMethod.POST) 用上面更加方便//从请求参数上获取用户名和密码public String login(@RequestParam("username") String username,@RequestParam("password")String password,Map<String,Object>map){if(!StringUtils.isEmpty(username)&&"123456".equals(password)){//登陆成功return "dashboard";}else{//登录失败map.put("msg","用户名密码错误");return "login.html";}}
}

禁用模板引擎缓存并且刷新

attention

[1.$符号取上下文中的变量:

2.#](https://s.weibo.com/weibo?q=%23、*+和%24的区别: 1.%24符号取上下文中的变量: 符号取thymeleaf工具中的方法、文字消息表达式:

Welcome to our grocery store!

3. *{…}选择表达式一般跟在th:object后,直接选择object中的属性

操作

applicaltion.properties下加上

#禁用模板引擎的缓存
spring.thymeleaf.cache=false

再ctrl+F9来刷新

加上错误消息

p标签和if条件

参见官网文档

<!--  做一个判断,见官方文档,#strings为工具引用--><p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

编写拦截器

1.重定向

防止表单的重复提交

package com.example.webexpriment.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;import java.util.Map;@Controller
public class LoginController {//    @RequestMapping(value="/user/login",method = RequestMethod.POST) 用上面更加方便//从请求参数上获取用户名和密码
@PostMapping(value="/user/login")public String login(@RequestParam("username") String username,@RequestParam("password")String password,Map<String,Object>map){if(!StringUtils.isEmpty(username)&&"123456".equals(password)){//登陆成功System.out.println("登录页面成功");//重定向,防止表单重复提交return "redirect:/main.html";}else{//登录失败map.put("msg","用户名密码错误");return "login";}}
}
package com.example.webexpriment.config;import com.example.webexpriment.component.MyLocaleResolver;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.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class MyMvcConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {//浏览器发送/gary请求,来到/success页面registry.addViewController("/").setViewName("login");registry.addViewController("/index.html").setViewName("login");registry.addViewController("/main.html").setViewName("dashboard");}@Beanpublic LocaleResolver localeResolver(){return new MyLocaleResolver();}}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CQLaC6ly-1592971582241)(C:\Users\Gary\AppData\Roaming\Typora\typora-user-images\image-20200624111600067.png)]

2.拦截器机制进行登陆检查

1)Controller当中post后传入一个session判断输入了没有

package com.example.webexpriment.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;import javax.servlet.http.HttpSession;
import java.util.Map;@Controller
public class LoginController {//    @RequestMapping(value="/user/login",method = RequestMethod.POST) 用上面更加方便//从请求参数上获取用户名和密码
@PostMapping(value="/user/login")public String login(@RequestParam("username") String username,@RequestParam("password")String password,Map<String,Object>map, HttpSession session){if(!StringUtils.isEmpty(username)&&"123456".equals(password)){//登陆成功System.out.println("登录页面成功");session.setAttribute("loginUser",username);//重定向,防止表单重复提交return "redirect:/main.html";}else{//登录失败map.put("msg","用户名密码错误");return "login";}}
}

2)添加新的类,实现接口

package com.example.webexpriment.component;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 user = request.getSession().getAttribute("loginUser");if(user==null){System.out.println("username为空");//拦截,返回登录页request.setAttribute("msg","没有权限请先登录");request.getRequestDispatcher("/index.html").forward(request,response);return false;}else{System.out.println(user);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 {}
}

3)配置类重写方法

@Override
//注册拦截器
public void addInterceptors(InterceptorRegistry registry) {//addPathPatterns()拦截哪些请求/**全部拦截registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login");//静态资源Spring Boot自己已经搞定映射了,无需多管了
}

员工操作

实验要求

1)、RestfulCRUD:CRUD满足Rest风格;

URI: /资源名称/资源标识 HTTP请求方式区分对资源CRUD操作

普通CRUD(uri来区分操作) RestfulCRUD
查询 getEmp emp—GET
添加 addEmp?xxx emp—POST
修改 updateEmp?id=xxx&xxx=xx emp/{id}—PUT
删除 deleteEmp?id=1 emp/{id}—DELETE

2)、实验的请求架构;

实验功能 请求URI 请求方式
查询所有员工 emps GET
查询某个员工(来到修改页面) emp/1 GET
来到添加页面 emp GET
添加员工 emp POST
来到修改页面(查出员工进行信息回显) emp/1 GET
修改员工 emp PUT
删除员工 emp/1 DELETE

3)、员工列表:

未完待续

Spring Boot web开发(未完待续)相关推荐

  1. spring boot web 开发示例

    一.创建Maven工程 创建maven工程,packaging 类型选择jar. 二.配置相关maven依赖. 1,首先你需要在pom中最上方添加spring boot的父级依赖,这样当前的项目就是S ...

  2. Spring boot web开发实战

    Spring boot项目创建好之后,如何引入静态资源: 1).webjars:直接以maven的方式把包导入进来 <!‐‐引入jquery‐webjar‐‐>在访问的时候只需要写webj ...

  3. spring boot web开发------自定义springmvc配置

    1.如何自定义springmvc配置 旧的springmvc配置文件 <?xml version="1.0" encoding="UTF-8"?> ...

  4. Spring Boot Web 开发相关总结

    2019独角兽企业重金招聘Python工程师标准>>> 1. 表单验证 首先, 在实体类的需要验证的字段上添加添加验证注解, 验证注解类主要在 validation-api-1.1. ...

  5. java调用高德地图API开发,高德在线地图开发——未完待续

    这是目录 一.引入高德地图API 二.高德地图开发 1.定义一个div来存放地图 2.生成地图 3.添加一个跳跃的点 4.添加控件 5.有其他需要的请留言 一.引入高德地图API 高德地图官方示例:h ...

  6. Spring Boot Web

    一. 概述 下面我们将进入 SpringBoot 基础阶段的学习. 在没有正式的学习 SpringBoot 之前,我们要先来了解下什么是 Spring . 我们可以打开 Spring 的官网 ( ht ...

  7. Spring boot web(2):web综合开发

    1 web开发 Spring boot web 开发非常简单,其中包括常用的 json输出.filters.property.log等 1.1 json接口开发 在以前的Spring 开发我么提供js ...

  8. Spring事件机制Event源码解析(未完待续)

    Spring事件机制Event源码解析(未完待续) 监听器: ApplicationEvent事件 ApplicationListener监听器(观察者) ApplicationEventMultic ...

  9. CTF论剑场(web) write up 未完待续

    CTF论剑场(web) write up web26 直接给你一串代码 <?php $num=$_GET['num']; $str=$_GET['str']; show_source(__FIL ...

最新文章

  1. 富有客户端技术之——jQuery EasyUI
  2. pythontkinter在一块区域中绘图_用Python中的tkinter模块作图(续)
  3. lync 安装后相关防病毒软件的设置
  4. jvm内存收集器总结(图片)
  5. gcc与g++编译器
  6. 【Android基础】短信的发送
  7. 分别在(ModelAtrs)Ascend、(Ubuntu16.04服务器+18.04镜像)GPU、(Ubuntu18.04)CPU下通过MindSpore实现(cifar10)图像分类
  8. linux中匿名用户怎么登陆_Linux网络配置 | FTP 实战-匿名用户登录
  9. docker 配置selenium调用Firefox无界面浏览器
  10. ApacheCN Java 译文集 20210921 更新
  11. java api 获取jvm实例_JVMTI那些事——和Java相互调用
  12. uva 11021 Tribles
  13. matlab电力模块,基于MATLAB中电力系统模块集(PSB的电力系统仿真研究
  14. 慕课 springmvc 起步 maven wbe
  15. 关于高校房产管理系统中主要管理模块都有哪些
  16. [Virus Analysis]恶意软件分析(二)玩出花的批处理(中)
  17. 360环视TOP10供应商榜单发布!未来五年市场规模将超300亿元
  18. 【10】Docker的安装 --Mac
  19. g的python实现_Python gevent协程切换实现详解
  20. 【线性代数笔记】矩阵的特征值和特征向量在哪些变换过程中变化?

热门文章

  1. 一体式无线阀控超声水表在西北某市大用户用水计量收费管理项目应用案例
  2. 种群竞争模型及matlab实现
  3. 个人小程序生成链接跳转
  4. 论文浅尝 | 最新10篇《知识图谱》论文推荐(ICML, CVPR, ACL, KDD, IJCAI 2019)
  5. springboot校园新闻趣事 计算机毕业设计(源码、运行环境)
  6. 视频教程:Java从入门到精通
  7. LinQ“高效”更新
  8. 海伦公式用计算机语言怎么写,python中海伦公式求取三角形面积的示例
  9. MahApps.Metro扁平化UI控件库(可修改主题色等)
  10. 淘宝直播回放如何下载