<%@ page import="java.util.List" %> <%@ page import="com.example.model.User" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <title>Title</title> <h1>User List</h1> <table border="1"> <tr> <td><strong>Id</strong></td> <td><strong>Username</strong></td> <td><strong>password</strong></td> <td><strong>Email</strong></td> <td><strong>Gender</strong></td> <td><strong>Birthday</strong></td> </tr> <c:choose> <c:when test="${empty userlist}"> <tr><td> <h1>No Order Found.</h1> </td> </c:when> <c:otherwise> <c:forEach var="u" items="${userlist}"> <tr> <td>User :<span><%=u.getUsername()%></span></td> <td>Password :<span><%=u.getPassword()%></span></td> <td>Email :<span><%=u.getEmail()%></span></td> <td>Sex :<span><%=u.getSex()%></span></td> <td>Country :<span><%=u.getCountry()%></span></td> <td> <a href="edit?id=<%=u.getId()%>">Edit</a></td> <td> <a href="delete?id=<%=u.getId()%>">Delete</a></td> </tr> </c:forEach> </c:otherwise> </c:choose> </table> <a href="register">Add User</a>
时间: 2023-08-17 11:48:59 浏览: 90
这是一个 JSP 页面,用于显示用户列表。它引入了 Java 类型的 List 和 User,以及 JSTL 的核心标签库。它通过使用 forEach 标签遍历 userlist 中的用户对象,并显示它们的用户名、密码、电子邮件、性别和国家。如果用户列表为空,则显示“找不到订单”的消息。此外,页面还提供了“添加用户”链接,指向“register”页面。
相关问题
IDEA+Java+JSP+Mysql+Tomcat写一个Web学生信息管理系统
为了写一个基于IDEA、Java、JSP、MySQL和Tomcat的Web学生信息管理系统,你可以按照以下步骤进行:
1. 创建一个Maven项目,项目结构如下:
```
|--src
| |--main
| | |--java
| | | |--com.example.student
| | | | |--db // 数据库相关类
| | | | |--model // 实体类
| | | | |--servlet // Servlet类
| | | |--resources
| | | |--webapp // JSP页面和静态资源
| | |--webapp // Web资源
| |--test
| | |--java
|--pom.xml
```
2. 在MySQL中创建一个名为“student”的数据库,然后创建一个名为“students”的表,表结构如下:
```
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
gender VARCHAR(10) NOT NULL,
age INT NOT NULL,
major VARCHAR(50) NOT NULL,
grade INT NOT NULL
);
```
3. 在db包下创建一个名为“DBUtil”的工具类,用于连接数据库。代码如下:
```java
package com.example.student.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/student";
private static final String USER = "root";
private static final String PASSWORD = "root";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
}
```
4. 在model包下创建一个名为“Student”的实体类,代码如下:
```java
package com.example.student.model;
public class Student {
private int id;
private String name;
private String gender;
private int age;
private String major;
private int grade;
public Student() {
}
public Student(int id, String name, String gender, int age, String major, int grade) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
this.major = major;
this.grade = grade;
}
// getter和setter方法省略
}
```
5. 在servlet包下创建一个名为“StudentServlet”的Servlet类,用于处理前端传来的请求。代码如下:
```java
package com.example.student.servlet;
import com.example.student.db.DBUtil;
import com.example.student.model.Student;
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 java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet(name = "StudentServlet", urlPatterns = "/student")
public class StudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
if ("add".equals(action)) {
// 处理学生信息添加请求
String name = req.getParameter("name");
String gender = req.getParameter("gender");
int age = Integer.parseInt(req.getParameter("age"));
String major = req.getParameter("major");
int grade = Integer.parseInt(req.getParameter("grade"));
Student student = new Student(0, name, gender, age, major, grade);
addStudent(student);
resp.sendRedirect(req.getContextPath() + "/student");
} else if ("edit".equals(action)) {
// 处理学生信息编辑请求
int id = Integer.parseInt(req.getParameter("id"));
String name = req.getParameter("name");
String gender = req.getParameter("gender");
int age = Integer.parseInt(req.getParameter("age"));
String major = req.getParameter("major");
int grade = Integer.parseInt(req.getParameter("grade"));
Student student = new Student(id, name, gender, age, major, grade);
updateStudent(student);
resp.sendRedirect(req.getContextPath() + "/student");
} else if ("delete".equals(action)) {
// 处理学生信息删除请求
int id = Integer.parseInt(req.getParameter("id"));
deleteStudent(id);
resp.sendRedirect(req.getContextPath() + "/student");
} else {
// 处理学生信息列表请求
List<Student> students = getAllStudents();
req.setAttribute("students", students);
req.getRequestDispatcher("/WEB-INF/views/student.jsp").forward(req, resp);
}
}
private List<Student> getAllStudents() {
List<Student> students = new ArrayList<>();
try (Connection conn = DBUtil.getConnection();
Statement stmt = conn.createStatement()) {
String sql = "SELECT * FROM students";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
int age = rs.getInt("age");
String major = rs.getString("major");
int grade = rs.getInt("grade");
Student student = new Student(id, name, gender, age, major, grade);
students.add(student);
}
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
private void addStudent(Student student) {
try (Connection conn = DBUtil.getConnection();
PreparedStatement stmt = conn.prepareStatement("INSERT INTO students (name, gender, age, major, grade) VALUES (?, ?, ?, ?, ?)")) {
stmt.setString(1, student.getName());
stmt.setString(2, student.getGender());
stmt.setInt(3, student.getAge());
stmt.setString(4, student.getMajor());
stmt.setInt(5, student.getGrade());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void updateStudent(Student student) {
try (Connection conn = DBUtil.getConnection();
PreparedStatement stmt = conn.prepareStatement("UPDATE students SET name=?, gender=?, age=?, major=?, grade=? WHERE id=?")) {
stmt.setString(1, student.getName());
stmt.setString(2, student.getGender());
stmt.setInt(3, student.getAge());
stmt.setString(4, student.getMajor());
stmt.setInt(5, student.getGrade());
stmt.setInt(6, student.getId());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void deleteStudent(int id) {
try (Connection conn = DBUtil.getConnection();
PreparedStatement stmt = conn.prepareStatement("DELETE FROM students WHERE id=?")) {
stmt.setInt(1, id);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
6. 在webapp目录下创建一个名为“student.jsp”的JSP页面,用于显示学生信息列表和处理学生信息的添加、编辑和删除等操作。代码如下:
```html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生信息管理系统</title>
</head>
<body>
<h1>学生信息管理系统</h1>
<table border="1">
<tr>
<th>ID</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>专业</th>
<th>年级</th>
<th>操作</th>
</tr>
<c:forEach items="${students}" var="student">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.gender}</td>
<td>${student.age}</td>
<td>${student.major}</td>
<td>${student.grade}</td>
<td>
<a href="${pageContext.request.contextPath}/student?action=edit&id=${student.id}">编辑</a>
<a href="${pageContext.request.contextPath}/student?action=delete&id=${student.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<h2>添加学生信息</h2>
<form method="post" action="${pageContext.request.contextPath}/student?action=add">
<div>
<label for="name">姓名:</label>
<input type="text" id="name" name="name" required>
</div>
<div>
<label for="gender">性别:</label>
<input type="radio" id="gender" name="gender" value="男" required>男
<input type="radio" id="gender" name="gender" value="女" required>女
</div>
<div>
<label for="age">年龄:</label>
<input type="number" id="age" name="age" required>
</div>
<div>
<label for="major">专业:</label>
<input type="text" id="major" name="major" required>
</div>
<div>
<label for="grade">年级:</label>
<input type="number" id="grade" name="grade" required>
</div>
<div>
<button type="submit">添加</button>
</div>
</form>
<c:if test="${not empty param.id}">
<h2>编辑学生信息</h2>
<form method="post" action="${pageContext.request.contextPath}/student?action=edit&id=${param.id}">
<div>
<label for="name">姓名:</label>
<input type="text" id="name" name="name" value="${student.name}" required>
</div>
<div>
<label for="gender">性别:</label>
<input type="radio" id="gender" name="gender" value="男" ${student.gender=='男'?'checked':''} required>男
<input type="radio" id="gender" name="gender" value="女" ${student.gender=='女'?'checked':''} required>女
</div>
<div>
<label for="age">年龄:</label>
<input type="number" id="age" name="age" value="${student.age}" required>
</div>
<div>
<label for="major">专业:</label>
<input type="text" id="major" name="major" value="${student.major}" required>
</div>
<div>
<label for="grade">年级:</label>
<input type="number" id="grade" name="grade" value="${student.grade}" required>
</div>
<div>
<button type="submit">保存</button>
</div>
</form>
</c:if>
</body>
</html>
```
7. 在pom.xml文件中添加以下依赖:
```xml
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
```
8. 在Tomcat中部署该项目,启动Tomcat服务,通过浏览器访问项目的根路径,即可看到学生信息管理系统的页面。
以上是一个基本的实现过程,具体实现过程中还需要根据实际情况进行相应的调整和优化。
用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 启动应用
详见方式一。
阅读全文