<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <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>*.do</url-pattern> </servlet-mapping> </web-app> |
<?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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans "> <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 --> <context:component-scan base-package="com.xz"/> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!--对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/> <!-- 配置dataSource 和sessionFactory --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>/WEB-INF/properties/jdbc.properties</value> </list> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driverClassName}"> </property> <property name="url"> <value>${url}</value> </property> <property name="username" value="${username}"></property> <property name="password" value="${password}"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource"></ref> </property> <property name="mappingResources"> <list> <value>com/xz/user/bean/User.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=false <!-- 数据库出现异常时 是否格式化sql语句 --> hibernate.cache.use_second_level_cache=true <!-- 开启二级缓存 --> hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider <!-- 这是用哪一种缓存的jar文件 --> hibernate.cache.use_query_cache=false <!-- 对hql语句的缓存 --> </value> </property> </bean> <!-- 配置事务 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 使用基于注解方式配置事务 --> <tx:annotation-driven transaction-manager="txManager"/> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" > <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans> |
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>**********${params.uname}</h1> <h1>**********${requestScope.u}</h1> <h1>**********${requestScope.user}</h1> </body> </html> |
package com.xz.po; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String uname; private String pwd; public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } } |
package com.xz.dao; import javax.annotation.Resource; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; import com.xz.po.User; @Repository("userDao") public class UserDao { @Resource private HibernateTemplate hibernateTemplate; public void add(User u){ System.out.println("UserDao.add()"); hibernateTemplate.save(u); } public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } } |
package com.xz.service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.xz.dao.UserDao; import com.xz.po.User; @Service("userService") public class UserService { @Resource private UserDao userDao; public void add(String uname){ System.out.println("UserService.add()"); User u = new User(); u.setUname(uname); userDao.add(u); } public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } } |
package com.xz.web; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import com.xz.po.User; import com.xz.service.UserService; @Controller("userController") @RequestMapping("/user.do") public class UserController { @Resource private UserService userService; @RequestMapping(params="method=reg") public String reg(String uname) { System.out.println("HelloController.handleRequest()"); userService.add(uname); return "index"; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } } |
<context:component-scan base-package="com.xz.web"/> |
package com.xz.web; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.xz.service.UserService; @Controller @RequestMapping("/user.do") public class UserController { @Resource private UserService userService; //http://localhost:8080/springmvc02/user.do?method=reg&uname=zzzz @RequestMapping(params="method=reg") public String reg(String uname) { System.out.println("HelloController.handleRequest()"); userService.add(uname); return "index"; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } } |
@RequestMapping(params="method=reg5") public String reg5(@RequestParam("name")String uname,ModelMap map) { System.out.println("HelloController.handleRequest()"); System.out.println(uname); return "index"; } |
@RequestMapping(params="method=reg4") public String reg4(ModelMap map) { System.out.println("HelloController.handleRequest()"); return "index"; } |
前缀为:/WEB-INF/jsp/ 后缀是:.jsp 在转发到:/WEB-INF/jsp/index.jsp |
package com.xz.web; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; @Controller @RequestMapping("/user.do") public class UserController { @RequestMapping(params="method=reg4") public String reg4(ModelMap map) { System.out.println("HelloController.handleRequest()"); // return "forward:index.jsp"; // return "forward:user.do?method=reg5"; //转发 // return "redirect:user.do?method=reg5"; //重定向 return "redirect:http://www.baidu.com"; //重定向 } @RequestMapping(params="method=reg5") public String reg5(String uname,ModelMap map) { System.out.println("HelloController.handleRequest()"); System.out.println(uname); return "index"; } } |
@Controller @RequestMapping("/user.do") public class UserController { @RequestMapping(params="method=reg2") public String reg2(String uname,HttpServletRequest req,ModelMap map){ req.setAttribute("a", "aa"); req.getSession().setAttribute("b", "bb"); return "index"; } } |
package com.xz.web; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; @Controller @RequestMapping("/user.do") public class UserController extends MultiActionController { @RequestMapping(params="method=reg") public String reg(String uname,ModelMap map){ map.put("a", "aaa"); return "index"; } } |
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head></head> <body> <h1>${requestScope.a}</h1> <c ![]() ![]() </body> </html> |
public class ModelAndView { /** View instance or view name String */ private Object view; /** Model Map */ private ModelMap model; /** * Indicates whether or not this instance has been cleared with a call to {@link #clear()}. */ private boolean cleared = false; /** * Default constructor for bean-style usage: populating bean * properties instead of passing in constructor arguments. * @see #setView(View) * @see #setViewName(String) */ public ModelAndView() { } /** * Convenient constructor when there is no model data to expose. * Can also be used in conjunction with <code>addObject</code>. * @param viewName name of the View to render, to be resolved * by the DispatcherServlet's ViewResolver * @see #addObject */ public ModelAndView(String viewName) { this.view = viewName; } /** * Convenient constructor when there is no model data to expose. * Can also be used in conjunction with <code>addObject</code>. * @param view View object to render * @see #addObject */ public ModelAndView(View view) { this.view = view; } /** * Creates new ModelAndView given a view name and a model. * @param viewName name of the View to render, to be resolved * by the DispatcherServlet's ViewResolver * @param model Map of model names (Strings) to model objects * (Objects). Model entries may not be <code>null</code>, but the * model Map may be <code>null</code> if there is no model data. */ public ModelAndView(String viewName, Map<String, ?> model) { this.view = viewName; if (model != null) { getModelMap().addAllAttributes(model); } } /** * Creates new ModelAndView given a View object and a model. * <emphasis>Note: the supplied model data is copied into the internal * storage of this class. You should not consider to modify the supplied * Map after supplying it to this class</emphasis> * @param view View object to render * @param model Map of model names (Strings) to model objects * (Objects). Model entries may not be <code>null</code>, but the * model Map may be <code>null</code> if there is no model data. */ public ModelAndView(View view, Map<String, ?> model) { this.view = view; if (model != null) { getModelMap().addAllAttributes(model); } } /** * Convenient constructor to take a single model object. * @param viewName name of the View to render, to be resolved * by the DispatcherServlet's ViewResolver * @param modelName name of the single entry in the model * @param modelObject the single model object */ public ModelAndView(String viewName, String modelName, Object modelObject) { this.view = viewName; addObject(modelName, modelObject); } /** * Convenient constructor to take a single model object. * @param view View object to render * @param modelName name of the single entry in the model * @param modelObject the single model object */ public ModelAndView(View view, String modelName, Object modelObject) { this.view = view; addObject(modelName, modelObject); } /** * Set a view name for this ModelAndView, to be resolved by the * DispatcherServlet via a ViewResolver. Will override any * pre-existing view name or View. */ public void setViewName(String viewName) { this.view = viewName; } /** * Return the view name to be resolved by the DispatcherServlet * via a ViewResolver, or <code>null</code> if we are using a View object. */ public String getViewName() { return (this.view instanceof String ? (String) this.view : null); } /** * Set a View object for this ModelAndView. Will override any * pre-existing view name or View. */ public void setView(View view) { this.view = view; } /** * Return the View object, or <code>null</code> if we are using a view name * to be resolved by the DispatcherServlet via a ViewResolver. */ public View getView() { return (this.view instanceof View ? (View) this.view : null); } /** * Indicate whether or not this <code>ModelAndView</code> has a view, either * as a view name or as a direct {@link View} instance. */ public boolean hasView() { return (this.view != null); } /** * Return whether we use a view reference, i.e. <code>true</code> * if the view has been specified via a name to be resolved by the * DispatcherServlet via a ViewResolver. */ public boolean isReference() { return (this.view instanceof String); } /** * Return the model map. May return <code>null</code>. * Called by DispatcherServlet for evaluation of the model. */ protected Map<String, Object> getModelInternal() { return this.model; } /** * Return the underlying <code>ModelMap</code> instance (never <code>null</code>). */ public ModelMap getModelMap() { if (this.model == null) { this.model = new ModelMap(); } return this.model; } /** * Return the model map. Never returns <code>null</code>. * To be called by application code for modifying the model. */ public Map<String, Object> getModel() { return getModelMap(); } /** * Add an attribute to the model. * @param attributeName name of the object to add to the model * @param attributeValue object to add to the model (never <code>null</code>) * @see ModelMap#addAttribute(String, Object) * @see #getModelMap() */ public ModelAndView addObject(String attributeName, Object attributeValue) { getModelMap().addAttribute(attributeName, attributeValue); return this; } /** * Add an attribute to the model using parameter name generation. * @param attributeValue the object to add to the model (never <code>null</code>) * @see ModelMap#addAttribute(Object) * @see #getModelMap() */ public ModelAndView addObject(Object attributeValue) { getModelMap().addAttribute(attributeValue); return this; } /** * Add all attributes contained in the provided Map to the model. * @param modelMap a Map of attributeName -> attributeValue pairs * @see ModelMap#addAllAttributes(Map) * @see #getModelMap() */ public ModelAndView addAllObjects(Map<String, ?> modelMap) { getModelMap().addAllAttributes(modelMap); return this; } /** * Clear the state of this ModelAndView object. * The object will be empty afterwards. * <p>Can be used to suppress rendering of a given ModelAndView object * in the <code>postHandle</code> method of a HandlerInterceptor. * @see #isEmpty() * @see HandlerInterceptor#postHandle */ public void clear() { this.view = null; this.model = null; this.cleared = true; } /** * Return whether this ModelAndView object is empty, * i.e. whether it does not hold any view and does not contain a model. */ public boolean isEmpty() { return (this.view == null && CollectionUtils.isEmpty(this.model)); } /** * Return whether this ModelAndView object is empty as a result of a call to {@link #clear} * i.e. whether it does not hold any view and does not contain a model. * <p>Returns <code>false</code> if any additional state was added to the instance * <strong>after</strong> the call to {@link #clear}. * @see #clear() */ public boolean wasCleared() { return (this.cleared && isEmpty()); } /** * Return diagnostic information about this model and view. */ @Override public String toString() { StringBuilder sb = new StringBuilder("ModelAndView: "); if (isReference()) { sb.append("reference to view with name '").append(this.view).append("'"); } else { sb.append("materialized View is [").append(this.view).append(']'); } sb.append("; model is ").append(this.model); return sb.toString(); } } |
package com.xz.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; import com.xz.po.User; @Controller @RequestMapping("/user.do") public class UserController extends MultiActionController { @RequestMapping(params="method=reg") public ModelAndView reg(String uname){ ModelAndView mv = new ModelAndView(); mv.setViewName("index"); // mv.setView(new RedirectView("index")); User u = new User(); u.setUname("高淇"); mv.addObject(u); //查看源代码,得知,直接放入对象。属性名为”首字母小写的类名”。 一般建议手动增加属性名称。 mv.addObject("a", "aaaa"); return mv; } } |
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <h1>${requestScope.a}</h1> <h1>${requestScope.user.uname}</h1> </body> </html> |
结果为: file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml\wps7E5F.tmp.jpg |
<!-- 处理文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > <property name="defaultEncoding" value="gbk"/> <!-- 默认编码 (ISO-8859-1) --> <property name="maxInMemorySize" value="10240"/> <!-- 最大内存大小 (10240)--> <property name="uploadTempDir" value="/upload/"/> <!-- 上传后的目录名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) --> <property name="maxUploadSize" value="-1"/> <!-- 最大文件大小,-1为无限止(-1) --> </bean> |
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>测试springmvc中上传的实现</title> </head> <body> <form action="upload.do" method="post" enctype="multipart/form-data"> <input type="text" name="name" /> <input type="file" name="file" /> <input type="submit" /> </form> </body> </html> |
package com.xz.web; import java.io.File; import java.util.Date; import javax.servlet.ServletContext; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller public class FileUploadController implements ServletContextAware { private ServletContext servletContext; @Override public void setServletContext(ServletContext context) { this.servletContext = context; } @RequestMapping(value="/upload.do", method = RequestMethod.POST) public String handleUploadData(String name,@RequestParam("file")CommonsMultipartFile file){ if (!file.isEmpty()) { String path = this.servletContext.getRealPath("/tmp/"); //获取本地存储路径 System.out.println(path); String fileName = file.getOriginalFilename(); String fileType = fileName.substring(fileName.lastIndexOf(".")); System.out.println(fileType); File file2 = new File(path,new Date().getTime() + fileType); //新建一个文件 try { file.getFileItem().write(file2); //将上传的文件写入新建的文件中 } catch (Exception e) { e.printStackTrace(); } return "redirect:upload_ok.jsp"; }else{ return "redirect:upload_error.jsp"; } } } |
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <h1>上传成功!</h1> </body> </html> |
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <h1>上传失败!</h1> </body> </html> |
欢迎光临 java无忧网 (http://www.javawyw.com/) | Powered by Discuz! X3.2 |