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>