**实体类:**属性、set get方法、toString方法
实体类Dao接口:
public interface StudentDao {
int insertStudent(Student student);
Student selectById(@Param("studentId") Integer id);
}
实体类Dao.xml:mapper映射、sql语句
实体类Service接口:声名业务方法
实体类Service接口实现类:
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public int addStudent(Student student) {
int rows=studentDao.insertStudent(student);
return rows;
}
@Override
public Student findStudent(Integer id) {
Student student=studentDao.selectById(id);
return student;
}
}
创servlet:
public class AddStudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String strName=request.getParameter("name");
String strAge=request.getParameter("age");
//获取全局作用域对象,确保spring容器对象只创建一次
ServletContext servletContext=getServletContext();
//使用spring提供的工具方法,获取容器对象
WebApplicationContext ctx= WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
StudentService service= (StudentService) ctx.getBean("studentService");
Student student=new Student();
student.setName(strName);
student.setAge(Integer.valueOf(strAge));
service.addStudent(student);
//给用户显示请求的处理结果
request.getRequestDispatcher("/show.jsp").forward(request,response);
}
}
在web.xml中注册servlet和监听
<servlet>
<servlet-name>AddStudentServlet</servlet-name>
<servlet-class>com.bjpowernode.controller.AddStudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddStudentServlet</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
创jsp页面:提交请求参数、显示请求处理结果
jsp01:提交请求参数
<form action="/springWeb/add" method="post">
姓名:<input type="text" name="name"><br/>
年龄:<input type="text" name="age"><br/>
<input type="submit" value="注册学生">
</form>
jsp02:显示请求处理结果
<body>
<p>学生注册成功!!!</p>
</body>
启动tomcat,测试!