Spring MVC配置

时间:2024-11-15 16:04:01

web配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ssmdemo1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
   <!-- 配置前端控制器 -->
  <servlet>
     <servlet-name>springmvc2</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:springmvc.xml</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
  </servlet>
  <!-- 验证码 -->
  <servlet>
   <servlet-name>Code</servlet-name>
   <servlet-class>com.gxa.bj.service.Code</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>Code</servlet-name>
   <url-pattern>/code</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
     <servlet-name>springmvc2</servlet-name>
     <url-pattern>*.action</url-pattern><!--配置的访问路径,一定是按照这种格式写  -->
  </servlet-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 解决post提交乱码的问题 -->
  <filter>
 <filter-name>CharacterEncodingFilter</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>
  </filter>
 <filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 
</web-app>

springmvc.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:p="http://www.springframework.org/schema/p"     xmlns:mvc="http://www.springframework.org/schema/mvc"     xmlns:context="http://www.springframework.org/schema/context"     xsi:schemaLocation="         http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd"         default-autowire="byName"         >  <!-- 用注解的方式 -->  <context:annotation-config>            <mvc:annotation-driven>            </mvc:annotation-driven>  </context:annotation-config>  <!-- 引入解析jstl的类 -->  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>  <!-- 将action里的类加入到spring中来 -->  <!-- <bean class="com.gxa.bj.action.UserAction">  </bean> -->  <!-- 在实际开发中采取的是包的扫描,将该包扫描到spring容器下 -->

<context:component-scan base-package="com.gxa.bj.action"></context:component-scan> </beans>

mybatis-config.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <mappers>
     <mapper resource="com/gxa/bj/model/UserInfoMapper.xml"/>
  </mappers>
</configuration>

applicationContext.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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.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.xsd"
    default-autowire="byName"
    > 
    <!-- 配置数据源-->
 <bean id="jdbcDataSource"
  class="com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name="driverClass">
   <value>oracle.jdbc.driver.OracleDriver</value>
  </property>
  <property name="jdbcUrl">
   <value>jdbc:oracle:thin:@127.0.0.1:1521:orcl</value>
  </property>
  <property name="user">
   <value>blogs</value>
  </property>
  <property name="password">
   <value>123</value>
  </property>
  <property name="initialPoolSize">
      <value>10</value>
  </property>
 </bean> 
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
      <property name="dataSource" ref="jdbcDataSource" /> 
      <property name="configLocation" value="classpath:mybatis-config.xml"></property> 
   </bean>
   <!--配置dao层 --> 
  <!--  <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
       <property name="mapperInterface" value="com.gxa.bj.dao.imp.UserMapper"></property>
       <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
   </bean> -->
   <!-- mapper接口的扫描,必须扫描到接口,扫描的原则是:所有扫描进Spring的Mapper对象,它的命名规则:
        首字母小写,后面的都是按照原有的接口名字定义。
        比如UserMapper接口扫描到spring里,id名为userMapper
    -->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
   <property name="basePackage" value="com.gxa.bj.dao.imp"></property>
   <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
 </bean>
   <!-- 配置Service层 -->
 <!--   <bean id="userInfoService" class="com.gxa.bj.service.UserInfoService">
       <property name="userMapper" ref="userMapper"></property>
   </bean>
   <bean id="typeInfoService" class="com.gxa.bj.service.TypeInfoService">
       <property name="typeInfoMapper" ref="typeInfoMapper"></property>
   </bean>
   <bean id="titleInfoService" class="com.gxa.bj.service.TitleInfoService">
       <property name="titleInfoMapper" ref="titleInfoMapper"></property>
   </bean> -->
 
  <!--  <context:component-scan base-package="com.gxa.bj.service"></context:component-scan> -->
   <!-- 在spring中声明事务的配置 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="jdbcDataSource" />
    </bean>
    <!-- 事务增强的配置 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 事务属性的配置,配置都哪些方法上 -->
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="add*"  rollback-for="Exception"/>
            <tx:method name="remove*" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="serviceCut" expression="execution(public * com.gxa.bj.service.*.*(..))" />
        <aop:advisor pointcut-ref="serviceCut" advice-ref="txAdvice" />
    </aop:config>
     <!-- 扫描service层到spring容器里 -->
   <context:component-scan base-package="com.gxa.bj.service"></context:component-scan>
</beans>

验证码实体类

package com.gxa.bj.service;

import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.util.Random;

import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

