下面我将为您详细讲解如何使用注解实现SpringMVC的登录功能。
1. 创建SpringMVC项目
首先,我们需要使用Maven工具创建一个空的SpringMVC项目:
<groupId>com.example</groupId>
<artifactId>springmvcdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
2. 创建实体类
接着,我们需要创建一个实体类,用于储存用户信息。这里我们创建一个User类:
public class User {
private String username;
private String password;
// getters and setters
}
3. 创建DAO层
然后,我们需要创建一个DAO层,用于查询数据库中的用户信息。这里我们使用JdbcTemplate进行数据库操作:
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public User getUser(String username) {
List<User> userList = jdbcTemplate.query(
"SELECT * FROM user WHERE username = ?",
new Object[]{username},
new BeanPropertyRowMapper<>(User.class)
);
return userList.isEmpty() ? null : userList.get(0);
}
}
4. 创建Service层
接下来,我们需要创建一个Service层,对DAO层进行包装,提供更加友好的API:
@Service
public class UserService {
@Autowired
private UserDao userDao;
public boolean verifyUser(String username, String password) {
User user = userDao.getUser(username);
return user != null && user.getPassword().equals(password);
}
}
5. 创建Controller
现在我们需要创建Controller层,处理用户请求。这里我们使用注解,实现登录功能。
@Controller
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping("/login")
public String login() {
return "login";
}
@PostMapping("/doLogin")
public String doLogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session,
Model model) {
if (userService.verifyUser(username, password)) {
session.setAttribute("username", username);
return "redirect:/home";
} else {
model.addAttribute("msg", "Invalid username or password.");
return "login";
}
}
@RequestMapping("/home")
public String home(HttpSession session, Model model) {
String username = (String) session.getAttribute("username");
if (username != null) {
model.addAttribute("username", username);
return "home";
} else {
return "redirect:/login";
}
}
}
6. 创建页面
最后,我们需要创建登录页面和主页页面。
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<p style="color: red;">${msg}</p>
<form action="/doLogin" method="post">
<p>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
</p>
<p>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
</p>
<p>
<input type="submit" value="Login">
</p>
</form>
</body>
</html>
home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Home</h1>
<p>Welcome, ${username}!</p>
</body>
</html>
好了,现在您已经学会如何使用注解实现SpringMVC的登录功能。如果您还有疑问,可以参考下面的示例。
示例一
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class LoginControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testLogin() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("/login")
).andExpect(
MockMvcResultMatchers.status().isOk()
).andExpect(
MockMvcResultMatchers.view().name("login")
);
}
@Test
public void testDoLogin_success() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.post("/doLogin")
.param("username", "admin")
.param("password", "123456")
).andExpect(
MockMvcResultMatchers.status().is3xxRedirection()
).andExpect(
MockMvcResultMatchers.view().name("redirect:/home")
).andExpect(
MockMvcResultMatchers.redirectedUrl("/home")
);
}
@Test
public void testDoLogin_failure() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.post("/doLogin")
.param("username", "admin")
.param("password", "654321")
).andExpect(
MockMvcResultMatchers.status().isOk()
).andExpect(
MockMvcResultMatchers.view().name("login")
).andExpect(
MockMvcResultMatchers.model().attributeExists("msg")
);
}
@Test
public void testHome() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("/home")
).andExpect(
MockMvcResultMatchers.status().is3xxRedirection()
).andExpect(
MockMvcResultMatchers.redirectedUrl("/login")
);
}
}
示例二
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public Map<String, Object> login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session) {
Map<String, Object> resultMap = new HashMap<>();
if (userService.verifyUser(username, password)) {
session.setAttribute("username", username);
resultMap.put("code", 0);
resultMap.put("msg", "Login success.");
} else {
resultMap.put("code", 1);
resultMap.put("msg", "Invalid username or password.");
}
return resultMap;
}
@GetMapping("/home")
public Map<String, Object> home(HttpSession session) {
Map<String, Object> resultMap = new HashMap<>();
String username = (String) session.getAttribute("username");
if (username != null) {
resultMap.put("code", 0);
resultMap.put("msg", "Welcome, " + username + "!");
} else {
resultMap.put("code", 1);
resultMap.put("msg", "Please login first.");
}
return resultMap;
}
}
希望这些内容能够帮助到您。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringMVC使用注解实现登录功能 - Python技术站