controller层接收jsp页面数据的参数Model HTTPSession对象是干嘛用的
时间: 2024-06-04 22:06:02 浏览: 13
在控制器(Controller)中,接收JSP页面数据的参数可以使用Model和HTTPSession对象。
Model对象用于向视图(View)传递数据,通过addAttribute()方法将数据添加到Model中,然后在视图中使用EL表达式(${})或JSTL标签(<c:out>)获取数据。
HTTPSession对象用于在多个请求之间保存数据,通过setAttribute()方法将数据添加到HTTPSession中,在其他请求中可以通过getAttribute()方法获取数据。HTTPSession对象通常用于保存用户登录信息、购物车等。
需要注意的是,HTTPSession对象会在服务器端保存数据,因此需要考虑内存和性能问题,避免存储过多的数据。而Model对象只是在请求处理期间有效,不会对服务器造成负担,因此一般情况下优先使用Model对象。
相关问题
springmvc+hibnate+mysql实现用户的登入和登出日志,用jsp页面显示
首先,你需要在项目中引入SpringMVC、Hibernate和MySQL的依赖。可以在pom.xml文件中添加如下依赖:
```xml
<dependencies>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.5.7.Final</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
</dependencies>
```
接下来,创建一个用户实体类User,包含用户名、密码和登录时间等属性,并使用Hibernate注解进行映射:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username", nullable = false)
private String username;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "login_time", nullable = false)
private Date loginTime;
// 省略getter和setter方法
}
```
接下来创建一个DAO类UserDao,用于对用户实体进行CRUD操作:
```java
@Repository
public class UserDao {
@Autowired
private SessionFactory sessionFactory;
public void save(User user) {
Session session = sessionFactory.getCurrentSession();
session.save(user);
}
public User findByUsername(String username) {
Session session = sessionFactory.getCurrentSession();
Query<User> query = session.createQuery("from User where username=:username", User.class);
query.setParameter("username", username);
return query.uniqueResult();
}
}
```
接下来,创建一个登录控制器LoginController,用于处理用户登录请求:
```java
@Controller
public class LoginController {
@Autowired
private UserDao userDao;
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam String username, @RequestParam String password, Model model) {
User user = userDao.findByUsername(username);
if (user == null || !user.getPassword().equals(password)) {
// 登录失败
model.addAttribute("error", "用户名或密码错误");
return "login";
} else {
// 登录成功,记录登录日志
user.setLoginTime(new Date());
userDao.save(user);
// 将用户信息存入session
HttpSession session = request.getSession();
session.setAttribute("user", user);
return "redirect:/index.jsp";
}
}
}
```
最后,创建一个注销控制器LogoutController,用于处理用户注销请求:
```java
@Controller
public class LogoutController {
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpServletRequest request) {
// 清空session
HttpSession session = request.getSession();
session.invalidate();
return "redirect:/login.jsp";
}
}
```
在JSP页面中,可以通过EL表达式获取用户信息并显示在页面上:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>欢迎 ${user.username} 登录</h1>
<a href="${pageContext.request.contextPath}/logout">注销</a>
</body>
</html>
```
以上就是一个简单的SpringMVC+Hibernate+MySQL实现用户登录和注销日志,并在JSP页面中显示用户信息的示例。
idea 中jsp页面实现验证码登陆
以下是使用 JSP 页面实现验证码登录的示例代码:
1.创建一个Controller类:
```java
@Controller
public class LoginController {
private static final String SESSION_KEY_CHECKCODE = "checkCode";
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public String login(String username, String password, String checkCode, HttpSession session, Model model) {
// 验证码校验
String checkCodeSession = (String) session.getAttribute(SESSION_KEY_CHECKCODE);
if (!checkCode.equalsIgnoreCase(checkCodeSession)) {
model.addAttribute("errorMsg", "验证码错误");
return "login";
}
// 用户名和密码校验
if ("admin".equals(username) && "123456".equals(password)) {
// 登录成功
return "redirect:/success";
} else {
// 登录失败
model.addAttribute("errorMsg", "用户名或密码错误");
return "login";
}
}
@GetMapping("/checkCode")
public void checkCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
// 定义图片宽、高
int width = 100;
int height = 50;
// 创建 BufferedImage 对象,设置图片大小和类型
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取 Graphics2D 对象,用于绘制图形
Graphics2D graphics2D = img.createGraphics();
// 设置背景色
graphics2D.setColor(Color.WHITE);
graphics2D.fillRect(0, 0, width, height);
// 设置字体
graphics2D.setFont(new Font("宋体", Font.BOLD, 20));
// 随机生成 4 位验证码
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 4; i++) {
int num = random.nextInt(10);
sb.append(num);
graphics2D.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
graphics2D.drawString(String.valueOf(num), i * 20, 30);
}
// 将验证码存入 session 中
session.setAttribute(SESSION_KEY_CHECKCODE, sb.toString());
// 释放 Graphics2D 对象
graphics2D.dispose();
// 将验证码图片输出到浏览器
ImageIO.write(img, "JPEG", response.getOutputStream());
}
@GetMapping("/success")
public String success() {
return "success";
}
}
```
2.创建一个login.jsp页面:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>验证码登录</title>
</head>
<body>
<h2>验证码登录</h2>
<form method="post" action="/login">
<label for="username">用户名:</label>
<input type="text" id="username" name="username"/><br/>
<label for="password">密码:</label>
<input type="password" id="password" name="password"/><br/>
<label for="checkCode">验证码:</label>
<input type="text" id="checkCode" name="checkCode"/>
<img src="/checkCode"/><br/>
<input type="submit" value="登录"/>
</form>
<div style="color: red">${errorMsg}</div>
</body>
</html>
```
3.创建一个success.jsp页面:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录成功</title>
</head>
<body>
<h2>登录成功</h2>
</body>
</html>
```
4.运行代码,在浏览器中访问 "http://localhost:8080/login" 即可看到验证码登录页面。
注意:此示例仅包含基本的验证码登录功能,实际应用中需要添加身份验证、安全性等方面的特性。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)