**
一.mvc是什么?
**
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。
在我的理解中,简单的说,mvc是一种思想,是将前端页面(界面),用户交互(业务逻辑),后端数据处理(数据),分离的思想。
***在我的程序中,我是这样用的:***
二.loc和bean
最大的难点在于loc和bean的概念,在这个链接里,某大佬有了很清晰的阐述:
https://www.awaimai.com/2596.html
1.在实践中,首先需要在web.xml和资源文件/webapp中创建新的xml来进行配置。
我在资源文件中新建了xml
- web.xml中主要是使用DispatcherServlet,并且把新建的xml文件的地址设置为contextConfigLocation的值。
代码如下:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 在app-servlet.xml中,我设置了对三个代码包的扫描
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="class12.controller"/>
<context:component-scan base-package="class12.model"/>
<context:component-scan base-package="class12.jdbc"/>
</beans>
- 在app-context.xml中,用loc的思想,将数据库驱动设为了bean
<bean id="datasource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/school"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
2.在java包里的使用
- controller
@Controller
public class addstudent extends HttpServlet {
@RequestMapping(value = "/addstudent",method = RequestMethod.POST)
protected String addstudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");//设置编码,以防表单提交的内容乱码
student st = new student();
st.setId(req.getParameter("id"));
st.setName(req.getParameter("name"));
Date date = new Date();
st.setCreateTime(date);
StudentJdbc.addstudent(st);
return "allstudent.jsp";
}
}
- model
简单的将三个model类注册成了bean,且规定prototype,因为之后在方法selectall中使用,每次使用都储存不同的实例。
@Component
@Scope("prototype")
关于bean的scope可以见这篇文章:
https://www.cnblogs.com/mmzs/p/10411269.html
- jdbc
在jdbc中有两个地方使用了bean
(1)使用bean代替了之前使用的new homework
//全局变量
private static ApplicationContext ct;
static{
ct=new AnnotationConfigApplicationContext(homework.class);
}
//这是在selectall方法中的语句,摘出来的
homework hw =(homework)ct.getBean("homework");
(2)数据库驱动改成了在app-context.xml中管理的bean
ApplicationContext ac = new ClassPathXmlApplicationContext("app-context.xml");
DataSource ds = (DataSource)ac.getBean("datasource");
List<homework> list = new ArrayList<>();
try(Connection connection = ds.getConnection()) {
……
}
三.整个代码具体流程
- 前端web页面
jsp页面的用法不必多说,展示其中一个页面:
// An highlighted block
<div align="center">
<h2>添加作业</h2>
<form action="${pageContext.request.contextPath}/AddStudentHomeworkServlet" method="post">
<table style="line-height: 40px">
<tr>
<th>学号:</th>
<td><input type="text" name="id" maxlength="30" size="50" required></td>
</tr>
<tr>
<th>作业id:</th>
<td><input type="text" name="hwid" maxlength="30" size="50" required></td>
</tr>
<tr>
<th>作业名称:</th>
<td><input type="text" name="hwname" maxlength="30" size="50" required></td>
</tr>
<tr>
<th>作业内容:</th>
<td><input type="text" name="content" maxlength="30" size="50" required></td>
</tr>
<tr align="center">
<td><input type="submit" value="添加作业"> </td>
</tr>
</table>
</form>
</div>
- controller
在这里用到了bean,接受了前端数据,建了实例并且传到jdbc类进行数据操作
@Controller
public class addstudent extends HttpServlet {
@RequestMapping(value = "/addstudent",method = RequestMethod.POST)
protected String addstudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");//设置编码,以防表单提交的内容乱码
student st = new student();
st.setId(req.getParameter("id"));
st.setName(req.getParameter("name"));
Date date = new Date();
st.setCreateTime(date);
StudentJdbc.addstudent(st);
return "allstudent.jsp";
}
}
- jdbc
接收controller传过来的实例,并启动数据库插入数据。
在前端要展示所有数据时候,selectall方法启动数据库并且用bean创建实例,存入list,在前端展示list。
@Configuration
public class StudentHomeworkJdbc {
private static ApplicationContext ct;
static{
ct=new AnnotationConfigApplicationContext(StudentHomework.class);
}
public static void main(String[] args) {
List<StudentHomework> list = selectAll();
for (StudentHomework sh : list){
System.out.println(sh.getHomeworkContent());
}
}
public static boolean addStudentHomework(StudentHomework sh){
String sqlString = "insert into s_student_homework (student_id,homework_id,homework_title,homework_content,create_time) values(?,?,?,?,?)";
ApplicationContext ac = new ClassPathXmlApplicationContext("app-context.xml");
DataSource ds = (DataSource)ac.getBean("datasource");
int resultSet = 0;
try (Connection connection = ds.getConnection()) {
try (PreparedStatement ps = connection.prepareStatement(sqlString)) {
ps.setString(1,sh.getStudentId());
ps.setString(2,sh.getHomeworkId());
ps.setString(3,sh.getHomeworkTitle());
ps.setString(4,sh.getHomeworkContent());
ps.setTimestamp(5,new Timestamp(sh.getCreateTime().getTime()));
resultSet = ps.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet > 0;
}
public static List<StudentHomework> selectAll(){
String sqlString = "SELECT * FROM s_student_homework";
ApplicationContext ac = new ClassPathXmlApplicationContext("app-context.xml");
DataSource ds = (DataSource)ac.getBean("datasource");
List<StudentHomework> list = new ArrayList<>();
try(Connection connection = ds.getConnection()) {
try(Statement statement = connection.createStatement()){
try(ResultSet resultSet = statement.executeQuery(sqlString)){
// 获取执行结果
while (resultSet.next()){
StudentHomework sh =(StudentHomework) ct.getBean("StudentHomework");
sh.setId(resultSet.getLong("id"));
sh.setStudentId(resultSet.getString("student_id"));
sh.setHomeworkId(resultSet.getString("homework_id"));
sh.setHomeworkTitle(resultSet.getString("homework_title"));
sh.setHomeworkContent(resultSet.getString("homework_content"));
sh.setCreateTime(resultSet.getTimestamp("create_time"));
list.add(sh);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
四.github
https://github.com/Xinchan233/javaee