public class Code extends HttpServlet {

/**   * Constructor of the object.   */  public Code() {   super();  }

/**   * Destruction of the servlet. <br>   */  public void destroy() {   super.destroy(); // Just puts "destroy" string in log   // Put your code here  }   public Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色           Random random = new Random();           if (fc > 255) {               fc = 255;           }           if (bc > 255) {               bc = 255;           }           int r = fc + random.nextInt(bc - fc);           int g = fc + random.nextInt(bc - fc);           int b = fc + random.nextInt(bc - fc);           return new Color(r, g, b);       }     public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {    this.doPost(request, response);     }

public void doPost(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {

///response.setContentType("text/html;charset=utf-8");  // PrintWriter out = response.getWriter();   response.setContentType("image/gif");      //生成图像   int width=80,height=40;   BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);   Random random=new Random();   //设置界面不缓存   response.setHeader("Pragma", "No-cache");   response.setHeader("Cache-Control", "no-cache");   response.setDateHeader("Expires", 0);   //背景色     Graphics g=image.getGraphics();     g.setColor(Color.WHITE);     g.fillRect(0, 0, width, height);   //验证码   int sRand[]=new int[4];   String s="";   for(int i=0;i<4;i++){    sRand[i]=(int)(Math.random()*10);    s+=sRand[i];     g.setColor(new Color(20 + random.nextInt(110), 20 + random                       .nextInt(110), 20 + random.nextInt(110)));               // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成    }      //显示的数字;   for(int i=0;i<4;i++){    //g.setColor(Color.BLUE);    g.setFont(new Font("楷体", Font.BOLD, 18));    g.drawString(sRand[i]+"", 20*i, 30);       }   //干扰线   g.setColor(getRandColor(160, 200));   for(int i=0;i<30;i++){    int x = random.nextInt(width);    int y = random.nextInt(height);    int xl = random.nextInt(width);    int yl = random.nextInt(height);    g.drawLine(x, y, xl,yl);       }   request.getSession().setAttribute("checkCode", s);  // System.out.println(s);   g.dispose();   ImageIO.write(image, "PNG", response.getOutputStream());       }

public void init() throws ServletException {   // Put your code here  }

}

验证码jsp

<script type="text/javascript" src="js/jquery-easyui-1.3.1/jquery-1.8.0.min.js"></script>
  <script type="text/javascript">
  $(function(){
   $("#code").click(function(){
    this.src="code?now="+new Date();
   
   });
   
   $("#verify").blur(function(){
    var val=this.value;
    $.getJSON("checkCode",{"val":val},function(json){
     if(val==json.repeat){
      $("#sp").html("√");
      $("#sp").css("color","green");
      $(":submit").prop("disabled",false);
     }else{
      $("#sp").html("验证码错误");
      $("#sp").css("color","red");
      $(":submit").prop(" disabled",true);
     }
     
    },"json");
    return false;
   });
   
  });
 
 </script>

<img src="code" alt="看不清楚,点击刷新" width="80" height="21" id="code">

model层Mapper.xml增删改查

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxa.bj.dao.imp.UserMapper">
   <insert id="addItem" parameterType="com.gxa.bj.model.UserInfo">
       insert into UserInfo(userid,username,userpwd,useremail,useraddress,regreason)
       values(#{userid},#{userName},#{userPwd},#{userEmail},#{userAddress},#{regReason})
   </insert>
   <delete id="removeItem">
        delete from UserInfo where userId=#{id}
   </delete>
   <update id="updateItem" parameterType="com.gxa.bj.model.UserInfo">
         update UserInfo set userName=#{userName},userPwd=#{userPwd},
         userEmail=#{userEmail},userAddress=#{userAddress},
         regReason=#{regReason} where userId=#{userId}
   </update>
   <select id="getModel" resultType="com.gxa.bj.model.UserInfo">
         select * from userinfo where userid=#{id}
   </select>
   <select id="getUsers" parameterType="java.lang.String" resultType="com.gxa.bj.model.UserInfo" >
        select * from userinfo where userName like '%${value}%'
   </select>
   <select id="getList"  parameterType="com.gxa.bj.model.UserInfo" resultType="com.gxa.bj.model.UserInfo">
        Select * From userInfo
        <where>
        <if test="userName!=null">
            And userName like #{userName}
        </if>
        <if test="userId>0">
            And userId =#{userId}
        </if>
        <if test="userPwd!=null and userPwd!=''">
            And userPwd like #{userPwd}
        </if>
        </where>
   </select>
   <select id="getListByPage" parameterType="com.gxa.bj.model.UserInfoPage"  resultType="com.gxa.bj.model.UserInfo">
   
    Select u.*
    From (Select rownum as num, userinfo.*
          from userinfo
          <where>
           <if test="userName!=null">
            And userName like #{userName}
        </if>
        <if test="userId >= 10">
            And userId =#{userId}
        </if>
        <if test="userPwd!=null and userPwd !='' ">
            And userPwd like #{userPwd}
        </if>
        </where>
          ) u Where u.num between  #{startNum} and #{endNum}
 
   </select>
  
</mapper>