Springboot和thymeleaf 和SpringSecurity快速配置

pom.xml导入依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>

        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
    </dependencies>

application.properties 对应的jdbc和thymleaf路径的配置:

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=hsp
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.security.user.name=admin
spring.security.user.password=123123

实体类:

@Data
public class User {
    @NotNull(message = "id不可为空")
    private Long id;
    @NotEmpty(message = "姓名不可为空")
    @Length(min = 2,message = "姓名长度不少于两位")
    private String name;
    @Min(value = 16,message = "年龄要大于16")
    @Max(value = 150,message = "年龄不得大于150")
    private int age;
}

repository:

public interface UserRepository {
    public List<User> findAll();
    public User findById(long id);
    public void save(User user);
    public void update(User user);
    public void deleteById(long id);
}
@Repository
public class UserRepository implements com.example.demo.repository.UserRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public List<User> findAll() {
        return jdbcTemplate.query("select * from user",new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public User findById(long id) {
        return jdbcTemplate.queryForObject("select* from user where  id = ?",new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public void save( User user) {
        jdbcTemplate.update("insert into user(name,age) values(?,?)",user.getName(),user.getAge());
    }

    @Override
    public void update( User user) {
        jdbcTemplate.update("update  user set name=?,age = ? where id = ?",user.getName(),
                user.getAge(),user.getId());
    }

    @Override
    public void deleteById(long id) {
        jdbcTemplate.update("delete from user where id=?",id);
    }
}

对应的控制

@RestController
@RequestMapping("/user")
public class UserHandler {
    @Autowired
    private UserRepository userRepository;
    @GetMapping("/findAll")
    public List<User> findAll(){
        return  userRepository.findAll();
    }
    @GetMapping("/findById/{id}")
    public User findById(@PathVariable("id") long id){
        return userRepository.findById(id);
    }
    @PostMapping("/save")
    public void save(@RequestBody User user){
        userRepository.save(user);
    }
    @PutMapping("/update")
    public void  update(@RequestBody  User user){
        userRepository.update(user);
    }
    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") long id){
        userRepository.deleteById(id);
    }
}

启动类:

@SpringBootApplication
public class Demo1Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);

    }

}

--------------------------------------------------------------------------------------------------------------------------------

Thymeleaf相关:

表格:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>叮咚鸡</h1>
    <table>
        <tr>
            <th>Index</th>
            <th>Count</th>
            <th>学生编号</th>
            <th>学生姓名</th>
            <th>学生年龄</th>
            <th>操作</th>
        </tr>
        <tr th:each="student,stat:${list}" th:style="'background-color:'+@{${stat.odd}?'#F2F2'}">
            <td th:text="${stat.index}"></td>
            <td th:text="${stat.count}"></td>

            <td th:text="${student.id}"></td>
            <td th:text="${student.name}"></td>
            <td th:text="${student.age}"></td>
        </tr>
    </table>
    <div >
        <p th:text="${name}"></p>
        <p th:text=" '学生姓名:'+ ${name} "></p>
        <p th:if="${flag == true}" th:text="if判断成立"></p>
        <p th:unless="${flag!= true}" th:text="unnless判断成立"></p>
    </div>
    <a th:href="@{http://www.baidu.com}">跳转百度</a>
    <a th:href="@{http://localhost:8080/index/url/if}">跳转其他</a>
    <form action="/logout" method="post">
        <input type="submit" value="退出">
    </form>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <a th:href="@{http://www.baidu.com}">跳转百度</a>
    <a th:href="@{http://localhost:8080/index/url/{name}(name=${name})}">跳转其他</a>
    <!-- chatgpt的写法 -->
    <a th:href="@{'http://localhost:8080/index/url/' + ${name}}">跳转其他</a>
    <img th:src="${src}">
    <div th:style="'background:url(' + ${src2} + ');'">我他妈是傻逼
    <br><br><br><br><br>
    </div>
    <input th:value="${age <= 30?'青年':'中年'}">

    <div th:switch="${gender}">
        <p th:case="female">女</p>
        <p th:case="male">男</p>
        <p th:case="*">牛B</p>
    </div>
    <!-- 时间-->
    <p th:text="${#dates.format(date,'yyyy-MM-dd HH:mm:ss')}"></p>
    <!--创建时间 -->
    <p th:text="${#dates.createToday()}"></p>
    <p th:text="${#dates.createNow()}"></p>

    <p th:text="${#strings.isEmpty(name)}"></p>
    <p th:text="${#strings.isEmpty(users)}"></p>

    <p th:text="'随即字符串:'+${#strings.randomAlphanumeric(10)}"></p>

