SpringMVC Demo

用Spring MVC实现用户登录的完整实例      本例子是再Eclipse中建立一个Tomcat工程,来讲解Spring MVC 的全过程,实例代码如下:
<一>编写日记文件放在myMVC/WEB-INF/src下

#指定日志输入文件的大小

log4j.appender.stdout.MaxFileSize=500KB

log4j.appender.stdout.MaxBackupIndex=50

log4j.appender.stdout.Append=true

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=[%-5p]%d{yyyy-MM-ddHH:mm:ss}%c-%m%n

#定义log4j的显示方式

log4j.appender.A1=org.apache.log4j.RollingFileAppender

#指定日志输入文件的名称

log4j.appender.A1.File=org.log

#指定日志输入文件的大小

log4j.appender.A1.MaxFileSize=500KB

log4j.appender.A1.MaxBackupIndex=50

log4j.appender.A1.Append=true

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%d{ISO8601}-[%P][%C{1}]-%m%n

#定义log4j的显示方式

log4j.appender.A1=org.apache.log4j.RollingFileAppender

#指定日志输入文件的名称

log4j.appender.A1.File=gc.log

#指定日志输入文件的大小

log4j.appender.gc.MaxFileSize=500KB

log4j.appender.gc.MaxBackupIndex=50

log4j.appender.gc.Append=true

log4j.appender.gc.layout=org.apache.log4j.PatternLayout

log4j.appender.gc.layout.ConversionPattern=%d{ISO8601}-[%P][%C{1}]-%m%n

<二>配置web.xml



<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

version="2.4"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <servlet>

     <servlet-name>dispatcherServlet</servlet-name>

     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

     <!-- 初始化参数 -->

     <init-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>/WEB-INF/dispatcherServlet-servlet.xml</param-value>

     </init-param>

  </servlet>

  <servlet-mapping>

     <servlet-name>dispatcherServlet</servlet-name>

     <url-pattern>*.do</url-pattern>

  </servlet-mapping>

  <taglib>

     <taglib-uri>/spring</taglib-uri>

     <taglib-location>/WEB-INF/spring.tld</taglib-location>

  </taglib>

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

</web-app>


<三>编写登录页面myMVC/gc/jsp目录下login.jsp



<%@taglib prefix="spring" uri="/spring"%>

<%@ page contentType="text/html;charset=GBK"%>

<html>

<head><title><spring:message code="title"/></title></head>

<body>

   <form action="/myMVC/login.do" name="User" method="post">

      <spring:bind path="command.username">

         <spring:message code="username"></spring:message>

         <input type="text" name="${status.expression }"value="${status.value }"/>

         <br>

         <font color="red"><b>${status.errorMessage }</b></font><br>

      </spring:bind>

      <spring:bind path="command.password">

         <spring:message code="password"></spring:message>

         <input type="password" name="${status.expression }"value="${status.value }"/>

         <br>

         <font color="red"><b>${status.errorMessage }</b></font><br>

      </spring:bind>

      <spring:bind path="command.password2">

         <spring:message code="password2"></spring:message>

         <input type="password" name="${status.expression }"value="${status.value }"/>

         <br>

         <font color="red"><b>${status.errorMessage }</b></font><br>        

      </spring:bind>

      <input type="submit" value="<spring:messagecode='submit'/>"/>

   </form>

</body>

</html>


<四>编写显示成功的页面myMVC/gc/jsp目录下success.jsp


<%@taglib prefix="spring" uri="/spring"%>

<%@page contentType="text/html;charset=GBK"%>

<html>

<head><title><spring:message code="title"></spring:message></title></head>

<body>

   <spring:bind path="command.username">

      <h3><spring:message code="welcome"></spring:message>{status.value }<spring:message code="loginSuccess"/></h3><br>

   </spring:bind>

</body>

</html>


<五>编写存放用户登录信息的Bean,在com.gc.action包中建立Java文件User.java



package com.gc.action;

publicclass User {

    private String username=null;

    private String password=null;

    private String password2=null;

    public String getPassword() {

       returnpassword;

    }

    publicvoid setPassword(String password) {

       this.password = password;

    }

    public String getPassword2() {

       returnpassword2;

    }

    publicvoid setPassword2(String password2) {

       this.password2 = password2;

    }

    public String getUsername() {

       returnusername;

    }

    publicvoid setUsername(String username) {

       this.username = username;

    }

}


