写一个javaweb实现登录注册基于(spring mvc,mysql,maven)的代码
时间: 2024-03-07 13:46:45 浏览: 157
javaweb使用mvc框架实现注册登录
很抱歉,作为AI语言模型,我无法提供完整的代码实现。但是我可以提供一个基于Spring MVC、MySQL和Maven的登录注册示例,供您参考学习。
首先,在pom.xml中添加以下依赖:
```
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
```
接着,创建Spring MVC配置文件spring-servlet.xml,并添加以下配置:
```
<!-- 配置注解扫描 -->
<context:component-scan base-package="com.example.controller" />
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- 配置Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.example.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<!-- 配置Hibernate事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 开启事务注解 -->
<tx:annotation-driven />
```
然后,创建Controller类UserController.java,并添加以下代码:
```
@Controller
@RequestMapping("/")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "register", method = RequestMethod.GET)
public String showRegisterForm() {
return "register";
}
@RequestMapping(value = "register", method = RequestMethod.POST)
public String register(@RequestParam String username, @RequestParam String password, Model model) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
if (userService.addUser(user)) {
model.addAttribute("message", "注册成功!");
return "login";
} else {
model.addAttribute("error", "注册失败,请重试!");
return "register";
}
}
@RequestMapping(value = "login", method = RequestMethod.GET)
public String showLoginForm() {
return "login";
}
@RequestMapping(value = "login", method = RequestMethod.POST)
public String login(@RequestParam String username, @RequestParam String password, Model model, HttpSession session) {
User user = userService.getUserByUsername(username);
if (user != null && user.getPassword().equals(password)) {
session.setAttribute("user", user);
return "redirect:/home";
} else {
model.addAttribute("error", "用户名或密码错误!");
return "login";
}
}
@RequestMapping("home")
public String home(HttpSession session, Model model) {
User user = (User) session.getAttribute("user");
if (user != null) {
model.addAttribute("username", user.getUsername());
return "home";
} else {
return "redirect:/login";
}
}
}
```
在上面的代码中,我们定义了四个请求处理方法,分别对应注册页面展示、注册请求处理、登录页面展示、登录请求处理。其中,@RequestMapping注解用于指定请求的URL地址,@RequestParam注解用于获取请求参数,Model用于向视图传递数据,HttpSession用于保存用户会话信息。
接着,创建Service层接口UserService.java,并添加以下代码:
```
public interface UserService {
boolean addUser(User user);
User getUserByUsername(String username);
}
```
创建Service实现类UserServiceImpl.java,并添加以下代码:
```
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public boolean addUser(User user) {
return userDao.addUser(user);
}
@Override
public User getUserByUsername(String username) {
return userDao.getUserByUsername(username);
}
}
```
在上面的代码中,我们使用了注解@Service和@Transactional,分别用于将UserServiceImpl类标记为Spring管理的Bean,以及开启事务支持。
最后,创建DAO层接口UserDao.java,并添加以下代码:
```
public interface UserDao {
boolean addUser(User user);
User getUserByUsername(String username);
}
```
创建DAO实现类UserDaoImpl.java,并添加以下代码:
```
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public boolean addUser(User user) {
Session session = sessionFactory.getCurrentSession();
try {
session.save(user);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public User getUserByUsername(String username) {
Session session = sessionFactory.getCurrentSession();
try {
Query<User> query = session.createQuery("from User where username=:username", User.class);
query.setParameter("username", username);
return query.uniqueResult();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
```
在上面的代码中,我们使用了注解@Repository将UserDaoImpl类标记为Spring管理的Bean,并使用注解@Autowired将SessionFactory注入到UserDaoImpl中。在addUser方法中,我们使用Hibernate的API将User对象存储到数据库中;在getUserByUsername方法中,我们使用HQL语句查询数据库中的User对象。
最后,创建JSP页面register.jsp、login.jsp和home.jsp,分别对应注册页面、登录页面和主页。具体实现可以参考以下代码:
register.jsp:
```
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<h1>注册</h1>
<c:if test="${not empty error}">
<p style="color: red;">${error}</p>
</c:if>
<c:if test="${not empty message}">
<p style="color: green;">${message}</p>
</c:if>
<form action="${pageContext.request.contextPath}/register" method="post">
<label>用户名:</label>
<input type="text" name="username" required>
<br>
<label>密码:</label>
<input type="password" name="password" required>
<br>
<input type="submit" value="注册">
</form>
<p><a href="${pageContext.request.contextPath}/login">已有账号?请登录</a></p>
</body>
</html>
```
login.jsp:
```
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<c:if test="${not empty error}">
<p style="color: red;">${error}</p>
</c:if>
<form action="${pageContext.request.contextPath}/login" method="post">
<label>用户名:</label>
<input type="text" name="username" required>
<br>
<label>密码:</label>
<input type="password" name="password" required>
<br>
<input type="submit" value="登录">
</form>
<p><a href="${pageContext.request.contextPath}/register">没有账号?请注册</a></p>
</body>
</html>
```
home.jsp:
```
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<h1>欢迎,${username}!</h1>
<p><a href="${pageContext.request.contextPath}/logout">退出登录</a></p>
</body>
</html>
```
至此,基于Spring MVC、MySQL和Maven的登录注册示例代码就完成了。需要说明的是,以上代码仅供参考学习,具体实现还要根据实际需求进行调整和完善。
阅读全文