</body>
</html>

表格:

<table>
    <tr>

        <th>编号</th>
        <th>姓名</th>
        <th>邮箱</th>
        <th>雇佣时间</th>
        <th>薪水</th>
        <th>操作</th>
    </tr>
    <tr th:each="student,stat:${list}" th:style="'background-color:'+@{${stat.odd}?'#F2F2'}">
        <td th:text="${student.id}"></td>
        <td th:text="${student.name}"></td>
        <td th:text="${student.email}"></td>
        <td th:text="${student.hiredDate}"></td>
        <td th:text="${student.salary}"></td>
        <td>
            <a th:href="@{/emp/update/{id}(id=${student.id})}" onclick="return confirm('Are you sure you want to update it?');">修改</a>
            <a th:href="@{/emp/deleteById/{id}(id=${student.id})}" onclick="return confirm('Are you sure you want to delete?');">删除</a>

        </td>
    </tr>
</table>

<a th:href="@{/emp/save}" role="button">添加数据</a>

表单(update) 主要是对日期的处理

<form action="/emp/update" method="post" th:object="${student}">
    <div>ID:<input type="text" name="id" th:value="${student.id}" readonly></div>
    <div>Name:<input type="text" th:field="*{name}"></div>
    <div>Email:<input type="text" th:field="*{email}"></div>
    <div>HireDate:<input type="text" th:field="*{hiredDate}"  placeholder="yyyy-MM-dd" class="datepicker"></div>
    <div>salary:<input type="text" th:field="*{salary}"></div>
    <input type="submit" value="提交">

</form>

表单(save)

<form action="/emp/save" method="post" >
    <div>ID: <input type="text" name="id" ></div>
    <div>Name: <input type="text" name="name"></div>
    <div>Email: <input type="text" name="email"></div>
    <div>HireDate: <input type="text" name="hiredDate" ></div>
    <div>Salary: <input type="text" name="salary"></div>
    <input type="submit" value="提交">
</form>

---------------------------------------------------------------------------------------------------------------------------------安全有关:

public class MyPasswordEncder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(charSequence.toString());
    }
}

对两个角色设置权限 admin user

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncder())
                .withUser("user").password(new MyPasswordEncder().encode("000"))
                .roles("user")
                .and()
                .withUser("admin").password(new MyPasswordEncder().encode("123"))
                .roles("ADMIN","user");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/index").access("hasRole('ADMIN') or hasRole('user')")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .and().csrf().disable();
    }
}

写的login登陆页面

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form th:action="@{/login}" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="text" name="password"> <br>
        <input type="submit" value="登陆">
    </form>
</body>
</html>
loginHandler
<form method="post" action="/login/validate">
    <table>
        <tr><td>id:</td><td><input type="text" name="id"></td></tr>
        <tr><td>pwd:</td><td><input type="password" name="pwd"></td></tr>
        <tr><td><input type="submit" value="登陆"></td><td>
            <input type="reset" value="重置">
        </td></tr>
    </table>


@Controller
@RequestMapping("/login")
public class LoginHandler {
    @Autowired
    EmployerRepository employerRepository;

    @GetMapping("/login")
    public String loginin(){
        return "login";
    }
    @GetMapping("/success")
    public String getSuccess(Model model){
        model.addAttribute("list",employerRepository.findAll());
        return "success";
    }

    @PostMapping("/validate")
    public String validateLogin(@RequestParam("id") String id, @RequestParam("pwd") String pwd, Model model){
        try {
            Employer employer = employerRepository.findById(Integer.parseInt(id));
            if(employer != null && pwd.equals(employer.getPwd()))
            {model.addAttribute("list",employerRepository.findAll());

                return "success";
            }
            else
                return "sorry";
        }
        catch (Exception e){
            System.out.println(e.getMessage());
            return "sorry";
        }


    }
}
<tr th:each="student,stat:${list}" th:style="'background-color:'+@{${stat.odd}?'#F2F2'}"> 每行变色
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值