package com.vilicode.filter; import com.vilicode.bean.User; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebFilter(filterName = "AdminFilter",urlPatterns = "/admin/*") public class AdminFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse requestp = (HttpServletResponse)resp; User u = (User) request.getSession().getAttribute("user"); if(u==null || u.isAdmin()==false) { requestp.sendRedirect("../index.action"); }else { // pass the request along the filter chain chain.doFilter(req, resp); } } public void init(FilterConfig config) throws ServletException { } }
时间: 2024-04-28 12:25:44 浏览: 121
这是一个 Java Servlet 中的过滤器,用于拦截访问 "/admin/*" 路径下的请求。它检查 Session 中是否存在一个名为 "user" 的属性,如果该属性不存在或者对应的用户不是管理员,则该请求会被重定向到 "../index.action" 路径下。如果用户是管理员,则该请求会通过,继续向下传递。
相关问题
1)使用Eclipse和Maven创建Web类型的工程; (2)在MysQL数据库中创建数据库,数据库名称为:0a,数据库编码使用UTF 8,表名为:tuser,宇段为:iid(int类型,主键)、v_name(varchar(20)字符串 类型,存储登录名称)、v_pass(varchar(20)字符串类型,存储密码),其中登录 名称和密码均使用英文,可以事先在该表中录入相关的登录信息。 (3)配置数据库连接池; (4)分别设计以下jSP页面: ①login.jsp:用户登录页面 ②main.jsp:系统后台首页 (5)servlet程序实现中央控制器,接收用户请求; (6)设计自定义类实现登录验证,类名自定义; (7)设计Filter过滤器,用于实现拦截非法用户访问
好的,那么接下来我将详细介绍如何按照你提供的步骤,使用Eclipse和Maven创建Web类型的工程,并实现登录验证、跳转页面以及拦截非法用户访问等功能。
1. 创建Web工程
首先,我们需要在Eclipse中创建一个Maven工程,具体步骤如下:
(1)打开Eclipse,选择“File” -> “New” -> “Maven Project”。
(2)在弹出的“New Maven Project”对话框中,选择“Create a simple project”选项,然后点击“Next”。
(3)在“New Maven Project”对话框中,填写Group Id、Artifact Id和Version等信息,然后点击“Finish”按钮。
(4)创建完成后,在Eclipse的“Project Explorer”视图中可以看到新建的Maven工程。
2. 创建数据库和表
在MySQL中创建名为“0a”的数据库,并创建名为“tuser”的表,表中包含iid(int类型,主键)、v_name(varchar(20)字符串类型,存储登录名称)、v_pass(varchar(20)字符串类型,存储密码)三个字段,其中登录名称和密码均使用英文,并录入相关的登录信息。
3. 配置数据库连接池
在Maven工程中,我们可以使用JDBC连接池管理数据库连接。具体步骤如下:
(1)在pom.xml文件中添加以下依赖项:
```
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
```
(2)在src/main/resources目录下创建druid.properties文件,配置以下信息:
```
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/0a?useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
initialSize=5
maxActive=10
```
其中,driverClassName、url、username和password分别为数据库驱动名称、数据库连接地址、数据库用户名和密码;initialSize和maxActive分别为初始连接数和最大连接数。
(3)创建一个名为DBCPUtils的类,用于创建和管理数据库连接池,代码如下:
```
package com.example.utils;
import java.sql.Connection;
import java.sql.SQLException;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class DBCPUtils {
private static DruidDataSource dataSource;
static {
try {
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(PropertiesUtils.load("druid.properties"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static void closeConnection(Connection conn) {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
该类使用Druid连接池创建数据库连接,并提供了获取连接和关闭连接的方法。
4. 设计login.jsp页面
login.jsp页面包含用户名和密码输入框以及登录按钮,用户输入用户名和密码后点击登录按钮,将请求通过Servlet程序处理。具体代码如下:
```
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<form method="post" action="login">
<label>Username:</label>
<input type="text" name="username"><br>
<label>Password:</label>
<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
```
5. 设计自定义类实现登录验证
我们可以创建一个名为UserDao的类,用于实现登录验证。具体代码如下:
```
package com.example.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.example.bean.User;
import com.example.utils.DBCPUtils;
public class UserDao {
public User getUser(String username, String password) {
User user = null;
String sql = "SELECT * FROM tuser WHERE v_name=? AND v_pass=?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBCPUtils.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
if (rs.next()) {
user = new User();
user.setId(rs.getInt("iid"));
user.setUsername(rs.getString("v_name"));
user.setPassword(rs.getString("v_pass"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBCPUtils.closeConnection(conn);
try {
if (pstmt != null) {
pstmt.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return user;
}
}
```
该类使用JDBC连接池获取数据库连接,并根据用户名和密码查询数据库中的记录,如果查询结果不为空,则验证通过,否则验证失败。
6. 设计Servlet程序作为中央控制器
我们可以创建一个名为LoginServlet的类,用于接收用户请求,调用自定义类进行登录验证,如果验证通过,则跳转至系统后台首页main.jsp,同时在页面上显示“欢迎,xxx”,其中xxx为系统登录名称;如果验证失败,则重新跳转至登录页面login.jsp,同时通过弹出窗口的方式显示“用户名或密码错误,请确认后重试!”的提示信息。具体代码如下:
```
package com.example.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.example.bean.User;
import com.example.dao.UserDao;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao = new UserDao();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userDao.getUser(username, password);
if (user != null) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
response.sendRedirect(request.getContextPath() + "/main.jsp");
} else {
String message = "用户名或密码错误,请确认后重试!";
request.setAttribute("message", message);
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
}
```
该类根据请求中的用户名和密码调用自定义类进行登录验证,并根据验证结果进行相应处理,如果验证通过,则将用户信息保存至Session中,然后跳转至系统后台首页main.jsp;如果验证失败,则将错误信息保存至请求中,然后重新跳转至登录页面login.jsp。
7. 设计main.jsp页面
main.jsp页面显示系统后台首页,并在页面上显示“欢迎,xxx”,其中xxx为系统登录名称。具体代码如下:
```
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Main Page</title>
</head>
<body>
<h1>Welcome, <%= session.getAttribute("user").getUsername() %>!</h1>
<p>This is the main page of the system.</p>
</body>
</html>
```
8. 设计Filter过滤器
我们可以创建一个名为LoginFilter的过滤器,用于实现拦截非法用户访问。具体代码如下:
```
package com.example.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter(urlPatterns = {"/main.jsp"})
public class LoginFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession();
if (session.getAttribute("user") != null) {
chain.doFilter(httpRequest, httpResponse);
} else {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
}
}
public void destroy() {
}
}
```
该过滤器拦截系统后台首页main.jsp的访问,检查Session中是否存在用户登录信息,如果用户已经登录,则允许访问;否则,强制跳转至登录页面login.jsp。
以上就是按照你提供的步骤,使用Eclipse和Maven创建Web类型的工程,并实现登录验证、跳转页面以及拦截非法用户访问等功能的详细步骤。
用idea写 用两种方式整合SSM框架 要求:1.以纯注解的方式整合SSM框架
好的,以下是两种方式整合SSM框架的步骤:
## 1. 整合SSM框架方式一(纯注解方式)
### 1.1 创建Maven项目
在IDEA中创建一个Maven项目,选择Web应用程序类型。
### 1.2 导入SSM框架依赖
在pom.xml文件中添加以下依赖:
```xml
<!-- Spring框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.8</version>
</dependency>
<!-- Spring MVC框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
<!-- MyBatis框架 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- MyBatis-Spring框架 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- JSP API -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!-- JSTL标签库 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
```
### 1.3 配置web.xml文件
在src/main/webapp/WEB-INF目录下创建web.xml文件,并添加以下配置:
```xml
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置SpringMVC的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 配置DispatcherServlet映射 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置字符集过滤器 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
### 1.4 配置Spring配置文件
在src/main/resources目录下创建spring-context.xml文件,并添加以下配置:
```xml
<!-- 配置数据源 -->
<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?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- 配置MyBatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.example.demo.entity"/> <!-- 指定实体类路径 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/> <!-- 指定Mapper映射文件路径 -->
</bean>
<!-- 配置Mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.demo.mapper"/> <!-- 指定Mapper接口所在的包 -->
</bean>
```
### 1.5 配置SpringMVC配置文件
在src/main/resources目录下创建spring-mvc.xml文件,并添加以下配置:
```xml
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置静态资源映射 -->
<mvc:resources mapping="/static/**" location="/static/"/>
<!-- 配置扫描Controller -->
<context:component-scan base-package="com.example.demo.controller"/>
```
### 1.6 编写Controller
在src/main/java目录下创建com.example.demo.controller包,并在该包下创建UserController.java文件,编写以下代码:
```java
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
public String list(Model model) {
List<User> userList = userService.findAll();
model.addAttribute("userList", userList);
return "user/list";
}
@GetMapping("/add")
public String add() {
return "user/add";
}
@PostMapping("/save")
public String save(User user) {
userService.save(user);
return "redirect:/user/list";
}
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") Long id, Model model) {
User user = userService.findById(id);
model.addAttribute("user", user);
return "user/edit";
}
@PostMapping("/update")
public String update(User user) {
userService.update(user);
return "redirect:/user/list";
}
@GetMapping("/delete/{id}")
public String delete(@PathVariable("id") Long id) {
userService.delete(id);
return "redirect:/user/list";
}
}
```
### 1.7 编写Service
在src/main/java目录下创建com.example.demo.service包,并在该包下创建UserService.java文件,编写以下代码:
```java
package com.example.demo.service;
import com.example.demo.entity.User;
import java.util.List;
public interface UserService {
List<User> findAll();
User findById(Long id);
void save(User user);
void update(User user);
void delete(Long id);
}
```
在com.example.demo.service包下创建UserServiceImpl.java文件,编写以下代码:
```java
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
@Override
public User findById(Long id) {
return userMapper.findById(id);
}
@Override
public void save(User user) {
userMapper.save(user);
}
@Override
public void update(User user) {
userMapper.update(user);
}
@Override
public void delete(Long id) {
userMapper.delete(id);
}
}
```
### 1.8 编写Mapper
在src/main/java目录下创建com.example.demo.mapper包,并在该包下创建UserMapper.java文件,编写以下代码:
```java
package com.example.demo.mapper;
import com.example.demo.entity.User;
import java.util.List;
public interface UserMapper {
List<User> findAll();
User findById(Long id);
void save(User user);
void update(User user);
void delete(Long id);
}
```
在com.example.demo.mapper包下创建UserMapper.xml文件,编写以下代码:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="userMap" type="com.example.demo.entity.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="age" property="age"/>
</resultMap>
<select id="findAll" resultMap="userMap">
SELECT * FROM user
</select>
<select id="findById" resultMap="userMap">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="save">
INSERT INTO user(username, password, age) VALUES(#{username}, #{password}, #{age})
</insert>
<update id="update">
UPDATE user SET username = #{username}, password = #{password}, age = #{age} WHERE id = #{id}
</update>
<delete id="delete">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
```
### 1.9 编写JSP页面
在src/main/webapp/WEB-INF/views/user目录下创建list.jsp、add.jsp和edit.jsp文件,编写以下代码:
list.jsp:
```html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Username</th>
<th>Password</th>
<th>Age</th>
<th>Actions</th>
</tr>
<c:forEach var="user" items="${userList}">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
<td>${user.age}</td>
<td>
<a href="/user/edit/${user.id}">Edit</a>
<a href="/user/delete/${user.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
<br>
<a href="/user/add">Add User</a>
</body>
</html>
```
add.jsp:
```html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add User</title>
</head>
<body>
<h1>Add User</h1>
<form action="/user/save" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="number" name="age"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Save"></td>
</tr>
</table>
</form>
</body>
</html>
```
edit.jsp:
```html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit User</title>
</head>
<body>
<h1>Edit User</h1>
<form action="/user/update" method="post">
<input type="hidden" name="id" value="${user.id}">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" value="${user.username}"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" value="${user.password}"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="number" name="age" value="${user.age}"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
```
### 1.10 启动应用
在IDEA中启动应用,访问http://localhost:8080/user/list即可查看用户列表。
## 2. 整合SSM框架方式二(Java配置方式)
### 2.1 创建Maven项目
在IDEA中创建一个Maven项目,选择Web应用程序类型。
### 2.2 导入SSM框架依赖
详见方式一。
### 2.3 配置WebInitializer
在src/main/java目录下创建com.example.demo.config包,并在该包下创建WebInitializer.java文件,编写以下代码:
```java
package com.example.demo.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
```
### 2.4 配置WebConfig
在src/main/java目录下创建com.example.demo.config包,并在该包下创建WebConfig.java文件,编写以下代码:
```java
package com.example.demo.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.sql.DataSource;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.demo.controller")
@MapperScan(basePackages = "com.example.demo.mapper")
@PropertySource("classpath:jdbc.properties")
public class WebConfig implements WebMvcConfigurer {
@Autowired
private Environment env;
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
return sessionFactory.getObject();
}
}
```
### 2.5 配置jdbc.properties
在src/main/resources目录下创建jdbc.properties文件,编写以下代码:
```
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123456
```
### 2.6 编写Controller
详见方式一。
### 2.7 编写Service
详见方式一。
### 2.8 编写Mapper
详见方式一。
### 2.9 编写JSP页面
详见方式一。
### 2.10 启动应用
详见方式一。
阅读全文