springboot使用初体验

首页实现Thymeleaf

${...} 变量表达式,Variable Expressions

@{...} 链接表达式,Link URL Expressions

#{...} 消息表达式,Message Expressions

~{...} 代码块表达式,Fragment Expressions

*{...} 选择变量表达式,Selection Variable Expressions

国际化

1.配置i18n文件

 

 

2.按钮自动切换,自定义一个组件LocaleResolver

 public class MyLocaleResolver implements LocaleResolver {
     //解析请求
     @Override
     public Locale resolveLocale(HttpServletRequest httpServletRequest) {
         //获取请求中的语言参数
         String language = httpServletRequest.getParameter("lang");
         Locale locale = Locale.getDefault();//没有使用默认
         //请求链接携带国际化参数
         if (!StringUtils.isEmpty(language)) {
             String[] split = language.split("_");
             //国家和地区
            locale = new Locale(split[0], split[1]);
        }
         return locale;
    }
 
     @Override
     public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
 
    }
 }
 

 

3.组件配置到spring容器@Bean

 @Configuration
 public class MyMvcConfig implements WebMvcConfigurer {
     @Override
     public void addViewControllers(ViewControllerRegistry registry) {
         registry.addViewController("/").setViewName("index");
         registry.addViewController("/index.html").setViewName("index");
         registry.addViewController("/main.html").setViewName("dashboard");
    }
     //自定义国际化
     @Bean
     public LocaleResolver localeResolver(){
         return new MyLocaleResolver();
    }
 }
 

 

4.#{}

 <!--如果msg消息为空,不显示-->
 <p style="color: red" th:text="${msg}" th:if="${!#strings.isEmpty(msg)}"></p>

登录

1.登录页设置name

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

2.contraller接受

 @Controller
 public class LoginController {
     @RequestMapping("/user/login")
     public String login(@RequestParam("username") String username,
                         @RequestParam("password") String password,
                         Model model){
         //具体业务
         if (!StringUtils.isEmpty(username)&&"123456".equals(password)) {
             return "redirect:/main.html";
        }else{
             model.addAttribute("msg","用户名或者密码错误!!!");
             return "index";
        }
    }
 
 }
 

3.@RequestParam

@RequestParam:将请求参数绑定到你控制器的方法参数上(是springmvc中接收普通参数的注解)

 语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)
 
 value:参数名
 
 required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
 
 defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值
 

 

1、转发

方式一:使用 “forword” 关键字(不是指java关键字),注意:类的注解不能使用@RestController 要用@Controller
 @RequestMapping(value="/test/test01/{name}" , method = RequestMethod.GET)
 public String test(@PathVariable String name) {
     return "forword:/ceng/hello.html";
 }
方式二:使用servlet 提供的API,注意:类的注解可以使用@RestController,也可以使用@Controller
 @RequestMapping(value="/test/test01/{name}" , method = RequestMethod.GET)
 public void test(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) throws Exception {
     request.getRequestDispatcher("/ceng/hello.html").forward(request,response);
 }

2、重定向

方式一:使用 “redirect” 关键字(不是指java关键字),注意:类的注解不能使用@RestController,要用@Controller
@RequestMapping(value="/test/test01/{name}" , method = RequestMethod.GET)
public String test(@PathVariable String name) {
return "redirect:/ceng/hello.html";
}
方式二:使用servlet 提供的API,注意:类的注解可以使用@RestController,也可以使用@Controller
@RequestMapping(value="/test/test01/{name}" , method = RequestMethod.GET)
public void test(@PathVariable String name, HttpServletResponse response) throws IOException {
response.sendRedirect("/ceng/hello.html");
}

使用API进行重定向时,一般会在url之前加上:request.getContextPath()

登陆拦截器

1.写一个LoginHandlerInterceptor配置类

public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登陆成功有用户session
String loginUser = (String) request.getSession().getAttribute("loginUser");
if (loginUser == null) {//没有登陆
request.setAttribute("msg","没有权限,请先登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
return true;
}
}
}

2.登录中加入session

@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model model, HttpSession session){
//具体业务
if (!StringUtils.isEmpty(username)&&"123456".equals(password)) {
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else{
model.addAttribute("msg","用户名或者密码错误!!!");
return "index";
}
}

}

3.在配置类加入拦截器


//登录拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");


}

员工列表

1.提取公共页面

  1. th: fragment="sidebar"

  2. th: rep1ace="~{commons/commons: :topbar}"

  3. 如果要传递参数,可以直接使用() 传参,接收判断即可!

2.列表循环展示

<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th >department</th>
<th>birth</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="emp:${emps}">
<td th:text="${emp.getId()}"></td>
<td th:text="${emp.getLastName()}"></td>
<td th:text="${emp.getEmail()}"></td>
<td th:text="${emp.getGender()==0?'女':'男'}"></td>
<td th:text="${emp.getDepartment().getDepartmentName()}"></td>
<td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH-mm-ss')}"></td>
<td>
<button class="btn btn-sm btn-primary">编辑</button>
<button class="btn btn-sm btn-danger">删除</button>
</td>
</tr>
</tbody>
</table>
</div>

 

添加员工

  1. 按钮提交

    <h2><a class="btn btn-sm btn-success" th:href="@{/emp}">添加员工</a></h2>
  2. 跳转到添加成功页面


    @GetMapping("/emp")
    public String toAdd(Model model){
    //查出部门所有信息
    Collection<Department> departments = departmentDao.getdepartments();
    model.addAttribute("deps",departments);
    return "emp/add";
    }

     

  3. 返回首页

      @PostMapping("/emp")
    public String addEmp(Employee employee){
    employeeDao.save(employee);
    return "redirect:/emps";
    }

    ps:传递的是th:value="${dep.getId()}"

    <div class="form-group">
    <label>department</label>
    <select class="form-control" name="department.id" >
    <option th:each="dep:${deps}" th:text="${dep.getDepartmentName()}" th:value="${dep.getId()}"></option>
    </select>
    </div>

修改员工

thymeleaf使用restful风格编写url

<a th:href="@{'/emp/' + ${emp.getId()}}">编辑</a>

隐藏域

  <input name="id" type="hidden" th:value="${emp.getId()}" >

单选框和下拉框

 <div class="form-group">
<label>Gender</label>
<br>
<div class="form-check form-check-inline">
<input th:checked="${emp.getGender()==1}" class="form-check-input" type="radio" name="gender" value=1>
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input th:checked="${emp.getGender()==0}" class="form-check-input" type="radio" name="gender" value=0>
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<select class="form-control" name="department.id" >
<option th:selected="${dep.getId()==emp.getDepartment().getId()}" th:each="dep:${deps}" th:text="${dep.getDepartmentName()}"
th:value="${dep.getId()}"></option>
</select>
</div>

删除员工

  //删除员工
@RequestMapping("/delemp/{id}")
public String deleteEmp(@PathVariable("id") Integer id){
employeeDao.delete(id);
return "redirect:/emps";
}

404

templates下建立error文件夹放404页面即可

 

 

 

 

 

 

posted @ 2021-11-24 01:00  亦知  阅读(45)  评论(0)    收藏  举报