框架技术---SpringBoot(五)WEB开发《三》WEB开发RestfulCRUD

一、 默认访问首页

// 所有的webMvcConfigureAdapter组件都会在一起起作用
   @Bean// 将组件注册在容器中
   public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
       WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
           @Override
           public void addViewControllers(ViewControllerRegistry registry) {
               registry.addViewController("/").setViewName("login");
               registry.addViewController("/index.html").setViewName("login");
           }
       };
       return  adapter;
   }

二、添加国际化

sprngMVC的步骤

  1. 编写国际化配置文件;
  2. 使用ResourceBundleMessageSource 管理国际化资源文件
  3. 在页面使用fmt:message取出国际化内容

springBoot步骤:

  1. 编写国际化配置文件;抽取需要显示的国际化信息
    在这里插入图片描述
  2. springBoot自动配置好了管理国际化资源文件的组件
public class MessageSourceAutoConfiguration {
    private static final Resource[] NO_RESOURCES = new Resource[0];

    public MessageSourceAutoConfiguration() {
    }

    @Bean
    @ConfigurationProperties(
        prefix = "spring.messages"
    )
    // 获取资源文件属性
    public MessageSourceProperties messageSourceProperties() {
        return new MessageSourceProperties();
    }

    @Bean
    public MessageSource messageSource(MessageSourceProperties properties) {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        if (StringUtils.hasText(properties.getBasename())) {
          // 设置国际化资源文件的基础名(去掉国家代码的)
            messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
        }

        if (properties.getEncoding() != null) {
            messageSource.setDefaultEncoding(properties.getEncoding().name());
        }

        messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
        Duration cacheDuration = properties.getCacheDuration();
        if (cacheDuration != null) {
            messageSource.setCacheMillis(cacheDuration.toMillis());
        }

        messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
        messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
        return messageSource;
    }
public class MessageSourceProperties {
    private String basename = "messages";//我们配置文件文件可以直接放在类路径下的messages.properties;
    private Charset encoding;
    @DurationUnit(ChronoUnit.SECONDS)
    private Duration cacheDuration;
    private boolean fallbackToSystemLocale;
    private boolean alwaysUseMessageFormat;
    private boolean useCodeAsDefaultMessage;

    public MessageSourceProperties() {
        this.encoding = StandardCharsets.UTF_8;
        this.fallbackToSystemLocale = true;
        this.alwaysUseMessageFormat = false;
        this.useCodeAsDefaultMessage = false;
    }

3.去页面获取国际化的值

修改文件encoding编码
在这里插入图片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta 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 · Bootstrap</title>

    <!--<link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/sign-in/">-->

    <!-- Bootstrap core CSS -->
<link href="css/bootstrap.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet"  crossorigin="anonymous">


    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }
    </style>
    <!-- Custom styles for this template -->
    <link href="css/signin.css" th:href="@{/css/signin.css}" rel="stylesheet">
  <script src="js/prompt.js" th:src="@{/js/prompt.js}"></script></head>
  <body class="text-center">
    <form class="form-signin" action="mainPage.html" th:action="@{/user/login}" method="post">
  <img class="mb-4" src="img/bootstrap-solid.svg" th:src="@{/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>
      <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
  <label  class="sr-only" th:text="#{login.username}">UserName</label>
  <input type="text" name="username" id="username" class="form-control" placeholder="UserName" th:placeholder="#{login.username}" required="" autofocus="">
  <label class="sr-only" th:text="#{login.password}">Password</label>
  <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" th:placeholder="#{login.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-2019</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>

效果是根据浏览器的语言设置的信息切换国际化;


原理:

国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象)

@Bean
 @ConditionalOnMissingBean
 @ConditionalOnProperty(
     prefix = "spring.mvc",
     name = {"locale"}
 )
 public LocaleResolver localeResolver() {
     if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) {
         return new FixedLocaleResolver(this.mvcProperties.getLocale());
     } else {
         AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
         localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
         return localeResolver;
     }
 }
 // 默认的区域解析器是根据浏览器请求头中获取

