eclipse SpringMVC项目
乌托邦项目管理
项目结构图
配置文件
web.xml
<?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"
xmlns:web="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" version="3.0">
<!-- <servlet-mapping> -->
<!-- <servlet-name>default</servlet-name> -->
<!-- <url-pattern>/js/*</url-pattern> -->
<!-- <url-pattern>/css/*</url-pattern> -->
<!-- <url-pattern>/images/*</url-pattern> -->
<!-- <url-pattern>/fonts/*</url-pattern> -->
<!-- <url-pattern>*.html</url-pattern> -->
<!-- <url-pattern>*.gif</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>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</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:spring-dao.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
<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>
</web-app>
spring-dao.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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--引入属性文件 -->
<context:property-placeholder
location="classpath:configuration.properties" />
<!--定义数据源dbcp -->
<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<!-- 以下配置可以省略 -->
</bean>
<!--定义jdbcTemplate -->
<bean
id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 包扫描 -->
<context:component-scan base-package="com.hd.dao"/>
<!--事务配置 -->
<!--声明式事务 Start -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven
transaction-manager="transactionManager" proxy-target-class="true" />
<!--声明式事务 End -->
</beans>
springMVC-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 启用spring mvc 注解 如:@Controller @Service @Autowired -->
<mvc:annotation-driven />
<!-- <mvc:default-servlet-handler/> -->
<!--配置静态资源:spring mvc拦截所有的请求,所有要对我们访问的资源进行处理,否则将不生效 -->
<mvc:resources mapping="/resources/**/" location="/resources/" />
<mvc:resources mapping="/error/**/" location="/WEB-INF/jsp/error/" />
<!-- 自动扫描的包名 ,使Spring支持自动检测组件,如注解的Controller -->
<context:component-scan
base-package="com.hd.controller" />
<context:component-scan
base-package="com.hd.service" />
<!-- 视图解析器:定义跳转的文件的前后缀 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 拦截器配置 -->
<!-- <mvc:interceptors> -->
<!-- <mvc:interceptor > -->
<!-- <mvc:mapping path="/users/**"/> -->
<!-- <mvc:mapping path="/city/**"/> -->
<!-- <mvc:mapping path="/shop/**"/> -->
<!-- <mvc:exclude-mapping path="/users/login"/> -->
<!-- <mvc:exclude-mapping path="/users/logintest"/> -->
<!-- <mvc:exclude-mapping path="/users/image"/> -->
<!-- <bean class="com.hd.interceptor.MyInterceptor"></bean> -->
<!-- </mvc:interceptor> -->
<!-- </mvc:interceptors> -->
<!-- 配置全局异常 -->
<!-- <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> -->
<!-- <property name="exceptionMappings"> -->
<!-- <props> -->
<!-- error是逻辑视图名称 -->
<!-- <prop key="java.lang.ArithmeticException">/error/error</prop> -->
<!-- <prop key="java.lang.NullPointerException">/error/error</prop> -->
<!-- 处理所有异常 -->
<!-- <prop key="java.lang.Exception">/error/error</prop> -->
<!-- </props> -->
<!-- </property> -->
<!-- </bean> -->
<!-- 文件上传,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置文件上传最大尺寸为50MB -->
<property name="maxUploadSize" value="52428800" />
<property name="defaultEncoding" value="utf-8" />
</bean>
<mvc:view-controller path="/users/right" view-name="right"/>
</beans>
log4j
#log4j.rootLogger=INFO,Console
log4j.logger.com.aishang.dao=DEBUG
log4j.logger.com.aishang.service=DEBUG
log4j.logger.com.aishang.controller=DEBUG
#log4j.logger.org.springframework.jdbc.core.JdbcTemplate=debug
#log4j.logger.com.mybatis3=DEBUG
#console jdbc
#log4j.logger.jdbc.sqlonly=DEBUG,console
log4j.logger.jdbc.sqltiming=INFO,console
log4j.logger.jdbc.connection=INFO,console,WARN
log4j.logger.jdbc.sqlonly=WARN
log4j.logger.jdbc.resultsettable=INFO
log4j.logger.jdbc.resultset=WARN
log4j.logger.jdbc.audit=WARN
#log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
log4j.rootLogger= INFO , console , R
log4j.logger.com.terren.terrenReport=INFO, stdout, R
log4j.logger.com.mchange.v2.log.MLog=ERROR, stdout
#stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %-5p [%t] %37c %3x - %m%n
#console
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
#log4j.appender.console.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%p]-[%c] %m%n
configuration.properties
#属性文件
#格式
#属性=值
#.properties
jdbc.driver=com.mysql.jdbc.Driver
#jdbc.driver=net.sf.log4jdbc.DriverSpy
jdbc.url=jdbc:mysql://localhost:3306/wtb_db?useUnicode=true&characterEncoding=UTF-8
#jdbc.url=jdbc:log4jdbc:mysql://localhost:3306/wtb_db?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
pageSize=5
工具类
为controller设置一些属性,减少重复操作
BaseController.java
package com.hd.controller.base;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
public class BaseController {
/**
* 重定向字符串
*/
protected static final String REDIRECT="redirect:";
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpSession session;
protected Map<String,Object> map;
protected Model model;
//在这个注解的时方法会在每个controller方法执行前执行
@ModelAttribute
private void init(HttpServletRequest request,HttpServletResponse response,Map<String,Object> map,Model model) {
//System.out.println("会在所有方法执行前执行!!");
this.request=request;
this.response=response;
this.session=request.getSession();
this.map=map;
this.model=model;
}
/**
* 获取项目的物理路径
* @return 路径
*/
protected String getRealPath() {
return session.getServletContext().getRealPath("/");
}
//在表单提交时先执行这个注解的方法,进行表单数据的转换
@InitBinder
public void initBinder(HttpServletRequest request,ServletRequestDataBinder binder)throws Exception
{
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
binder.registerCustomEditor(Date.class, dateEditor);
}
}
controller文件继承BaseController
public class UsersController extends BaseController{}
文件上传
UploadFile
package com.hd.util;
import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
/**
*
* @author Teatcher Zhang
*
*/
public class UploadFile {
/**
* 文件上传通用类
* @param files
* @param request 请求对象
* @param upFilePath 上传的文件的路径:如:upload
* @return String ,返回上传的文件名称
* @throws Exception
*
*/
public static String fileUp(MultipartFile files,HttpServletRequest request,String upFilePath)
{
String newFileName=null;
try
{
//files[i].isEmpty();是否有上传文件
if(files.getSize()!=0)
{
String orignalName=files.getOriginalFilename();//获取上传文件的原名
String suffix=orignalName.substring(orignalName.lastIndexOf("."));//扩展名称
newFileName=UUID.randomUUID()+suffix;//新文件名称
//流准备上传文件
//String a=request.getSession().getServletContext().getRealPath("/")+"/fileupload/"+newFileName;//得到物理路径
String a=request.getSession().getServletContext().getRealPath("/")+"/"+upFilePath+"/"+newFileName;//得到物理路径
//J:\tomcat7\apache-tomcat-7.0.90\webapps\demo20180806\/fileupload/4c64b22a-e135-474c-881f-92639982a426.jpg
//File saveFile=new File(request.getSession().getServletContext().getRealPath("/")+"/fileupload/"+newFileName);
File saveFile=new File(a);
//上传文件
FileUtils.copyInputStreamToFile(files.getInputStream(), saveFile);
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return newFileName;
}
}
分页通用类
pages.java
package com.hd.util;
import java.util.List;
/**
* 分页通用类
* @author Administrator
*
*/
public class Pages<T> {
//1>first 首页=1
private int first;
//2>next 下一页: if(总页数>当前页) {next=当前页+1} else{next=总页数}
private int next;
//3>pre 前一页: if(当前页>1) {pre=当前页-1} else {pre=1}
private int pre;
//4>last 末页=总页数
private int last;
//5>page 当前页
private int page;
//6>rowCount 总记录条数
private int rowCount;
//7>pages 总页数=rowCount%pageSize==0?rowCount/pageSize:rowCount/pageSize+1;
private int pages;
//8>pageSize每页大小
private int pageSize=Common.PAGESIZE;
//9>方法:完成给1,2,3,4属性赋值:
//10>List<T> list;存放查询结果
private List<T> list;
public int getFirst() {
return first;
}
public void setFirst(int first) {
this.first = first;
}
public int getNext() {
return next;
}
public void setNext(int next) {
this.next = next;
}
public int getPre() {
return pre;
}
public void setPre(int pre) {
this.pre = pre;
}
public int getLast() {
return last;
}
public void setLast(int last) {
this.last = last;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
/**
* 得到总记录条数
* @return
*/
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
//方法:完成给上面的属性赋值
/**
*
* @param page 当前页
* @param rowCount 总记录数
* @param list 查询结果
*/
public void calc(int page,int rowCount, List<T> list)
{
this.first=1;
this.pages=rowCount%pageSize==0?rowCount/pageSize:rowCount/pageSize+1;
this.last=pages;
this.pre=page>1?page-1:1;
this.list=list;
this.rowCount=rowCount;
this.next=pages>page?page+1:this.pages;
this.page=page;
// if(page>1)
// {
// this.pre=page-1;
// }
// else
// {
// this.pre=1;
// }
// if(pages>page)
// {
// this.next=page+1;
// }
// else
// {
// this.next=this.pages;
// }
}
public Pages(){}
public Pages(int page,int rowCount, List<T> list)
{
this.calc(page, rowCount, list);
}
}
生成验证码
package com.hd.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class RandomValidateCode {
public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
private Random random = new Random();
private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
// 1+6=?
// id text para an
// 1 1+6=? 7
private int width = 80;//图片宽
private int height = 26;//图片高
private int lineSize = 40;//干扰线数量
private int stringNum = 4;//随机产生字符数量
/*
* 获得字体
*/
private Font getFont(){
return new Font("Fixedsys",Font.CENTER_BASELINE,18);
}
/*
* 获得颜色
*/
private Color getRandColor(int fc,int bc){
if(fc > 255)
fc = 255;
if(bc > 255)
bc = 255;
int r = fc + random.nextInt(bc-fc-16);
int g = fc + random.nextInt(bc-fc-14);
int b = fc + random.nextInt(bc-fc-18);
return new Color(r,g,b);
}
/**
* 生成随机图片
*/
public void getRandcode(HttpServletRequest request,
HttpServletResponse response) {
HttpSession session = request.getSession();
//BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();//产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,18));
g.setColor(getRandColor(110, 133));
//绘制干扰线
for(int i=0;i<=lineSize;i++){
drowLine(g);
}
//绘制随机字符
String randomString = "";
for(int i=1;i<=stringNum;i++){
randomString=drowString(g,randomString,i);
}
session.removeAttribute(RANDOMCODEKEY);
session.setAttribute(RANDOMCODEKEY, randomString);
System.out.println(randomString);
g.dispose();
try {
ImageIO.write(image, "JPEG", response.getOutputStream());//将内存中的图片通过流动形式输出到客户端
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 绘制字符串
*/
private String drowString(Graphics g,String randomString,int i){
g.setFont(getFont());
g.setColor(new Color(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
String rand = String.valueOf(getRandomString(random.nextInt(randString.length())));
randomString +=rand;
g.translate(random.nextInt(3), random.nextInt(3));
g.drawString(rand, 13*i, 16);
return randomString;
}
/*
* 绘制干扰线
*/
private void drowLine(Graphics g){
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
g.drawLine(x, y, x+xl, y+yl);
}
/*
* 获取随机的字符
*/
public String getRandomString(int num){
return String.valueOf(randString.charAt(num));
}
}
关键操作
ajax实现城市下拉列表三级联动
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="/resources/css/main.css" />
<script type="text/javascript" src="/resources/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
sheng();
$("#sheng").change(function shi(){
var cid=$("#sheng").val();
$("#shi").empty();
$.post("/city/selectcity",{"cid":cid,"state":"0"},function(data){
$.each(data,function(index,obj){
var option="<option value='"+obj.id+"'>"+obj.cityname+"</option>";
$("#shi").append(option);
});
},"json")
});
});
//省
function sheng(){
$.post("/city/selectcity",{"cid":"0","state":"1"},function(data){
$.each(data,function(index,obj){
var option="<option value='"+obj.id+"'>"+obj.cityname+"</option>";
$("#sheng").append(option);
});
},"json")
};
</script>
</head>
<body>
<form action="/city/insertAndDelete" >
<table class="cssTable">
<tr>
<th colspan="2" align="center" class="title">添加城市</th>
</tr>
<tr>
<td>选择省份</td>
<td>
<select id="sheng" class="search-select" >
<option value="-1">请选择</option>
</select>
</td>
</tr>
<tr>
<td>选择城市</td>
<td>
<select name="id" id="shi" class="search-select" >
<option value="-1">请选择</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input name="" type="button" value="返回" class="search-buttton search-add" οnclick="location.href='/city/select'" />
<input name="submit" type="submit" value="提交" class="search-buttton search-add" />
<input name="Input" type="reset" value="重置" class="search-buttton search-add" /> </td>
</tr>
</table>
</form>
</body>
</html>
下拉列表默认选中,及批量删除功能
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="/resources/css/main.css" />
<script type="text/javascript" src="/resources/bootstrap/js/jquery.min.js">
</script>
<script type="text/javascript" src="/resources/bootstrap/js/bootstrap.min.js">
</script>
<link rel="stylesheet" href="/resources/bootstrap/css/bootstrap.min.css">
<script type="text/javascript" src="/resources/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
function deleteme() {
if(confirm("确认删除么")){
return true;
}else{
return false;
}
}
$(function(){
//下拉列表默认选中
$("#cid").val("${cid}");
//实现全选功能
$("#ckall").click(function(){
var a=$("input[name=ckall]").prop("checked");
//alert(a);
$("input[name=c]").prop("checked",a);
});
//批量删除
$("#deleteall").click(function(){
var ids="";
$("input[name=c]:checked").each(function(){
ids+=$(this).val()+",";
})
//alert(ids);
location.href="/city/deleteall?ids="+ids;
});
});
</script>
</head>
<body>
<div class="search">
<a href="/city/insert" class="search-buttton search-add">新增</a>
<form action="/city/select">
<span class="span_text">选择省份</span>
<select name="cid" id="cid" class="search-select" >
<option value="-1">请选择</option>
<c:forEach items="${citys }" var="city">
<option value="${city.id }">${city.cityname }</option>
</c:forEach>
</select>
<input type="submit" value="查询" class="search-buttton search-search" />
</form>
<a href="#" id="deleteall" class="search-buttton search-deleteall">批量删除</a>
</div>
<table class="cssTable table-hover">
<tr>
<th><input type="checkbox" name="ckall" id="ckall" class="dcheckbox" /></th>
<th>编号</th>
<th>省份名称</th>
<th>城市名称</th>
<th>添加者</th>
<th>添加时间</th>
<th>操作</th>
</tr>
<c:forEach items="${pages.list }" var="city" varStatus="sts">
<tr>
<td><input type="checkbox" name="c" value="${city.id }" class="dcheckbox" /></td>
<td>${(pages.page-1)*pages.pageSize+sts.count }</td>
<td>${city.sheng }</td>
<td>${city.cityname }</td>
<td>${city.username }</td>
<td>${city.addtime }</td>
<td>
<a href="/city/seleteById?id=${city.id }" class="btn_update">改名</a>
<a href="/city/insertAndDelete?id=${city.id }" class="btn_delete" οnclick="return deleteme()">删除</a>
</td>
</tr>
</c:forEach>
<tr>
<td colspan="7">
<div class="foot-page" align="center">
<span>当前页/总页数 ${pages.page }/${pages.pages }</span>
<a href="/city/select?currpage=${pages.first }&cid=${cid }">首页</a>
<a href="/city/select?currpage=${pages.pre }&cid=${cid }">上一页</a>
<a href="/city/select?currpage=${pages.next }&cid=${cid }">下一页</a>
<a href="/city/select?currpage=${pages.last }&cid=${cid }">末页</a>
</div>
</tr>
</table>
</body>
</html>
表单验证
<script type="text/javascript">
function refresh(obj) {
obj.src = "users/image?"+Math.random();
}
$(function(){
})
function check(){
if($("#username").val()==""){
alert("请输入用户名!")
return false;
}
if($("#password").val()==""){
alert("请输入密码!");
return false;
}
return true;
}
</script>
<form class="form" id="entry_form" action="/users/logintest" οnsubmit="return check()" method="post">
<input type="text" placeholder="用户名" id="username" name="username" >
<input type="password" placeholder="密码" id="password" name="password">
<input name="vercode" placeholder="请输入验证码" type="text">
<!--验证码后面的随机数用于刷新验证码的.只有地址栏改变了,浏览器才新生刷新页面-->
<img id="im"title="点击更换" οnclick="this.src='/users/image?d='+Math.random();" src="/users/image" class="imgclass">
<br>
<button type="submit" id="entry_btn">登录</button>
<h1>${error }</h1>
<div id="prompt" class="prompt"></div>
</form>
<script type="text/javascript">
$(function(){
Victor("container", "output"); //登录背景函数
$("#username").focus();
//键盘按下enter事件注册绑定登录
$(document).keydown(function(event){
if(event.keyCode==13){
$("#entry_btn").click();
}
});
});
</script>
文件上传功能
file.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function lookImg(ele,imgId){
//获取input file的files文件数组;
//$('#filed')获取的是jQuery对象,.get(0)转为原生对象;
//这边默认只能选一个,但是存放形式仍然是数组,所以取第一个元素使用[0];
var file = ele.files[0];
//创建用来读取此文件的对象
var reader = new FileReader();
//使用该对象读取file文件
reader.readAsDataURL(file);
//读取文件成功后执行的方法函数
reader.οnlοad=function(e){
//读取成功后返回的一个参数e,整个的一个进度事件
console.log(e);
//选择所要显示图片的img,要赋值给img的src就是e中target下result里面
//的base64编码格式的地址
//alert(e.target.result);
document.getElementById(imgId).src = e.target.result;
}
}
</script>
</head>
<body>
<form action="/villa/testfileup" method="post" enctype="multipart/form-data">
文件上传:<input type="file" name="files" οnchange="lookImg(this,'img1');">
<br>
<img id="img1" width="300px" height="200px" src="" />
<input type="submit" value="上传文件">
</form>
</body>
</html>
模糊查询与动态拼接SQL语句
//jdbc模板
@Resource
private JdbcTemplate jdbcTemplate;
/**
* 分页查询
* @param currpage 当前页
* @param username 名字
* @return
*/
public List<Users> select(Integer currpage,String username,Integer online){
//String sql="select * from tb_users where username like ? limit "+(currpage-1)*Common.PAGESIZE+","+Common.PAGESIZE;
String sql="select * from tb_users where 1=1 ";
StringBuilder sb=new StringBuilder(sql);
List<String> list=new ArrayList<String>();
if(username!=null && !username.equals("")) {
sb.append(" and username like ? ");
list.add(username);
}
if(online!=-1) {
sb.append(" and online=? ");
list.add(online.toString());
}
sb.append(" limit "+(currpage-1)*Common.PAGESIZE+","+Common.PAGESIZE);
Object[] obj=list.toArray();
List<Users> list1=this.jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<Users>(Users.class),obj);
return list1;
}
拦截器
访问每个页面前检查用户是否登录
package com.hd.interceptor;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
//视图渲染后
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("视图渲染后");
}
//方法执行后
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("方法执行后");
}
//方法执行前
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2) throws Exception {
System.out.println("方法执行前");
//判断请求头文件中有没有X-Requested-With: XMLHttpRequest
HttpSession session =req.getSession();
if (req.getHeader("X-Requested-With")!=null && req.getHeader("X-Requested-With").equals("XMLHttpRequest") ) {
//是ajax请求
if (session.getAttribute("username")==null) {
//给回调函数赋值
PrintWriter out=resp.getWriter();
out.print("{\"msg\":\"no\"}");
out.flush();
out.close();
return false;
} else {
return true;
}
} else {
//非ajax请求
if (session.getAttribute("username")==null) {
session.setAttribute("error", "请登录");
resp.sendRedirect("/login.jsp");
return false;
} else {
return true;
}
}
}
}