论坛首页 Java企业应用论坛

基于spring3.0.5 mvc 简单用户管理实例

浏览 107049 次
该帖已经被评为精华帖
作者 正文
   发表时间:2011-06-08  
matychen 写道
huang_yong 写道
<mvc:resources mapping="/img/**" location="/img/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>

个人觉得以上这一段还不如在web.xml定义:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/resources/*</url-pattern>
</servlet-mapping>

注意:将img、js、css放在resources目录下


只要一行
<mvc:resources mapping="/resources/**" location="/resources/"/>

你却要4行。。。



<mvc:default-servlet-handler/>结合HandlerMapping的order,哈哈
0 请登录后投票
   发表时间:2011-06-08  
可以完全不用servlet API又不实现任何接口去处理request或session的作用。
package com.fsj.spring.web;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
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.bind.annotation.SessionAttributes;

import com.fsj.spring.model.TDept;
import com.fsj.spring.model.TUser;
import com.fsj.spring.service.IDeptService;
import com.fsj.spring.service.IUserService;
import com.fsj.spring.util.Constants;

@Controller
@RequestMapping("/user")
//将Model中属性名为Constants.USER_INFO_SESSION的属性放到Session属性列表中,以便这个属性可以跨请求访问
@SessionAttributes(Constants.USER_INFO_SESSION)
public class UserController {
	

	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(@RequestParam String name,@RequestParam String password,Model model) throws Exception{
		TUser user1 = userService.getUserByName(name);
		if(user1 == null) {
			model.addAttribute("message", "用户不存在");
			return "login";
		}else if(password == null || !password.equals(user1.getPassword()) ){
			model.addAttribute("message", "密码错误");
			return "login";
		}else {
			model.addAttribute(Constants.USER_INFO_SESSION, user1); //名为Constants.USER_INFO_SESSION的属性放到Session属性列表中
			return "welcome";
		}
	}
	
	@RequestMapping(value="/login1",method=RequestMethod.POST)
	public String login1(TUser user,Model model) throws Exception{
		TUser user1 = userService.getUserByName(user.getName());
		if(user1 == null) {
			model.addAttribute("message", "用户不存在");
			return "login";
		}else if(user.getPassword() == null || !user.getPassword().equals(user1.getPassword()) ){
			model.addAttribute("message", "密码错误");
			return "login";
		}else {
			model.addAttribute(Constants.USER_INFO_SESSION, user1); //名为Constants.USER_INFO_SESSION的属性放到Session属性列表中
			return "welcome";
		}
	}
	
	@RequestMapping(value="/list")   
	public String list(Model model,@RequestParam(value="resMess",required=false) String resMess, //还可以通过@RequestParam的required属性指定参数是否是必须的
			@RequestParam(value="resMess",required=false) String opeMess) throws Exception {
		List<TUser> userList = userService.getUserList();
		model.addAttribute("userList", userList);
		List<TDept> deptList = deptService.getDeptList();
		model.addAttribute("deptList", deptList);
		if(StringUtils.isNotBlank(resMess) && StringUtils.isNotBlank(opeMess)) {
			model.addAttribute("message",setOperateMessage(resMess,opeMess,"用户"));
		}
		return "user/list";
	}

	private String setOperateMessage(String resMess,String opeMess,String modMess) {
		//TODO 以后可以和写日志结合在一起,可以放在BaseController中
		String ope = "";
		String res = "";
		if(Constants.OPERATE_TYPE_ADD.equals(opeMess)) {
			ope = "增加";
		}else if(Constants.OPERATE_TYPE_UPDATE.equals(opeMess)) {
			ope = "更新";
		}else if(Constants.OPERATE_TYPE_DELETE.equals(opeMess)) {
			ope = "删除";
		}
		
		if(Constants.RESULT_SUCCESS.equals(resMess)) {
			res = "成功";
		}else if(Constants.RESULT_FAILED.equals(resMess)) {
			res = "失败";
		}
		return ope + modMess + res;
	}
	
	/*
	 * 同样的请求路径 user/add 如果是get请求就转到增加页面去,如果是post请求就做add操作
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String toAdd(Model model) throws Exception{
		List<TDept> deptList = deptService.getDeptList();
		model.addAttribute("deptList", deptList);
		return "user/add";
	}
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String doAdd(TUser user,Model model) throws Exception{
		try {
			userService.addUser(user);
			model.addAttribute("resMess", Constants.RESULT_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("resMess", Constants.RESULT_FAILED);
			throw e;
		}
		model.addAttribute("opeMess", Constants.OPERATE_TYPE_ADD);
		
		//return "redirect:/user/list";  //或
		return "redirect:list"; 
	}
	
	/*
	 * Restful url
	 */
	@RequestMapping(value="/update/{id}",method=RequestMethod.GET)
	public String toUpdate(@PathVariable("id") int id, Model model) throws Exception{
		model.addAttribute("user",userService.getUserById(id));
		model.addAttribute("deptList", deptService.getDeptList());
		return "user/update";
	}
	@RequestMapping(value="/update/{id}",method=RequestMethod.POST)
	public String doUpdate(@PathVariable("id") int id, TUser user,Model model) throws Exception{
		try {
			userService.updateUser(user);
			model.addAttribute("resMess", Constants.RESULT_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("resMess", Constants.RESULT_FAILED);
			throw e;
		}
		model.addAttribute("opeMess", Constants.OPERATE_TYPE_UPDATE);
		//return "redirect:../list"; 
		//重定向,简单防止重复提交
		return "redirect:/user/list"; 
	}
	
	@RequestMapping(value="/delete/{id}")
	public String delete(@PathVariable("id") int id,Model model)throws Exception{
		try {
			userService.deleteUser(id);
			model.addAttribute("resMess", Constants.RESULT_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("resMess", Constants.RESULT_FAILED);
			throw e;
		}
		model.addAttribute("opeMess", Constants.OPERATE_TYPE_DELETE);
		return "redirect:/user/list";//重定向
	}
	

	private IUserService userService;
	private IDeptService deptService;
	
	public IDeptService getDeptService() {
		return deptService;
	}

	public void setDeptService(IDeptService deptService) {
		this.deptService = deptService;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
}

0 请登录后投票
   发表时间:2011-06-08  
allstar1987 写道
大概看了一下,感觉跟WEBWORK(STRUTS2)的风格差不多。

另外,一大堆的东西,真的有SERVLET简洁吗?

真的有
0 请登录后投票
   发表时间:2011-06-08   最后修改:2011-06-08
很多东西都不用写的
0 请登录后投票
   发表时间:2011-06-09  
刚学习使用servlet+jsp+myBatis做练手项目,看了这贴,让我有些疼的慌,可选择的实在很多啊,再看LZ发的,让我项目了ASP.NET MVC,LZ写的这些在ASP.NET MVC2.x后的版本都很完善了(这里不参与口水阿,只描述事实)...

所以借这里的宝地想请教下,现在做J2EE项目使用哪个framework比较适中啊,学习难度+实用范围+...

恳请不要拍我,给新手点建议,灰常感谢...
0 请登录后投票
   发表时间:2011-06-09  
收藏下,好东西
0 请登录后投票
   发表时间:2011-06-09  
引用

<!--  
    配置一个基于注解的定制的WebBindingInitializer,解决日期转换问题,方法级别的处理器映射, 
    有人说该bean要放在context:component-scan前面,要不然不起作用,但我试的放后面也可以啊。 
    --> 
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
        <property name="cacheSeconds" value="0" /> 
        <property name="webBindingInitializer"> 
            <bean class="com.fsj.spring.util.MyWebBinding" /> 
        </property> 
    </bean> 


我这么配置的,怎么不行呢?

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="webBindingInitializer">
			<bean class="com.*.*.web.interceptor.BindingInitializer" />
		</property>
	</bean>



其他地方不用配置吧?这样会出现这个错误
2011-6-9 9:03:28 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet dispatcherServlet threw exception
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'record' on field 'endTime': rejected value [2011-06-09 23:59:59]; codes [typeMismatch.record.endTime,typeMismatch.endTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [record.endTime,endTime]; arguments []; default message [endTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "2011-06-09 23:59:59" from type 'java.lang.String' to type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException]
Field error in object 'record' on field 'startTime': rejected value [2011-06-01 00:00:00]; codes [typeMismatch.record.startTime,typeMismatch.startTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [record.startTime,startTime]; arguments []; default message [startTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'startTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "2011-06-01 00:00:00" from type 'java.lang.String' to type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException]
	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:810)
	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:359)
	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
	at java.lang.Thread.run(Thread.java:619)

0 请登录后投票
   发表时间:2011-06-09  
matychen 写道
引用

<!--  
    配置一个基于注解的定制的WebBindingInitializer,解决日期转换问题,方法级别的处理器映射, 
    有人说该bean要放在context:component-scan前面,要不然不起作用,但我试的放后面也可以啊。 
    --> 
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
        <property name="cacheSeconds" value="0" /> 
        <property name="webBindingInitializer"> 
            <bean class="com.fsj.spring.util.MyWebBinding" /> 
        </property> 
    </bean> 


我这么配置的,怎么不行呢?

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="webBindingInitializer">
			<bean class="com.*.*.web.interceptor.BindingInitializer" />
		</property>
	</bean>



其他地方不用配置吧?这样会出现这个错误
2011-6-9 9:03:28 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet dispatcherServlet threw exception
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'record' on field 'endTime': rejected value [2011-06-09 23:59:59]; codes [typeMismatch.record.endTime,typeMismatch.endTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [record.endTime,endTime]; arguments []; default message [endTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "2011-06-09 23:59:59" from type 'java.lang.String' to type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException]
Field error in object 'record' on field 'startTime': rejected value [2011-06-01 00:00:00]; codes [typeMismatch.record.startTime,typeMismatch.startTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [record.startTime,startTime]; arguments []; default message [startTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'startTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "2011-06-01 00:00:00" from type 'java.lang.String' to type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException]
	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:810)
	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:359)
	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
	at java.lang.Thread.run(Thread.java:619)


首先,你为什么要这样写com.*.*.web.interceptor.BindingInitializer,你不能确定你的BindingInitializer具体路径?你的BindingInitializer是怎么写的啊?贴出来看一下,是用的spring自带的日期的属性编辑器还是自定义的?
0 请登录后投票
   发表时间:2011-06-09   最后修改:2011-06-09
太阳神喻 写道

首先,你为什么要这样写com.*.*.web.interceptor.BindingInitializer,你不能确定你的BindingInitializer具体路径?你的BindingInitializer是怎么写的啊?贴出来看一下,是用的spring自带的日期的属性编辑器还是自定义的?



public class BindingInitializer implements WebBindingInitializer {

	public void initBinder(WebDataBinder binder, WebRequest arg1) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, false));
	}

}


前面有公司名,不好写出来。所以用×号代替了。
不管是用自定义的还是spring自带的,都出现这个问题,我还发现,如果这个写在了最前面,会出现另外一个错误,直接登录页面都不能进入了。

<?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:mvc="http://www.springframework.org/schema/mvc" 
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" 
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd	
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
       <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="webBindingInitializer">
			<bean class="com.*.*.web.interceptor.BindingInitializer" />
		</property>
	</bean>

	<!-- 自动搜索@Component , @Controller , @Service , @Repository等标注的类 -->
	<context:component-scan base-package="com.*.*.web.*" />
	<!-- controller层的属性和配置文件读入 ,多个用逗号隔开-->
	<context:property-placeholder location="classpath:/config/others/config.properties" />
	<!-- Configures support for @Controllers -->
	<mvc:annotation-driven />
0 请登录后投票
   发表时间:2011-06-09  
写的不错了。我抽时间也学习下
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics