导入配置
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>pulls2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>pulls2</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>
org.apache.tomcat.embed
</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>
true
</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
使用步骤
1.Model准备
package com.example.pulls2.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pulls2.pojo.User;
import java.util.List;
public interface UserService {
public List<User> select();
public User fiand(Long id);
public int addUser(User user);
public User login(QueryWrapper wrapper);
}
2.创建控制器
package com.example.pulls2.controller;
import com.example.pulls2.pojo.User;
import com.example.pulls2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
public class UserController {
@Resource
UserService userService;
@GetMapping("/select")
public List<User> select(){//查询页面
return userService.select();
}
@GetMapping("/chaz/{id}")//查询id用户
public User getUser(@PathVariable("id")Long userId){
return userService.fiand(userId);
}
@PostMapping("/user")//添加用户
public void addUser(User user){
userService.addUser(user);
}
}
RESTful的支持
RESTful是目前最流行的一种互联网软件架构.
spring boot对RESTful的支持
- @GetMapping,处理get请求
- @PostMapping,处理post请求
- @PutMapping,用于更新资源
- @DeleteMapping,处理删除请求
- @PatchMapping,用于更新部分资源
3.Web测试的支持
下面是MockMvc测试类的基本结构
@Before代表在测试启动时候需要提前加载的内容,这里是提前加载MVC环境
package com.example.pulls2;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
import javax.annotation.Resource;
import javax.swing.*;
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserControllerTester {
@Resource
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup(){
this.mockMvc= MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testGetUser() throws Exception {//查询用户
String mvcResult=mockMvc.perform(MockMvcRequestBuilders.get("/chaz/4")).
andReturn().getResponse().getContentAsString();
System.out.println("结果:"+mvcResult);
}
@Test
public void testaddUser() throws Exception {//添加用户
final MultiValueMap<String,String>params=new LinkedMultiValueMap<>();
params.add("name","张章");
params.add("logid","1");
params.add("password","1");
mockMvc.perform(MockMvcRequestBuilders.post("/user").params(params)).
andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
}
视图(JSP)开发
项目结构在main文件夹下创建webapp在创建WEB-INF目录,在WEB-INF目录下面在创建jsp目录
配置文件
在application.properties中加入配置
#前缀
spring.mvc.view.prefix=/WEB-INF/jsp/
#后缀
spring.mvc.view.suffix=.jsp
编写控制器
package com.example.pulls2.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pulls2.pojo.User;
import com.example.pulls2.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@Resource
private UserService userService;
@RequestMapping("/jie")
public String login(){
return "login";
}
@RequestMapping("/login")
public String ulogin(String name, String password, HttpSession session, Model mode){
QueryWrapper wrapper=new QueryWrapper();
wrapper.eq("name",name);
wrapper.eq("password",password);
User user=userService.login(wrapper);
if (user!=null){
session.setAttribute("user",user);
return "main";
}else{
mode.addAttribute("msg","用户名或密码错误,登录失败!");
return "login";
}
}
}
环境配置
启动项目后在浏览器中打开对应的链接就可以使用了
自定义过滤器
在目录filter创建类
package com.example.pulls2.filter;
import org.springframework.http.HttpRequest;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class AuthorizationFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
HttpServletResponse httpServletResponse=(HttpServletResponse)servletResponse;
if (httpServletRequest.getSession().getAttribute("user")==null){
httpServletResponse.setContentType("text/html;charset=UTF-8");
PrintWriter out=httpServletResponse.getWriter();
out.println("<script>alert('请先进行登录,再进行后操作!(Filter 控制)');location.href='"+httpServletRequest.getContextPath()+"/jie';</script>");
}else{
filterChain.doFilter(httpServletRequest,httpServletResponse);
}
}
@Override
public void destroy() {
}
}
然后在config目中创建类
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean registrationBean=new FilterRegistrationBean();
registrationBean.setFilter(new AuthorizationFilter());
registrationBean.setName("AuthorizationFilter");
registrationBean.addUrlPatterns("/main");//作为演示,仅限main访问
registrationBean.setOrder(5);
return registrationBean;
}
大家快去试试构建一个视图项目吧,实践出真理.