我们可以自己写一个国际化解析器

/**
 * 可以在连接上携带上区域信息
 */
public class MyLocaleResolver implements LocaleResolver{
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
//        获取去请求中的l参数
        String l = request.getParameter("l");
//        初始化默认的Locale
        Locale locale = Locale.getDefault();
//        判断参数是否为空
        if(!StringUtils.isEmpty(l)){
//            分割参数的_语言和国家
            String[] split = l.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, @Nullable HttpServletResponse httpServletResponse, @Nullable Locale locale) {

    }
}
// 将自己写的区域信息解析器注册到容器中
@Bean
   public LocaleResolver localeResolver(){
       return new MyLocaleResolver();
   }

登陆

开发期间模板引擎页面修改以后,要实时生效

  • 禁用模板引擎的缓存
#禁用缓存
spring.thymeleaf.cache=false
  • 页面修改完成ctrl+f9;重新编译;
  • 拦截器实现
    • 实现HandlerInterceptor接口
    //目标方法执行之前
    @Override
     public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
        return true;
    }
    
CRUD
普通CRUD(uri来区分操作)RestulCRUD
查询getEmpemp —GET
添加addEmp?xxxemp —POST
修改updateEmp?id=xxx&xxxemp/{id} —PUT
删除delectEmp?id=1emp/{id} —DELECT

实验请求架构:

实验功能请求url请求方式
查询所有员工empsGET
查询某个员工(来到求改页面)emp/1GET
来到添加页面empGET
添加员工empPOST
来到修改页面emp/1GET
修改员工empPUT
删除员工emp/1DELECT

修改员工数据时,put请求在表单中的使用:
高版本的springboot 的HiddenHttpMethodFilter默认时关闭的需要
在application.xml中添加配置

#启动HiddenHttpMethodFilter 可以使用put请求
spring.mvc.hiddenmethod.filter.enabled=true
<!--发送put请求修改员工数据-->
                <!--1.Spring MVC种配置HiddenHttpMethodFilter 这一步springboot已经自动配置好-->
                <!--2.页面创建一个post表单-->
                <!--3.创建input项,name="_method" 值就是我们指定的请求方式-->
                <form th:action="@{/emp}" method="post">
                    <!--发送put请求修改员工数据-->
                    <!--1.Spring MVC种配置HiddenHttpMethodFilter-->
                    <!--2.页面创建一个post表单-->
                    <!--3.创建input项,name="_method" 值就是我们指定的请求方式-->
                <input type="hidden" name="_method" value="put" th:if="${emp!=null}">

删除员工
方式一:
通过将button按钮放到form表单中进行提交

 <td >
  <a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
  <form id="deleteEmpForm" th:action="@{/emp/}+${emp.id}"  method="post">
  <input type="hidden" name="_method" value="delete">
  <button type="submit"  class="btn btn-sm btn-danger">删除</button>
   </form>
 </td>

方式二:通过js在提交给form表单;将form表单放到表单外面;减少form的个数。

<!--- 在table中的删除按钮----->
 <td >
                                 <a class="btn btn-sm btn-primary"th:href="@{/emp/}+${emp.id}">编辑</a>
                                <button th:attr="del_uri=@{/emp/}+${emp.id}"  class="btn btn-sm btn-danger deleteBtn">删除</button>
 </td>
 <!-------删除的form表单放在table外面 所有数据公用这一个form--->
        <form id="deleteEmpForm"  method="post">
            <input type="hidden" name="_method" value="delete">
        </form>
        
 <!---------bootStrap  core javascript  ----------> 
  <script type="text/javascript" th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
<script type="text/javascript" th:src="@{/webjars/bootstrap/4.0.0/js/bootstrap.js}"></script>
<script>
    $(".deleteBtn").click(function () {
        // 删除当前员工
        $('#deleteEmpForm').attr('action',$(this).attr("del_uri")).submit();
        return false;
    })
</script>   
                            
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值