概述
网上找了很多资料,也找了些达人的例子,结合自己的测试和摸索,自己做了个spring mvc开发练习。
JAVAEE框架开发中,最常的模式就是MVC,其中以struts的mvc开发占主导地位。后来spring mvc也流行起来。
struts2 mvc和spring mvc各有千秋。不过在具体的开发中,选择用struts2 mvc 还是spring mvc,最主要的是看团队的学习成本和开发水平。其实两者都是比较好的mvc框架。
这里还是采用的xml配置为主。因为自己感觉注解的方式去装配bean,不太好!注解都写在类中了,个人觉得还是把bean配置在xml中统一管理好一些。降低耦合度。
下面上代码:
1、首先是用到的jar,这里只是个大概的jar哈。可能有一些不必要的,但是都日常项目中常用的。截个图上来:
2、web.xml配置
<?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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- ContextConfigLocation,配置加载spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml,classpath:spring-mvc.xml</param-value>
</context-param>
<!-- spring的监听,自动装载BEAN -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring 刷新Introspector防止内存泄露 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- spring配置web.xml
启用spring的请求接收器DispatcherServlet -->
<servlet>
<servlet-name>Dispatcher</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3、spring主配置文件: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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- 加载jdbc.properties配置文件-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<!-- 配置数据源,读取jdbc.properties配置文件,采用Proxool连接池 -->
<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">
<property name="driver" value="${jdbc.driver}" />
<property name="driverUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="alias" value="${jdbc.alias}" />
<property name="simultaneousBuildThrottle" value="${jdbc.simultaneousBuildThrottle}" />
<property name="maximumActiveTime" value="${jdbc.maximumActiveTime}" />
<property name="maximumConnectionCount" value="${jdbc.maximumConnectionCount}" />
<property name="minimumConnectionCount" value="${jdbc.minimumConnectionCount}" />
<property name="delegateProperties" value="characterEncoding=${jdbc.characterEncoding}" />
</bean>
<!-- 采用spring的jdbcTemplate做为数据操作类,这个很好用,采用自己写ConnectionFactory去获取连接,此连接没有在spring的事务环境中,只有手工去配置事务。采用jdbcTemplate模板获取的连接,可以支持AOP事务操作 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<!-- 事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="query*" read-only="true" />
<tx:method name="*" rollback-for="Exception,RuntimeException" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- Spring AOP config -->
<aop:config proxy-target-class="true">
<!-- 切入点在service层上进行拦截,添加事务管理 -->
<!-- service下面的所有类的所有方法,可配置在接口和类下面都可以 -->
<aop:pointcut id="servicesPointcut" expression="execution(* com.zyujie.*.service.*.*(..))" />
<!-- 运行拦截的方法关联配置 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="servicesPointcut" />
</aop:config>
<import resource="conf/spring/spring-init-login.xml" />
</beans>
4、单独加了一个spring mvc的配置文件,其实可以写在主配置里,spring-mvc.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- 不进行拦截的 -->
<mvc:resources location="/" mapping="/**/*.html" order="0" />
<mvc:resources location="/imgs/" mapping="/imgs/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/css/" mapping="/css/**" />
<pre name="code" class="html"> <!-- prefix是view,也就是jsp的前缀路径,suffix是后缀名,跳转页面时spring会在根目录下按照返回的名字,跳转的页面拼成jsp。 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 支持上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- set the max upload size100MB -->
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
</beans>
5、主要的配置文件就这些了,其它log4j,缓存,属性文件这里就不例出来了。下面是spring单个功能性的配置文件:如果用注解方式,可以不写这个。spring-init-login.xml。说明一下:这里使用的是一个Controller处理多个请求:如,/login.do?method=add.../login.do?method=delete这种方式。所以下面注入了多请求处理器。
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="userLoginDao" class="com.zyujie.init.dao.UserLoginDao">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="userLoginService" class="com.zyujie.init.service.impl.UserLoginServiceImpl">
<property name="userLoginDao" ref="userLoginDao" />
</bean>
<!--定义映射-->
<bean id="/init/userloginMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/login.do">userLoginAction</prop>
</props>
</property>
</bean>
<!-- 多请求处理控制器 -->
<bean id="paraMethodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName">
<value>method</value>
</property>
</bean>
<!-- 定义Action 这里还是scope为prototype,不要用单例模式。-->
<bean id="userLoginAction" class="com.zyujie.init.web.UserLoginAction" scope="prototype">
<property name="methodNameResolver" ref="paraMethodResolver" />
<property name="userLoginService" ref="userLoginService" />
<!-- 指定失败要返回的页面 -->
<property name="loginView">
<value>login</value>
</property>
<!-- 指定成功要返回的页面 -->
<property name="successView">
<value>success</value>
</property>
</bean>
</beans>
6、下面是类了,DAO和SERVICE我就不写了。主要是ACTION,上面提到的多请求处理控制器需要继承MultiActionController
package com.zyujie.init.web;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.zyujie.init.pojo.UserInfo;
import com.zyujie.init.service.UserLoginService;
public class UserLoginAction extends MultiActionController {
private String successView;
private String loginView;
private UserLoginService userLoginService;
public void setUserLoginService(UserLoginService userLoginService) {
this.userLoginService = userLoginService;
}
public ModelAndView addUser(HttpServletRequest req, HttpServletResponse resp) {
Map model = new HashMap();
model.put("success", "增加用户成功");
String user = req.getParameter("user");
String password = req.getParameter("password");
System.out.println(user+"--------"+password);
return new ModelAndView(this.getSuccessView(), model);
}
/*
* 普通登录
*/
public ModelAndView login(HttpServletRequest req, HttpServletResponse resp) {
Map model = new HashMap();
model.put("success", "用户登录成功");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username);
UserInfo user = userLoginService.userLogin(username, password);
if(user == null){
return new ModelAndView(this.getLoginView(), model);
}else{
req.getSession().setAttribute("username", user.getUser_name());
return new ModelAndView(this.getSuccessView(), model);
}
}
/*
* ajax登录返回
*/
public ModelAndView ajaxlogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Map model = new HashMap();
model.put("success", "用户登录成功");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username);
UserInfo user = userLoginService.userLogin(username, password);
if(user == null){
String s = "用户登录错误";
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write(s);
return null;
}else{
req.getSession().setAttribute("username", user.getUser_name());
String s = "用户登录成功";
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write(s);
return null;
}
}
/*
* 文件上传
*/
public ModelAndView upload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
//如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且还要指定@RequestParam注解
//并且上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件
// 转型为MultipartHttpRequest:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
// 获得文件:
List<MultipartFile> myfiles = multipartRequest.getFiles("file");
for(MultipartFile myfile : myfiles){
if(myfile.isEmpty()){
System.out.println("文件未上传");
}else{
System.out.println("文件长度: " + myfile.getSize());
System.out.println("文件类型: " + myfile.getContentType());
System.out.println("文件名称: " + myfile.getName());
System.out.println("文件原名: " + myfile.getOriginalFilename());
System.out.println("========================================");
//如果用的是Tomcat服务器,则文件会上传到 {服务发布位置}\WEB-INF\upload\文件夹中
String realPath = req.getSession().getServletContext().getRealPath("/WEB-INF/upload");
System.out.println(realPath);
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
}
}
Map model = new HashMap();
model.put("success", "用户登录成功");
return new ModelAndView(this.getSuccessView(), model);
}
public String getSuccessView() {
return successView;
}
public void setSuccessView(String successView) {
this.successView = successView;
}
public String getLoginView() {
return loginView;
}
public void setLoginView(String loginView) {
this.loginView = loginView;
}
}
7、下面是JSP了,这里定义了几种提交方式。FORM表单,A标签,AJAX提交。其中AJAX返回JSON是同理的。
<%@ page language="java" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>spring mvc demo</title>
<script type="text/javascript" language="javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
function subTest(){
var username = "admin";
var password = "admin";
$.ajax({
url:'/spring-mvc/login.do?method=ajaxlogin',
data:{
username : username,
password : password
},
async : true,
dataType : 'html',
error : function(){
alert('系统错误');
},
success : function(data){
alert(data);
}
});
}
</script>
</head>
<body>
<center>
<form action="/spring-mvc/login.do" method="get">
<table>
<tr><td><input type="hidden" id="method" name="method" value="login" /></td></tr>
<tr><td><input type="text" id="username" name="username" /></td></tr>
<tr><td><input type="text" id="password" name="password" /></td></tr>
<tr><td><input type="submit" id="subok" name="subok" value="ok" /></td></tr>
</table>
</form>
<br/>
<a href="/spring-mvc/login.do?method=addUser&user=admin&password=123">test</a>
<br/>
<a href=javascript:subTest();>js test</a>
<br/>
<form action="/spring-mvc/login.do?method=upload" method="POST" enctype="multipart/form-data">
文件1: <input type="file" id="file1" name="file" /><br/>
文件2: <input type="file" id="file2" name="file" /><br/>
文件3: <input type="file" id="file3" name="file" /><br/>
<input type="submit" value="上传" />
</form>
</center>
</body>
</html>
大致的spring mvc基本架构就是这样的了!具体就介绍到这里!spring mvc还有很多功能,再慢慢的学习吧!
我把小例子传到自己的资源空间里了:大家可以去下载!
本博文例子:spring-mvc小例子
最后
以上就是可爱钢铁侠为你收集整理的spring mvc的练习的全部内容,希望文章能够帮你解决spring mvc的练习所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复