Demo reference: click to open the link
Spring annotation reference: click to open the link
SpringMVC reference: click to open the link
Some knowledge points about SpringMVC and annotations:
1. Notes on <bean>:
@Service is used to annotate business layer components
@Controller is used to annotate control layer components (such as action in struts)
@Repository is used to annotate data access components, namely DAO components
@Component refers to components in general. When components are not well classified, we can use this annotation for annotation.
2. Inject comments
@Autowired annotation, it can annotate class member variables, methods and constructors to complete the automatic assembly work @Autowired automatically injects byType .
But when @Qualifier is used in combination, the automatic injection strategy is changed from byType to byName
@Autowired
@Qualifier("student")
private Student student;
@Resource is automatically injected according to byName by default. @Resource has two attributes that are more important, namely name and type. Spring resolves the name attribute of the @Resource annotation to the name of the bean, and the type attribute resolves to the type of the bean.
3. SpringMVC common annotations
@Controller
Responsible for registering a bean to the spring context
@RequestMapping
Annotation specifies which URL requests can be processed by the controller
@RequestBody
This annotation is used to read the body part data of the Request request, parse it with the HttpMessageConverter configured by the system default, and then bind the corresponding data to the object to be returned, and then bind the object data returned by the HttpMessageConverter to the method in the controller Parameter
@ResponseBody
This annotation is used to convert the object returned by the Controller method to the specified format through an appropriate HttpMessageConverter, and then write it to the body data area of the Response object
@ModelAttribute
Use the @ModelAttribute annotation on the method definition: Spring MVC will call the methods marked with @ModelAttribute at the method level one by one before calling the target processing method
Use the @ModelAttribute annotation before entering the method parameters: you can get the object from the hidden model data from the hidden object, and then bind the request parameter-to the object, and then pass in the input parameter to add the method input parameter object to In the model
@RequestParam
Use @RequestParam at the input parameter of the processing method to pass request parameters to the request method
AthPathVariable
Bind URL placeholders to input parameters
@ExceptionHandler
Annotate to the method, the method will be executed when an exception occurs
@ControllerAdvice
Make a Contoller a global exception handling class. The method annotated with the @ExceptionHandler method in the class can handle all exceptions in the Controller
Demo directory structure:
demo exhibition:
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 corresponds to the servlet name configured in web.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">
<!-- 启用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 configuration data source.
<?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. Control layer.
@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 mapping 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>