第一个SpringBootWeb项目
SpringBootWeb项目
项目目录:
java:

resources:

登录实现:
登录界面:
需要修改css路径
<!DOCTYPE html>
<html lang="en">
<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="/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="/css/signin.css" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html">
<img class="mb-4" 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>
<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<input type="password" class="form-control" 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">[[#{login.btn}]]</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>
// 添加首页控制IndexController
@Controller
public class IndexController {
@RequestMapping({"/","/index.html"})
public String index(){
return "index";
}
}
// 再MyMvcConfig中添加跳转视图控制:
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model model,
HttpSession session){
if(Objects.equals(username, "y")){
session.setAttribute("loginUser", username);
return "redirect:/main.html";
}else{
//登录失败
model.addAttribute("msg","用户名或密码错误!");
return "index";
}
}
@RequestMapping("/user/logout")
public String logout(HttpSession session){
session.setAttribute("loginUser", null);
return "redirect:/index.html";
}
}
运行结果:

国际化
需要在Resources目录下新建i18n文件夹:

并添加对应的文字:

使用时在对应的文本添加即可:
<form class="form-signin" action="/user/login">
<img class="mb-4" 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>
<!--如果msg为空,则不显示消息-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<p>
</p>
<input type="password" name="password" class="form-control" 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">[[#{login.btn}]]</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
</form>
新建MyLocaleResolver用来重写LocalResolves类:
在按钮上传入参数并刷新页面:
<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>
下面是重写的类:
public class MyLocaleResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取请求的参数
String l =request.getParameter("l");
Locale locale1 = Locale.getDefault();//默认(如果没有)
if(!StringUtils.isEmpty(l)){
String[] s = l.split("_");
locale1 = new Locale(s[0], s[1]);
}
return locale1;
}
@Override
public void setLocale(HttpServletRequest request,HttpServletResponse response, Locale locale) {
}
}
接着添加到MyMvcConfig文件里即可:
//自定义国际化组件
@Bean
public LocaleResolver localeResolver() {
return new MyLocaleResolver();
}
自定义拦截器
为了使网站更加安全,使用户只能登录之后才能访问网站的内部,需要在登录后向后端传入一个参数用来判断用户是否登录:
//自定义拦截器
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登录后应该有用户的session
Object loginUser = request.getSession().getAttribute("loginUser");
if(loginUser == null) {
request.setAttribute("msg","没有权限,请先登录!");
request.getRequestDispatcher("/index.html").forward(request, response);
return false;
}
return true;
}
}
添加到MyMvcConfig中:
// 拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");
}
//这里可以添加你需要拦截排除的文件
新建员工与部门
//员工表
@Data
@NoArgsConstructor
public class Empolyee {
private Integer id;
private String name;
private String email;
private Integer gender;//男1,女0
private Department department;
private Date birth;
public Empolyee(int i, String aa, String mail, int i1, Department department) {
this.id = i;
this.name = aa;
this.email = mail;
this.gender = i1;
this.department = department;
this.birth = new Date();
}
}
//部门表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String name;
}
添加Dao层
//员工Dao
@Repository
public class EmployeeDao {
//模拟数据库
private static Map<Integer, Empolyee> empolyeeMap = null;
//员工的部门
@Autowired
private DepartmentDao DepartmentDao;
static {
empolyeeMap = new HashMap<Integer, Empolyee>(); //创建部门表
empolyeeMap.put(101,new Empolyee(101,"AA","A66@qq.com",1,getDepartmentById(101)));
empolyeeMap.put(102,new Empolyee(102,"BB","B66@qq.com",0,getDepartmentById(102)));
empolyeeMap.put(103,new Empolyee(103,"CC","C66@qq.com",1,getDepartmentById(103)));
empolyeeMap.put(104,new Empolyee(104,"DD","D66@qq.com",0,getDepartmentById(104)));
empolyeeMap.put(105,new Empolyee(105,"EE","E66@qq.com",1,getDepartmentById(105)));
}
//主键自增
private static Integer initId = 106;
//增加员工
public static void save(Empolyee empolyee){
if(empolyee.getId()==null){
empolyee.setId(initId++);
}
empolyee.setDepartment(getDepartmentById(empolyee.getDepartment().getId()));
empolyeeMap.put(empolyee.getId(),empolyee);
}
//删除员工
public void delete(Integer id){
empolyeeMap.remove(id);
}
//获取所有员工信息
public Collection<Empolyee> getEmpolyees() {
return empolyeeMap.values();
}
//通过id获得员工
public static Empolyee getEmpolyeeById(Integer id) {
return empolyeeMap.get(id);
}
}
//部门Dao
@Repository
public class DepartmentDao {
//模拟数据库
private static Map<Integer, Department> departmentMap = null;
static {
departmentMap = new HashMap<Integer, Department>(); //创建部门表
departmentMap.put(101,new Department(101,"一部"));
departmentMap.put(102,new Department(102,"二部"));
departmentMap.put(103,new Department(103,"三部"));
departmentMap.put(104,new Department(104,"四部"));
departmentMap.put(105,new Department(105,"五部"));
}
//获取所有部门信息
public Collection<Department> getDepartments() {
return departmentMap.values();
}
//通过id获得部门
public static Department getDepartmentById(Integer id) {
return departmentMap.get(id);
}
}
增删改查
// 控制层
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
@Autowired
DepartmentDao departmentDao;
@RequestMapping("/emps")
public String list(Model model){
Collection<Empolyee> empolyees = employeeDao.getEmpolyees();
model.addAttribute("emps", empolyees);
return "emp/list";
}
@GetMapping("/emp")
public String toAddPage(Model model){
//查出部门数据
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments", departments);
return "emp/add";
}
@PostMapping("/emp")
public String addEmp(Empolyee empolyee){
//添加的操作
System.out.println(empolyee);
EmployeeDao.save(empolyee);
return "redirect:/emps";
}
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id")Integer id, Model model){
//查出原来的数据
Empolyee empolyee = EmployeeDao.getEmpolyeeById(id);
model.addAttribute("emp", empolyee);
//查出部门数据
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments", departments);
return "emp/update";
}
@PostMapping("/updateEmp")
public String updateEmp(Empolyee empolyee){
employeeDao.save(empolyee);
return "redirect:/emps";
}
@GetMapping("/deleteEmp/{id}")
public String deleteEmp(@PathVariable("id")Integer id){
employeeDao.delete(id);
return "redirect:/emps";
}
}
错误处理
在templates文件夹下新建error文件夹,无需配置其他文件即可访问到。

404错误
服务器无法根据客户端的请求找到资源(网页)。通过此代码,网站设计人员可设置"您所请求的资源无法找到"的个性页面
500错误
服务器内部错误,无法完成请求

浙公网安备 33010602011771号