5. 自实现SpringMVC

1.源码下载地址

源码下载地址

2.代码架构

  1. com.ys.annotation包下是自定义注解
  2. com.ys.controller包下是自定义controller
  3. com.ys.service包下是自定义service
  4. com.ys.servlet包下是自定义servlet,类似于DispatcherServlet,是核心类
    在这里插入图片描述

2.1 web.xml配置

这里注意要让所有的请求通过,所以设置为/,并且设置,让程序加载时就启动servlet在这里插入图片描述

2.2 引包

pom.xml中仅需引入servlet的jar包
在这里插入图片描述

2.3 自定义注解类

仿照springmvc注解做简单模仿,五个注解均仅有一个value方法,除定义的注解位置不同,无其他区别
在这里插入图片描述

2.4 自定义Controller类

@MyController
@MyRequestMapping("/my")
public class TestController{
	@MyAutowired(value = "testService")
	private TestService testService;

	@MyRequestMapping("/ok")
	public void updateUser(HttpServletRequest request,HttpServletResponse response,
						@MyRequestParam("name") String name,
						@MyRequestParam("password") String password){
		String user = testService.updateUser(name,password);
		try {
			response.getWriter().write(user);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@MyRequestMapping("/no")
	public void noUser(HttpServletRequest request,HttpServletResponse response,
						@MyRequestParam("name") String name,
						@MyRequestParam("password") String password){
		String user = testService.updateUser(name,password);
		try {
			response.getWriter().write(user);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

2.5 自定义Service类

import com.ys.annotation.MyService;

@MyService("testService")
public class TestService {
	public String updateUser(String name, String password){
		return "name:"+name+"password:"+password;
	}
}

2.6 Servlet类核心功能(类似于MVC中的DispatcherServlet前置控制器)

该核心servlet类在服务启动是会执行其中的init方法,init方法主要实现了5个功能

1.扫描包,根据基础包路径进行递归,找出所有class文件。这也就是为什么spring规范启动类默认要在主路径下
2.实例化类对象缓存到map中。过滤所有class文件,将注解的value作为map的key值,通过全包名反射得到的对象实例作为map的value值
3.扫描MyAutowired,给标注了@MyController,@MyService的类注入对象实例
4.扫描MyRequestMapping,解析标注了@MyControlle的类,扫描其中标注了@MyRequestMapping的方法,将@MyControlle的value值 + @MyRequestMapping的value值拼接,作为map的key值,方法实例作为map的value值缓存
5.处理请求,当servlet收到post请求时,在dopost方法中通过解析请求地址得到缓存map的key值,从而得到缓存map中的方法实例,通过调用方法,传入参数,得到处理结果
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ys.annotation.MyAutowired;
import com.ys.annotation.MyController;
import com.ys.annotation.MyRequestMapping;
import com.ys.annotation.MyRequestParam;
import com.ys.annotation.MyService;
import com.ys.controller.TestController;

public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//用来存储class文件路径
	List<String> classNames = new ArrayList<String>();
	//用来存储controller类对象
	Map<String,Object> beans = new HashMap<String,Object>();
	//创建一个存储autowire的集合
	Map<String,Object> handlerMap = new HashMap<String,Object>();
	
	//tomcat启动扫描controller,service
	//通过反射实例化对象
	//处理autowired
	//path-method
	@Override
	public void init() throws ServletException {
		// 1.扫描所有class文件
		scanPackage("com.ys");
		// 2.实例化类对象
		instance();
		// 3.扫描MyAutowired
		doAutowired();
		// 4.处理requestMapping
		UrlHanding();
		// 5.输出测试日志
		test();
	}

	private void test() {
		System.out.println("---------------------------");
		for (String name : classNames) {
			System.out.println(name);
		}		
		System.out.println("beans-------------------------------------");
		for (String key : beans.keySet()) {
			System.out.println("key:"+key+"\t"+"value:"+beans.get(key));
		}
		System.out.println("handlerMap--------------------------------");
		for (String key : handlerMap.keySet()) {
			System.out.println("key:"+key+"\t"+"value:"+handlerMap.get(key));
		}
	}

	private void UrlHanding() {
		// 遍历容器里的bean
		for (Map.Entry<String, Object> entry : beans.entrySet()) {
			// 获取到map中的对象
			Object instance = entry.getValue();
			// 获取到当前类的路径,可以利用反射对对象进行实例化
			Class<?> clazz = instance.getClass();
			// 注意:在controller下使用autowired注解
			if (clazz.isAnnotationPresent(MyController.class)) {
				//MyController类上会存在MyRequestMapping注解
				MyRequestMapping map1 = clazz.getAnnotation(MyRequestMapping.class);
				//获取类路径,类上的值,需要和方法上的进行拼接
				String classPath = map1.value();
				//获取对象所有的方法
				Method[] methods = clazz.getMethods();
				//遍历方法
				for (Method method : methods) {
					//判断方法上是否有注解
					if(method.isAnnotationPresent(MyRequestMapping.class)){
						//获取方法上的注解值
						MyRequestMapping map2 = method.getAnnotation(MyRequestMapping.class);
						//获取注解上的value
						String methodPath = map2.value();
						//拼接,并以路径为key,方法名为value存到map中
						handlerMap.put(classPath+methodPath, method);
					}else{
						continue;
					}
				}
			}else{
				continue;
			}
		}
	}

	private void doAutowired() {
		//遍历容器里的bean
		for (Map.Entry<String, Object> entry: beans.entrySet()) {
			//获取到map中的value值
			Object instance = entry.getValue();
			//获取到当前类的路径,可以利用反射对对象进行实例化
			Class<?> clazz = instance.getClass();
			//注意:在controller下使用autowired注解
			if(clazz.isAnnotationPresent(MyController.class)){
				//获取控制层中所有的属性
				Field[] fields = clazz.getDeclaredFields();
				//遍历属性
				for (Field field : fields) {
					//判断属性上是否有Autowired注解
					if(field.isAnnotationPresent(MyAutowired.class)){
						//获取属性上的注解
						MyAutowired ea = field.getAnnotation(MyAutowired.class);
						//获取注解值
						String key = ea.value();
						//根据注解值,获取bean的类路径
						//service上的值和autowired的值相同
						Object ins = beans.get(key);
						//暴力破解获取私有值
						field.setAccessible(true);
						//
						try {
							field.set(instance, ins);
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
					}else{//如果有dao层,加一个else if
						continue;
					}
				}
			}
		}
	}

	private void instance() {
		for (String className : classNames) {
			//com.ys.xxx.xxx.class
			//截取掉当前的.class后缀
			String cn = className.replace(".class", "");
			try {
				//获取到当前类的路径,可以利用反射对对象进行实例化
				Class<?> clazz = Class.forName(cn);
				//判断当前类里是否声明了类上注解
				if(clazz.isAnnotationPresent(MyController.class)){
					//控制类
					Object instance = clazz.newInstance();
					//获取类上的requestmapping注解
					MyRequestMapping map1 = clazz.getAnnotation(MyRequestMapping.class);
					//获取注解的值
					String key = map1.value();
					//将注解上的值作为key值存入到map集合中
					beans.put(key, instance);
				}else if(clazz.isAnnotationPresent(MyService.class)){
					//业务类
					Object instance = clazz.newInstance();
					//获取类上的Myservice注解
					MyService map2 = clazz.getAnnotation(MyService.class);
					//获取注解的值
					String key = map2.value();
					//将注解上的值作为key值存入到map集合中
					beans.put(key, instance);
				}else{
					continue;
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	//扫描所有的基础包下的文件,将所有的类路径存在list集合下
	private void scanPackage(String basepackage) {
		//将路径中的.换成java认识的/
		URL url = this.getClass().getClassLoader().getResource("/"+basepackage.replaceAll("\\.", "/"));
		//E:workpace/abc
		String fileStr = url.getFile();
		//找到基础包路径
		File file = new File(fileStr);
		//获取该文件下所有的文件
		String[] fileNames = file.list();
		//只需要文件,所以遍历
		for (String path : fileNames) {
			//fileStr+filename  基础包路径拼接上对应路径名
			File filePath = new File(fileStr+path);
			//判断是否是文件
			if(filePath.isDirectory()){
				//是文件的话递归直到是文件为止
				scanPackage(basepackage+"."+path);
			}else{
				//com.ys.xxx.xxx.class
				classNames.add(basepackage+"."+filePath.getName());
			}
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//  http://ip+端口/项目名/请求路径
		//  uri获取得是            /项目名/请求路径
		String uri = request.getRequestURI();
		System.out.println("uri:"+uri);
		//获取工程名
		String contextPath = request.getContextPath();
		System.out.println("contextPath:"+contextPath);
		//剪切   /请求路径
		String path = uri.replace(contextPath, ""); 
		System.out.println("path:"+path);
		//获取handlerMap中的方法
		Method method = (Method)handlerMap.get(path);
		System.out.println("method:"+method);
		//不足:进行了强转:因为只有一个controller类,所以,多个情况使用Object类型,具体使用时进行强转
		TestController instance = (TestController)beans.get("/"+path.split("/")[1]);
		System.out.println(instance);
		//参数处理
		Object[] args = hand(request, response, method);
		//调用方法
		try {
			method.invoke(instance, args);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//获取方法中的参数
	private static Object[] hand(HttpServletRequest request, HttpServletResponse response,Method method){
		//拿到当前执行方法有哪些参数
		Class<?>[] paramClazzs = method.getParameterTypes();
		//根据参数个数,new一个参数的数组,将方法里的所有参数赋值大agrs中
		Object[] args = new Object[paramClazzs.length];
		
		int args_i = 0;
		int index = 0;
		for (Class<?>  paramClazz : paramClazzs) {
			if(ServletRequest.class.isAssignableFrom(paramClazz)){
				args[args_i++] = request;
			}
			if(ServletResponse.class.isAssignableFrom(paramClazz)){
				args[args_i++] = response;
			}
			
			Annotation[] paramAns = method.getParameterAnnotations()[index];
			if(paramAns.length>0){
				for (Annotation paramAn : paramAns) {
					if(MyRequestParam.class.isAssignableFrom(paramAn.getClass())){
						MyRequestParam mp = (MyRequestParam) paramAn;
						//找到注解里的name和password
						args[args_i++] = request.getParameter(mp.value());
					}
				}
			}
			index++;
		}
		return args;
	}
}

3.结果

servlet中的init方法中test测试 :遍历已经完成存储的容器结果
在这里插入图片描述
最终运行结果
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
弃用了struts,用spring mvc框架做了几个项目,感觉都不错,而且使用了注解方式,可以省掉一大堆配置文件。本文主要介绍使用注解方式配置的spring mvc,之前写的spring3.0 mvc和rest小例子没有介绍到数据层的内容,现在这一篇补上。下面开始贴代码。 文中用的框架版本:spring 3,hibernate 3,没有的,自己上网下。 先说web.xml配置: [java] view plaincopy 01.<?xml version="1.0" encoding="UTF-8"?> 02.<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> 03. <display-name>s3h3</display-name> 04. <context-param> 05. <param-name>contextConfigLocation</param-name> 06. <param-value>classpath:applicationContext*.xml</param-value> 07. </context-param> 08. <listener> 09. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 10. </listener> 11. 12. <servlet> 13. <servlet-name>spring</servlet-name> 14. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 15. <load-on-startup>1</load-on-startup> 16. </servlet> 17. <servlet-mapping> 18. <servlet-name>spring</servlet-name> <!-- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller --> 19. <url-pattern>*.do</url-pattern> 20. </servlet-mapping> 21. <welcome-file-list> 22. <welcome-file>index.jsp</welcome-file> 23. </welcome-file-list> 24.</web-app> spring-servlet,主要配置controller的信息 [java] view plaincopy 01.<?xml version="1.0" encoding="UTF-8"?> 02. <beans 03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 04. xmlns:context="http://www.springframework.org/schema/context" 05. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 06. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 07. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 08. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 09. 10. <context:annotation-config /> 11. <!-- 把标记了@Controller注解的类转换为bean --> 12. <context:component-scan base-package="com.mvc.controller" /> 13. <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> 14. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 15. 16. <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> 17. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 18. p:prefix="/WEB-INF/view/" p:suffix=".jsp" /> 19. 20. <bean id="multipartResolver" 21. class="org.springframework.web.multipart.commons.CommonsMultipartResolver" 22. p:defaultEncoding="utf-8" /> 23. </beans> applicationContext.xml代码 [java] view plaincopy 01.<?xml version="1.0" encoding="UTF-8"?> 02.<beans 03. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" 04. xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 05. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 06. xsi:schemaLocation=" 07. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 08. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 09. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 10. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 11. 12. <context:annotation-config /> 13. <context:component-scan base-package="com.mvc" /> <!-- 自动扫描所有注解该路径 --> 14. 15. <context:property-placeholder location="classpath:/hibernate.properties" /> 16. 17. <bean id="sessionFactory" 18. class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 19. <property name="dataSource" ref="dataSource" /> 20. <property name="hibernateProperties"> 21. <props> 22. <prop key="hibernate.dialect">${dataSource.dialect}</prop> 23. <prop key="hibernate.hbm2ddl.auto">${dataSource.hbm2ddl.auto}</prop> 24. <prop key="hibernate.hbm2ddl.auto">update</prop> 25. </props> 26. </property> 27. <property name="packagesToScan"> 28. <list> 29. <value>com.mvc.entity</value><!-- 扫描实体类,也就是平时所说的model --> 30. </list> 31. </property> 32. </bean> 33. 34. <bean id="transactionManager" 35. class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 36. <property name="sessionFactory" ref="sessionFactory" /> 37. <property name="dataSource" ref="dataSource" /> 38. </bean> 39. 40. <bean id="dataSource" 41. class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 42. <property name="driverClassName" value="${dataSource.driverClassName}" /> 43. <property name="url" value="${dataSource.url}" /> 44. <property name="username" value="${dataSource.username}" /> 45. <property name="password" value="${dataSource.password}" /> 46. </bean> 47. <!-- Dao的实现 --> 48. <bean id="entityDao" class="com.mvc.dao.EntityDaoImpl"> 49. <property name="sessionFactory" ref="sessionFactory" /> 50. </bean> 51. <tx:annotation-driven transaction-manager="transactionManager" /> 52. <tx:annotation-driven mode="aspectj"/> 53. 54. <aop:aspectj-autoproxy/> 55.</beans> hibernate.properties数据库连接配置 [java] view plaincopy 01.dataSource.password=123 02.dataSource.username=root 03.dataSource.databaseName=test 04.dataSource.driverClassName=com.mysql.jdbc.Driver 05.dataSource.dialect=org.hibernate.dialect.MySQL5Dialect 06.dataSource.serverName=localhost:3306 07.dataSource.url=jdbc:mysql://localhost:3306/test 08.dataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password} 09.dataSource.hbm2ddl.auto=update 配置已经完成,下面开始例子 先在数据库建表,例子用的是mysql数据库 [java] view plaincopy 01.CREATE TABLE `test`.`student` ( 02. `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 03. `name` varchar(45) NOT NULL, 04. `psw` varchar(45) NOT NULL, 05. PRIMARY KEY (`id`) 06.) 建好表后,生成实体类 [java] view plaincopy 01.package com.mvc.entity; 02. 03.import java.io.Serializable; 04. 05.import javax.persistence.Basic; 06.import javax.persistence.Column; 07.import javax.persistence.Entity; 08.import javax.persistence.GeneratedValue; 09.import javax.persistence.GenerationType; 10.import javax.persistence.Id; 11.import javax.persistence.Table; 12. 13.@Entity 14.@Table(name = "student") 15.public class Student implements Serializable { 16. private static final long serialVersionUID = 1L; 17. @Id 18. @Basic(optional = false) 19. @GeneratedValue(strategy = GenerationType.IDENTITY) 20. @Column(name = "id", nullable = false) 21. private Integer id; 22. @Column(name = "name") 23. private String user; 24. @Column(name = "psw") 25. private String psw; 26. public Integer getId() { 27. return id; 28. } 29. public void setId(Integer id) { 30. this.id = id; 31. } 32. 33. public String getUser() { 34. return user; 35. } 36. public void setUser(String user) { 37. this.user = user; 38. } 39. public String getPsw() { 40. return psw; 41. } 42. public void setPsw(String psw) { 43. this.psw = psw; 44. } 45.} Dao层实现 [java] view plaincopy 01.package com.mvc.dao; 02. 03.import java.util.List; 04. 05.public interface EntityDao { 06. public List<Object> createQuery(final String queryString); 07. public Object save(final Object model); 08. public void update(final Object model); 09. public void delete(final Object model); 10.} [java] view plaincopy 01.package com.mvc.dao; 02. 03.import java.util.List; 04. 05.import org.hibernate.Query; 06.import org.springframework.orm.hibernate3.HibernateCallback; 07.import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 08. 09.public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao{ 10. public List<Object> createQuery(final String queryString) { 11. return (List<Object>) getHibernateTemplate().execute( 12. new HibernateCallback<Object>() { 13. public Object doInHibernate(org.hibernate.Session session) 14. throws org.hibernate.HibernateException { 15. Query query = session.createQuery(queryString); 16. List<Object> rows = query.list(); 17. return rows; 18. } 19. }); 20. } 21. public Object save(final Object model) { 22. return getHibernateTemplate().execute( 23. new HibernateCallback<Object>() { 24. public Object doInHibernate(org.hibernate.Session session) 25. throws org.hibernate.HibernateException { 26. session.save(model); 27. return null; 28. } 29. }); 30. } 31. public void update(final Object model) { 32. getHibernateTemplate().execute(new HibernateCallback<Object>() { 33. public Object doInHibernate(org.hibernate.Session session) 34. throws org.hibernate.HibernateException { 35. session.update(model); 36. return null; 37. } 38. }); 39. } 40. public void delete(final Object model) { 41. getHibernateTemplate().execute(new HibernateCallback<Object>() { 42. public Object doInHibernate(org.hibernate.Session session) 43. throws org.hibernate.HibernateException { 44. session.delete(model); 45. return null; 46. } 47. }); 48. } 49.} Dao在applicationContext.xml注入 <bean id="entityDao" class="com.mvc.dao.EntityDaoImpl"> <property name="sessionFactory" ref="sessionFactory" /> </bean> Dao只有一个类的实现,直接供其它service层调用,如果你想更换为其它的Dao实现,也只需修改这里的配置就行了。 开始写view页面,WEB-INF/view下新建页面student.jsp,WEB-INF/view这路径是在spring-servlet.xml文件配置的,你可以配置成其它,也可以多个路径。student.jsp代码 [xhtml] view plaincopy 01.<%@ page language="java" contentType="text/html; charset=UTF-8" 02. pageEncoding="UTF-8"%> 03.<%@ include file="/include/head.jsp"%> 04.<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 05.<html> 06.<head> 07.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 08.<title>添加</title> 09.<mce:script language="javascript" src="<%=request.getContextPath()%><!-- 10./script/jquery.min.js"> 11.// --></mce:script> 12.<mce:style><!-- 13.table{ border-collapse:collapse; } 14.td{ border:1px solid #f00; } 15.--></mce:style><style mce_bogus="1">table{ border-collapse:collapse; } 16.td{ border:1px solid #f00; }</style> 17.<mce:script type="text/javascript"><!-- 18.function add(){ 19. [removed].href="<%=request.getContextPath() %>/student.do?method=add"; 20.} 21. 22.function del(id){ 23.$.ajax( { 24. type : "POST", 25. url : "<%=request.getContextPath()%>/student.do?method=del&id;=" + id, 26. dataType: "json", 27. success : function(data) { 28. if(data.del == "true"){ 29. alert("删除成功!"); 30. $("#" + id).remove(); 31. } 32. else{ 33. alert("删除失败!"); 34. } 35. }, 36. error :function(){ 37. alert("网络连接出错!"); 38. } 39.}); 40.} 41.// --></mce:script> 42.</head> 43.<body> 44. 45.<input id="add" type="button" value="添加"/> 46.<table > 47. <tr> 48. <td>序号</td> 49. <td>姓名</td> 50. <td>密码</td> 51. <td>操作</td> 52. </tr> 53. <c:forEach items="${list}" var="student"> 54. <tr id="<c:out value="${student.id}"/>"> 55. <td><c:out value="${student.id}"/></td> 56. <td><c:out value="${student.user}"/></td> 57. <td><c:out value="${student.psw}"/></td> 58. <td> 59. <input type="button" value="编辑"/> 60. <input type="button" value="${student.id}"/>')" value="删除"/> 61. </td> 62. </tr> 63. </c:forEach> 64. 65.</table> 66.</body> 67.</html> student_add.jsp [xhtml] view plaincopy 01.<%@ page language="java" contentType="text/html; charset=UTF-8" 02. pageEncoding="UTF-8"%> 03.<%@ include file="/include/head.jsp"%> 04.<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 05.<html> 06.<head> 07.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 08.<title>学生添加</title> 09.<mce:script type="text/javascript"><!-- 10.function turnback(){ 11. [removed].href="<%=request.getContextPath() %>/student.do"; 12.} 13.// --></mce:script> 14.</head> 15.<body> 16.<form method="post" action="<%=request.getContextPath() %>/student.do?method=save"> 17.<div><c:out value="${addstate}"></c:out></div> 18.<table> 19. <tr><td>姓名</td><td><input id="user" name="user" type="text" /></td></tr> 20. <tr><td>密码</td><td><input id="psw" name="psw" type="text" /></td></tr> 21. <tr><td colSpan="2" align="center"><input type="submit" value="提交"/><input type="button" value="返回" /> </td></tr> 22.</table> 23. 24.</form> 25.</body> 26.</html> controller类实现,只需把注解写上,spring就会自动帮你找到相应的bean,相应的注解标记意义,不明白的,可以自己查下@Service,@Controller,@Entity等等的内容。 [java] view plaincopy 01.package com.mvc.controller; 02. 03.import java.util.List; 04. 05.import javax.servlet.http.HttpServletRequest; 06.import javax.servlet.http.HttpServletResponse; 07. 08.import org.apache.commons.logging.Log; 09.import org.apache.commons.logging.LogFactory; 10.import org.springframework.beans.factory.annotation.Autowired; 11.import org.springframework.stereotype.Controller; 12.import org.springframework.ui.ModelMap; 13.import org.springframework.web.bind.annotation.RequestMapping; 14.import org.springframework.web.bind.annotation.RequestMethod; 15.import org.springframework.web.bind.annotation.RequestParam; 16.import org.springframework.web.servlet.ModelAndView; 17. 18.import com.mvc.entity.Student; 19.import com.mvc.service.StudentService; 20. 21.@Controller 22.@RequestMapping("/student.do") 23.public class StudentController { 24. protected final transient Log log = LogFactory 25. .getLog(StudentController.class); 26. @Autowired 27. private StudentService studentService; 28. public StudentController(){ 29. 30. } 31. 32. @RequestMapping 33. public String load(ModelMap modelMap){ 34. List<Object> list = studentService.getStudentList(); 35. modelMap.put("list", list); 36. return "student"; 37. } 38. 39. @RequestMapping(params = "method=add") 40. public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{ 41. return "student_add"; 42. } 43. 44. @RequestMapping(params = "method=save") 45. public String save(HttpServletRequest request, ModelMap modelMap){ 46. String user = request.getParameter("user"); 47. String psw = request.getParameter("psw"); 48. Student st = new Student(); 49. st.setUser(user); 50. st.setPsw(psw); 51. try{ 52. studentService.save(st); 53. modelMap.put("addstate", "添加成功"); 54. } 55. catch(Exception e){ 56. log.error(e.getMessage()); 57. modelMap.put("addstate", "添加失败"); 58. } 59. 60. return "student_add"; 61. } 62. 63. @RequestMapping(params = "method=del") 64. public void del(@RequestParam("id") String id, HttpServletResponse response){ 65. try{ 66. Student st = new Student(); 67. st.setId(Integer.valueOf(id)); 68. studentService.delete(st); 69. response.getWriter().print("{/"del/":/"true/"}"); 70. } 71. catch(Exception e){ 72. log.error(e.getMessage()); 73. e.printStackTrace(); 74. } 75. } 76.} service类实现 [java] view plaincopy 01.package com.mvc.service; 02. 03.import java.util.List; 04. 05.import org.springframework.beans.factory.annotation.Autowired; 06.import org.springframework.stereotype.Service; 07.import org.springframework.transaction.annotation.Transactional; 08. 09.import com.mvc.dao.EntityDao; 10.import com.mvc.entity.Student; 11. 12.@Service 13.public class StudentService { 14. @Autowired 15. private EntityDao entityDao; 16. 17. @Transactional 18. public List<Object> getStudentList(){ 19. StringBuffer sff = new StringBuffer(); 20. sff.append("select a from ").append(Student.class.getSimpleName()).append(" a "); 21. List<Object> list = entityDao.createQuery(sff.toString()); 22. return list; 23. } 24. 25. public void save(Student st){ 26. entityDao.save(st); 27. } 28. public void delete(Object obj){ 29. entityDao.delete(obj); 30. } 31.} OK,例子写完。有其它业务内容,只需直接新建view,并实现相应comtroller和service就行了,配置和dao层的内容基本不变,也就是每次只需写jsp(view),controller和service调用dao就行了。 怎样,看了这个,spring mvc是不是比ssh实现更方便灵活。
1. 在注解模式下,搭建SpringMVC框架的流程如下: (1)添加SpringMVC相关依赖,包括spring-webmvc、javax.servlet-api等。 (2)在web.xml中配置DispatcherServlet,将其作为应用程序的前端控制器。 (3)在Spring配置文件中配置组件扫描,用于扫描所有的控制器类。 (4)在控制器类上添加@Controller注解,声明该类是一个控制器。 (5)在控制器类中,使用@RequestMapping注解来映射请求URL和处理器方法。 (6)在处理器方法中,可以使用@RequestParam注解来接收请求参数,使用@ResponseBody注解来返回响应数据。 2. 在SpringMVC模式下实现文件上传的过程如下: (1)在Spring配置文件中配置MultipartResolver,用于处理文件上传请求。 (2)在控制器类中,使用@RequestMapping注解来映射文件上传请求的URL和处理器方法。 (3)在处理器方法中,使用@RequestParam注解来接收上传的文件,可以使用MultipartFile类型来接收文件。 (4)在处理器方法中,使用MultipartHttpServletRequest来获取上传文件的详细信息。 (5)在处理器方法中,可以将上传的文件保存到本地文件系统或者云存储中,然后返回上传结果。 3. 在SpringMVC模式下,Controller接收请求参数的多种方式包括: (1)使用@RequestParam注解来接收请求参数,可以指定参数名、是否必须、默认值等属性。 (2)使用@PathVariable注解来接收路径变量,即URL中的占位符。 (3)使用@RequestBody注解来接收请求体中的JSON或XML格式数据。 (4)使用HttpServletRequest对象来获取请求参数,可以获取URL参数、请求头、请求体等信息。 (5)使用@InitBinder注解来定义表单数据的转换器或校验器,用于将请求参数转换成业务对象。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼鱼大头鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值