本文章是基于整合spring和mybatis做的后续优化,大家可以先查看我的另一篇文章来整合框架
1.构建项目 maven-archetype-webapp2.将整合的spring和mybatis的pom.xml里的内容复制粘贴过来,再添加servlet依赖和jsp依赖
<!-- servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- jsp依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
3.将java和resources文件全部复制到main文件夹下
4.定义index.jsp页面
<html>
<body>
<p>注册学生</p>
<form action="regservlet" method="post">
<table>
<tr>
<td>id</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>name<td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>email</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>age</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td><input type="submit" value="提交" ></td>
<td><input type="reset" value="清空"></td>
</tr>
</table>
</form>
</body>
</html>
5.定义RegisterServlet并重写doGet方法
//接收请求参数
String strName=request.getParameter("name");
String strAge=request.getParameter("age");
//使用容器获取service对象
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService studentService=(StudentService) ac.getBean("studentService");//后面跟实现类的id
//调用service的方法并传值
Student stu=new Student();
Integer strage=Integer.parseInt(strAge);
stu.setName(strName);
stu.setAge(strage);
studentService.addStudent(stu);
//请求转发调用result.jsp
request.getRequestDispatcher("/result.jsp").forward(request,response);
}
6.servlet中提到的result.jsp也要写一个
<font size="20px" color="red">注册成功</font>
7.web.xml注册servlet
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>zjc.javaweb.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>regservlet</url-pattern>
</servlet-mapping>
</web-app>