基於註解的SpringMVC+Spring JDBC template+JSTL-demo練習
Spring註解參考:點選開啟連結
SpringMVC參考:點選開啟連結
一些關於SpringMVC和註解的知識點:
1.<bean>的註解:
@Service用於標註業務層元件
@Controller用於標註控制層元件(如struts中的action)
@Repository用於標註資料訪問元件,即DAO元件
@Component泛指元件,當元件不好歸類的時候,我們可以使用這個註解進行標註。
2.注入註解
@Autowired 註釋,它可以對類成員變數、方法及建構函式進行標註,完成自動裝配的工作@Autowired 按 byType 自動注入。
但是 @Qualifier 結合使用時,自動注入的策略就從 byType 轉變成 byName 了
@Autowired
@Qualifier("student")
private Student student;
@Resource 預設按 byName 自動注入。@Resource 有兩個屬性是比較重要的,分別是 name 和 type,Spring 將 @Resource 註釋的 name 屬性解析為 Bean 的名字,而 type 屬性則解析為 Bean 的型別。3.SpringMVC常用註解
@Controller
負責註冊一個bean 到spring 上下文中
@RequestMapping
註解為控制器指定可以處理哪些 URL 請求
@RequestBody
該註解用於讀取Request請求的body部分資料,使用系統預設配置的HttpMessageConverter進行解析,然後把相應的資料繫結到要返回的物件上 ,再把HttpMessageConverter返回的物件資料繫結到 controller中方法的引數上
@ResponseBody
該註解用於將Controller的方法返回的物件,通過適當的HttpMessageConverter轉換為指定格式後,寫入到Response物件的body資料區
@ModelAttribute
在方法定義上使用 @ModelAttribute 註解:Spring MVC 在呼叫目標處理方法前,會先逐個呼叫在方法級上標註了@ModelAttribute 的方法
在方法的入參前使用 @ModelAttribute 註解:可以從隱含物件中獲取隱含的模型資料中獲取物件,再將請求引數 –繫結到物件中,再傳入入參將方法入參物件新增到模型中
@RequestParam
在處理方法入參處使用 @RequestParam 可以把請求參 數傳遞給請求方法
@PathVariable
繫結 URL 佔位符到入參
@ExceptionHandler
註解到方法上,出現異常時會執行該方法
@ControllerAdvice
使一個Contoller成為全域性的異常處理類,類中用@ExceptionHandler方法註解的方法可以處理所有Controller發生的異常
demo目錄結構:
demo展示:
1.web.xml。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Student</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
<!-- <load-on-startup>1</load-on-startup> -->
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring配置 -->
<!-- ====================================== -->
<!--監聽器 自動裝配ApplicationContext的配置資訊-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 指定Spring Bean的配置檔案所在目錄。預設配置在WEB-INF目錄下 自動裝配ApplicationContext的配置資訊-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<!-- 亂碼問題 -->
<filter>
<filter-name>SpringEncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SpringEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.springmvc-servlet.xml 與之前web.xml配置的servlet名字對應。
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 啟用spring mvc 註解 -->
<context:annotation-config />
<!-- scan the package and the sub package -->
<context:component-scan base-package="com.example.controller"/>
<context:component-scan base-package="com.example.dao.impl"/>
<context:component-scan base-package="com.example.service.impl"/>
<!-- don't handle the static resource -->
<mvc:default-servlet-handler />
<!-- if you use annotation you must configure following setting -->
<mvc:annotation-driven />
<!-- 完成請求和註解POJO的對映 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- configure the InternalResourceViewResolver 一種試圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 字首 -->
<property name="prefix" value="/jsp/"/>
<!-- 字尾 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
3.applicationContext.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- declare datasource bean -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/student" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
</beans>
4.控制層。
@Controller
public class StudentController{
@Autowired
StudentService service;
@RequestMapping(value="jsp/showAdd")
public ModelAndView showAddStudent(@ModelAttribute Student student){
Map<String, Object> map = getCheckButton();
return new ModelAndView("addStudent","map",map);
}
@RequestMapping(value="jsp/add")
public ModelAndView addStudent(@ModelAttribute Student student){
if(student.getName() != "" && student.getSex() != "" && student.getInstitute() != "" && student.getDate() != "" ) {
service.addStudent(student);
}
return new ModelAndView("redirect:show");
}
@RequestMapping(value="jsp/show" )
public ModelAndView queryStudent(){
List<Student> studentlList = service.getStudentList();
return new ModelAndView("queryStudent","studentList",studentlList);
}
@RequestMapping(value="jsp/delete")
public ModelAndView deleteStudent(@RequestParam String id){
service.deleteStudent(id);
return new ModelAndView("redirect:show");
}
@RequestMapping(value="jsp/edit")
public ModelAndView editStudent(@RequestParam String id,@ModelAttribute Student student){
Student student2 = service.queryOneStudent(id);
Map<String, Object> map = getCheckButton();
map.put("student2", student2);
return new ModelAndView("changeStudent","map",map);
}
@RequestMapping(value="jsp/update")
public ModelAndView updateStudent(@ModelAttribute Student student){
service.changeStudent(student);
return new ModelAndView("redirect:show");
}
public Map<String,Object> getCheckButton(){
List<String> gendarList = new ArrayList<>();
gendarList.add("male");
gendarList.add("female");
List<String> instituteList = new ArrayList<>();
instituteList.add("計算機與軟體學院");
instituteList.add("人文學院");
instituteList.add("外國語學院");
instituteList.add("藝術學院");
instituteList.add("機械學院");
Map<String, Object> map = new HashMap<>();
map.put("gendarList", gendarList);
map.put("instituteList", instituteList);
return map;
}
}
5.StudentDao
public interface StudentDao{
public void addStudent(Student student);
public void deleteStudent(String id);
public Student queryOneStudent(String id);
public void changeStudent(Student student);
public List<Student> getStudentList();
}
6.StudentDaoImpl
@Repository("studentDao")
public class StudentDaoImpl implements StudentDao{
public StudentDaoImpl() {
super();
// TODO Auto-generated constructor stub
}
@Autowired
DataSource dataSource;
@Override
public void addStudent(Student student) {
// TODO Auto-generated method stub
String sql = "insert into student.student" +"(name,sex,institute,birth) values (?,?,?,?)";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sql, new Object[]{
student.getName(),student.getSex(),student.getInstitute(),student.getDate()
});
}
@Override
public void deleteStudent(String id) {
// TODO Auto-generated method stub
String sql = "delete from student.student where id=" + id;
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sql);
}
@Override
public Student queryOneStudent(String id) {
// TODO Auto-generated method stub
String sql = "select * from student.student where id=" + id;
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Student> list = jdbcTemplate.query(sql,new StudentMapperRow());
return list.get(0);
}
@Override
public void changeStudent(Student student) {
// TODO Auto-generated method stub
String sql = "update student.student set name=?,sex=?,institute=?,birth=? where id=?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sql, new Object[]{student.getName(),student.getSex(),student.getInstitute(),student.getDate(),student.getId()});
}
@Override
public List<Student> getStudentList() {
// TODO Auto-generated method stub
List<Student> list = new ArrayList<Student>();
String sql = "select * from student.student";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
list = jdbcTemplate.query(sql,new StudentMapperRow());
return list;
}
}
7.StudentMapperRow 對映student
public class StudentMapperRow implements RowMapper<Student> {
@Override
public Student mapRow(ResultSet arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
Student student = new Student();
student.setId(Integer.parseInt(arg0.getString(1)));
student.setName(arg0.getString(2));
student.setSex(arg0.getString(3));
student.setInstitute(arg0.getString(5));
student.setDate(arg0.getString(4));
return student;
}
}
8.StudentService
public interface StudentService{
public void addStudent(Student student);
public void deleteStudent(String id);
public Student queryOneStudent(String id);
public void changeStudent(Student student);
public List<Student> getStudentList();
}
9.StudentServiceImpl
@Service("studentService")
public class StudentServiceImpl implements StudentService{
@Resource(name="studentDao")
private StudentDao studentDao;
@Override
public void addStudent(Student student) {
studentDao.addStudent(student);
}
@Override
public void deleteStudent(String id) {
// TODO Auto-generated method stub
studentDao.deleteStudent(id);
}
@Override
public Student queryOneStudent(String id) {
// TODO Auto-generated method stub
return studentDao.queryOneStudent(id);
}
@Override
public void changeStudent(Student student) {
// TODO Auto-generated method stub
studentDao.changeStudent(student);
}
@Override
public List<Student> getStudentList() {
// TODO Auto-generated method stub
return studentDao.getStudentList();
}
}
10.Student
public class Student{
private int id;
private String name;
private String sex;
private String institute;
private String date;
public Student(){
}
public Student(int id,String name, String sex, String institute, String date) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.institute = institute;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getInstitute() {
return institute;
}
public void setInstitute(String institute) {
this.institute = institute;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex
+ ", institute=" + institute + ", date=" + date + "]";
}
}
11.addStudent.jsp
<form:form action="add" method="post" modelAttribute="student">
student name:<form:input path="name"/><br>
student sex:<form:radiobuttons path="sex" items="${map.gendarList }"/><br>
student institute:<form:select path="institute" items="${map.instituteList }"></form:select><br>
student date:<input type="date" name="date"><br>
<input type="submit" value="submit">
<input type="reset" value="reset">
</form:form>
12.changeStudent.jsp
<form:form action="update" method="post" modelAttribute="student">
student id:<form:input path="id" readonly="true" value="${map.student2.id }" /><br>
student name:<form:input path="name" value="${map.student2.name }"/><br>
student sex:<c:forEach items="${map.gendarList }" var="gendar">
<c:choose>
<c:when test="${map.student2.sex eq gendar }">
<input type="radio" name="sex" value="${gendar} " checked="checked"> ${gendar}
</c:when>
<c:otherwise>
<input type="radio" name="sex" value="${gendar} " > ${gendar}
</c:otherwise>
</c:choose>
</c:forEach><br>
student institute:<select name="institute"><c:forEach items="${map.instituteList }" var="institute">
<c:choose>
<c:when test="${map.student2.institute eq institute }">
<option selected="selected" value="${institute }">${institute }</option>
</c:when>
<c:otherwise>
<option value="${institute }">${institute }</option>
</c:otherwise>
</c:choose>
</c:forEach></select><br>
student date:<input type="date" name="date" value="${map.student.date }"><br>
<input type="submit" value="submit">
<input type="reset" value="reset">
</form:form>
13.queryStudent.jsp
<table border="1px">
<tr>
<td>student id</td>
<td>student name</td>
<td>student sex</td>
<td>student institute</td>
<td>student date</td>
<td>edit student</td>
<td>delete student</td>
</tr>
<c:forEach items="${studentList}" var="list">
<tr>
<td>${list.id}</td>
<td>${list.name }</td>
<td>${list.sex }</td>
<td>${list.institute }</td>
<td>${list.date }</td>
<td><a href="<c:url value="edit?id=${list.id}"/>">edit</a></td>
<td><a href="<c:url value="delete?id=${list.id}"/>">delete</a></td>
</tr>
</c:forEach>
</table>
<a href="showAdd">add student</a>