SpringMVC basado en anotaciones + plantilla Spring JDBC + ejercicio de demostración JSTL

Referencia de demostración: haga clic para abrir el enlace

Referencia de la anotación de primavera: haga clic para abrir el enlace

Referencia de SpringMVC: haga clic para abrir el enlace


Algunos puntos de conocimiento sobre SpringMVC y anotaciones:

1. Notas sobre <bean>:

@Service se utiliza para anotar componentes de la capa empresarial

@Controller se utiliza para anotar componentes de la capa de control (como la acción en los puntales)

@Repository se utiliza para anotar componentes de acceso a datos, a saber, componentes DAO

@Component se refiere a componentes en general. Cuando los componentes no están bien clasificados, podemos usar esta anotación para anotación.


2. Inyectar comentarios

@Autowired anotación, puede anotar variables de miembros de clase, métodos y constructores para completar el trabajo de ensamblaje automático @Autowired inyecta automáticamente byType .

Pero cuando se usa @Qualifier en combinación, la estrategia de inyección automática cambia de byType a byName

 @Autowired  
 @Qualifier("student")  
 private Student student;  
@Resource se inyecta automáticamente de acuerdo con byName de forma predeterminada. @Resource tiene dos atributos que son más importantes, a saber, el nombre y el tipo. Spring resuelve el atributo de nombre de la anotación @Resource con el nombre del bean y el atributo de tipo se resuelve con el tipo del bean.

3. Anotaciones comunes de SpringMVC

  @Controlador

  Responsable de registrar un bean en el contexto de primavera

  @RequestMapping

  La anotación especifica qué solicitudes de URL puede procesar el controlador

  @RequestCuerpo

  Esta anotación se usa para leer los datos de la parte del cuerpo de la solicitud Request, analizarlos con el HttpMessageConverter configurado por el sistema predeterminado y luego vincular los datos correspondientes al objeto que se devolverá, y luego vincular los datos del objeto devueltos por HttpMessageConverter a el método en el parámetro del controlador

  @ResponseCuerpo

  Esta anotación se utiliza para convertir el objeto devuelto por el método Controller en un formato específico a través de un HttpMessageConverter apropiado, y luego escribirlo en el área de datos del cuerpo del objeto Response.

  @ModelAttribute    

  Use la anotación @ModelAttribute en la definición del método: Spring MVC llamará a los métodos marcados con @ModelAttribute en el nivel de método uno por uno antes de llamar al método de procesamiento de destino

  Use la anotación @ModelAttribute antes de ingresar los parámetros del método: puede obtener el objeto de los datos del modelo oculto del objeto oculto, y luego vincular el parámetro de solicitud al objeto, y luego pasar el parámetro de entrada para agregar el parámetro de entrada del método objetar en el modelo 

  @RequestParam 

  Use @RequestParam en el parámetro de entrada del método de procesamiento para pasar los parámetros de solicitud al método de solicitud

  AthPathVariable

  Vincular marcadores de posición de URL a parámetros de entrada

  @ExceptionHandler

  Anotar en el método, el método se ejecutará cuando ocurra una excepción

  @ControllerAdvice

  Haga de un controlador una clase de manejo de excepciones global. El método anotado con el método @ExceptionHandler en la clase puede manejar todas las excepciones en el controlador


Estructura del directorio de demostración:


exposición de demostración:



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 corresponde al nombre del servlet configurado en 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. fuente de datos de configuración 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. Capa de control.

@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.EstudianteDao

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.EstudianteDaoImpl

@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.Estudiante de mapeo de StudentMapperRow

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.Servicio para estudiantes

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>



Supongo que te gusta

Origin blog.csdn.net/u010857795/article/details/53688494
Recomendado
Clasificación