<六>在com.gc.action包下编写用户验证类UserValidator.java


package com.gc.action;

import com.gc.action.User;

import org.springframework.validation.Validator;

import org.springframework.validation.Errors;

publicclass UserValidator implements Validator {

    publicboolean supports(Class clazz){

       return clazz.equals(User.class);

    }

    publicvoid validate(Object obj,Errors errors){

       User user=(User)obj;

       if(!"tang".equals(user.getUsername())){

           errors.rejectValue("username", "usernameerror", null, "用户名不正确");

       }

       if(!"123456".equals(user.getPassword())){

           errors.rejectValue("password", "passworderror", null, "密码不正确");

       }

       if(!user.getPassword().equals(user.getPassword2())){

           errors.rejectValue("password2", "password2error", null, "2次输入密码不一致");

       }

    }

}


<七>在com.gc.action包下编写用户登录逻辑Login.java


package com.gc.action;

import java.util.Map;

import org.apache.log4j.Logger;

import org.springframework.validation.BindException;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.SimpleFormController;

publicclass Login extends SimpleFormController{

    private Logger logger=Logger.getLogger(this.getClass().getName());

    public ModelAndView onSubmit(Object command,BindException errors)throws Exception{

       User user=(User)command;

       Map modle=errors.getModel();

       modle.put("user", user);

       returnnew ModelAndView(getSuccessView(),modle);

    }

}


<八>myMVC/WEB-INF目录下编写配置文件dispatcherServlet-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"

"http:www.springframework.org/dtd/spring-bean.dtd">

<beans>

   <!-- 定义国际化消息 -->

   <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">

      <property name="basename">

         <value>messages</value>

      </property>

   </bean>

   <!-- 定义映射 -->

   <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

      <property name="mapping">

         <props>

            <prop key="login.do">login</prop>

         </props>

      </property>

   </bean>

   <!-- 定义视图及路径 -->

   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

      <property name="viewClass">

         <value>org.springframework.web.servlet.view.InternalResourceView</value>

      </property>

      <!-- JSP都放在WEB-INF/jsp目录下 -->

      <property name="prefix">

         <value>/WEB-INF/jsp</value>

      </property>

      <!-- JSP页面的后缀都四.JSP -->

      <property name="suffix">

         <value>.jsp</value>

      </property>

   </bean>

   <!-- 定义控制器 -->

   <bean id="login" class="com.gc.action.Login">

      <property name="commandClass">

         <value>com.gc.action.User</value>

      </property>

      <!-- 指定验证类 -->

      <property name="validator">

         <ref bean="userValidator"/>

      </property>

      <!-- 指定失败要返回的页面 -->

      <property name="formView">

         <value>login</value>

      </property>

      <property name="successView">

         <value>success</value>

      </property>

   </bean>

   <!-- 定义验证类 -->

   <bean id="userValidator" class="com.gc.action.UserValidator"></bean>

</beans>


<九>myMVC/WEB-INF/src目录下编写资源文件messages.properties及messages_en_US.properties
messages.properties

title=SpringMVC实例

username=输入用户名:

password=输入密码:

password2=确认密码:

submit=提交

welcome=欢迎

loginSuccess=登录成功

usernameerror=用户名不正确

passworderror=密码不正确

doublepassword=2次密码不一致
   native2ascii工具转码后

title=SpringMVC\u5b9e\u4f8b

username=\u8f93\u5165\u7528\u6237\u540d:

password=\u8f93\u5165\u5bc6\u7801:

password2=\u786e\u8ba4\u5bc6\u7801:

submit=\u63d0\u4ea4

welcome=\u6b22\u8fce

loginSuccess=\u767b\u5f55\u6210\u529f

usernameerror=\u7528\u6237\u540d\u4e0d\u6b63\u786e

passworderror=\u5bc6\u7801\u4e0d\u6b63\u786e

doublepassword=2\u6b21\u5bc6\u7801\u4e0d\u4e00\u81f4
messages_en_US.properties


title=SpringMVC

username=username

password=password

password2=password2

submit=submit

welcome=welcome

loginSuccess=loginSuccess

usernameerror=usernameerror

passworderror=passworderror

doublepassword=doublepassworderror

转自网络

<script type="text/javascript"></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

你可能感兴趣的:(spring,log4j,bean,jsp,servlet)