²©Ö÷½éÉÜ£º?ÔÚÖ°JavaÑз¢¹¤³Ìʦ¡¢×¨×¢ÓÚ³ÌÐòÉè¼Æ¡¢Ô´Âë·ÖÏí¡¢¼¼Êõ½»Á÷¡¢×¨×¢ÓÚJava¼¼ÊõÁìÓòºÍ±ÏÒµÉè¼Æ?
ÏîÄ¿Ãû³Æ
servletÐìÖÝÂÃÓÎÍøÕ¾¹ÜÀíϵͳ
ÊÓÆµÐ§¹û
https://www.bilibili.com/video/BV1YL4y1w72d/
ϵͳ˵Ã÷
4.2.1 ǰ̨½çÃæ
ÏÔʾ½çÃæ,Æä¹¦ÄÜÈçÏÂ:
(1)ÐìÖÝÂÃÓξ°ÇøµÄÐÅÏ¢ÏÔʾ:ÏÔʾ×î½üµÄ¶¯Ì¬µÄÂÃÓξ°µã,ÐìÖÝ×î½üµÄÏà¹ØÐÂÎÅ,µÈµÈ¡£
(2)ÐÅÏ¢½»»¥,¿ÉÒÔÌá½»Ò»¸öÏûÏ¢º¯Êý,¿ÉÒԵõ½ÓйØÂÃÓξ°µãºÍ½¨ÒéµÄÍøÕ¾ÏµÍ³¡£
ǰ̨½çÃæÉè¼ÆÈçÏÂͼËùʾ£º
ͼ4-2 ǰ̨Éè¼ÆÍ¼

±à¼
4.2.2 ºǫ́¹ÜÀí
¹ÜÀíµÄ±³¾°ÏÂ,Æä¹¦ÄÜÈçÏÂ:
(1)¸öÈËÐÅÏ¢¹ÜÀí:¹ÜÀíÔ±µÇ¼ºÍ¸öÈËÐÅÏ¢,ÃÜÂë,ºÍ¸Ä±ä;
(2)ÐÅÏ¢¹ÜÀí:ÉÏ´«µÄÐìÖÝÐÂÎÅÐÅÏ¢,²¢¿ÉÒÔɾ³ýºÍ±à¼ÒÔǰµÄÏûÏ¢;
(3)¾°Çø¹ÜÀí:ÐìÖݸ÷¾°µãµÄÖ´ÐÐÌí¼Ó¡¢É¾³ýºÍ±à¼;
(4)ÁôÑÔ°å¹ÜÀí:Óû§ÐÅÏ¢µÄ²é¿´ºÍɾ³ý¹ÜÀí;
(5)ͨ¹ýÕÕÆ¬¹ÜÀí:Ç°Ì¨Ò³ÃæÏÔʾµãԲͼ¡£
ºǫ́¹ÜÀí½çÃæÉè¼ÆÈçͼ4 - 3Ëùʾ£º

±à¼
ͼ4-3 ºǫ́Éè¼ÆÍ¼
»·¾³ÐèÒª
1.ÔËÐл·¾³£º×îºÃÊÇjava jdk 1.8£¬ÎÒÃÇÔÚÕâ¸öƽ̨ÉÏÔËÐеġ£ÆäËû°æ±¾ÀíÂÛÉÏÒ²¿ÉÒÔ¡£
2.IDE»·¾³£ºIDEA£¬Eclipse,Myeclipse¶¼¿ÉÒÔ¡£ÍƼöIDEA;
3.tomcat»·¾³£ºTomcat 7.x,8.x,9.x°æ±¾¾ù¿É
4.Ó²¼þ»·¾³£ºwindows 7/8/10 1GÄÚ´æÒÔÉÏ£»»òÕß Mac OS£»
5.Êý¾Ý¿â£ºMySql 5.7°æ±¾£»
6.ÊÇ·ñMavenÏîÄ¿£º·ñ£»
¼¼ÊõÕ»
1. ºó¶Ë£ºSpring+SpringMVC+Mybatis
2. ǰ¶Ë£ºJSP+CSS+JavaScript+jQuery
ʹÓÃ˵Ã÷
1. ʹÓÃNavicat»òÕ߯äËü¹¤¾ß£¬ÔÚmysqlÖд´½¨¶ÔÓ¦Ãû³ÆµÄÊý¾Ý¿â£¬²¢µ¼ÈëÏîÄ¿µÄsqlÎļþ£»
2. ʹÓÃIDEA/Eclipse/MyEclipseµ¼ÈëÏîÄ¿£¬Eclipse/MyEclipseµ¼Èëʱ£¬ÈôΪmavenÏîÄ¿ÇëÑ¡Ôñmaven;
ÈôΪmavenÏîÄ¿£¬µ¼Èë³É¹¦ºóÇëÖ´ÐÐmaven clean;maven installÃüÁȻºóÔËÐУ»
3. ½«ÏîÄ¿ÖÐspringmvc-servlet.xmlÅäÖÃÎļþÖеÄÊý¾Ý¿âÅäÖøÄΪ×Ô¼ºµÄÅäÖÃ;
4. ÔËÐÐÏîÄ¿£¬ÔÚä¯ÀÀÆ÷ÖÐÊäÈëhttp://localhost:8080/ µÇ¼
ÔËÐнØÍ¼

±à¼
±à¼
±à¼
±à¼
±à¼
±à¼
±à¼
±à¼
±à¼
±à¼
±à¼
±à¼
Óû§¹ÜÀí¿ØÖÆ²ã:
package com.houserss.controller;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import com.houserss.common.Const;
import com.houserss.common.Const.Role;
import com.houserss.common.ServerResponse;
import com.houserss.pojo.User;
import com.houserss.service.IUserService;
import com.houserss.service.impl.UserServiceImpl;
import com.houserss.util.MD5Util;
import com.houserss.util.TimeUtils;
import com.houserss.vo.DeleteHouseVo;
import com.houserss.vo.PageInfoVo;
/**
* Created by admin
*/
@Controller
@RequestMapping("/user/")
public class UserController {
@Autowired
private IUserService iUserService;
/**
* Óû§µÇ¼
* @param username
* @param password
* @param session
* @return
*/
@RequestMapping(value = "login.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<User> login(User user,String uvcode, HttpSession session){
String code = (String)session.getAttribute("validationCode");
if(StringUtils.isNotBlank(code)) {
if(!code.equalsIgnoreCase(uvcode)) {
return ServerResponse.createByErrorMessage("ÑéÖ¤Âë²»ÕýÈ·");
}
}
ServerResponse<User> response = iUserService.login(user.getUsername(),user.getPassword());
if(response.isSuccess()){
session.setAttribute(Const.CURRENT_USER,response.getData());
}
return response;
}
}

¹ÜÀíÔ±¹ÜÀí¿ØÖÆ²ã:
package com.sxl.controller.admin; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.sxl.controller.MyController; @Controller("adminController") @RequestMapping(value = "/admin") public class AdminController extends MyController { @RequestMapping(value = "/index") public String frame(Model model, HttpServletRequest request)throws Exception { return "/admin/index"; } @RequestMapping(value = "/main") public String main(Model model, HttpServletRequest request)throws Exception { return "/admin/main"; } @RequestMapping(value = "/tj1") public String tj1(Model model, HttpServletRequest request)throws Exception { String sql="select DATE_FORMAT(insertDate,'%Y-%m-%d') dates,sum(allPrice) price from t_order order by DATE_FORMAT(insertDate,'%Y-%m-%d') desc"; List<Map> list = db.queryForList(sql); model.addAttribute("list", list); System.out.println(list); return "/admin/tj/tj1"; } @RequestMapping(value = "/password") public String password(Model model, HttpServletRequest request)throws Exception { return "/admin/password"; } @RequestMapping(value = "/changePassword") public ResponseEntity<String> loginSave(Model model,HttpServletRequest request,String oldPassword,String newPassword) throws Exception { Map admin = getAdmin(request); if(oldPassword.equals(admin.get("password").toString())){ String sql="update t_admin set password=? where id=?"; db.update(sql, new Object[]{newPassword,admin.get("id")}); return renderData(true,"1",null); }else{ return renderData(false,"1",null); } } }
ÐÞ¸ÄÃÜÂëÒµÎñÂß¼:
package com.sxl.controller.admin;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.sxl.controller.MyController;
@Controller("userController")
@RequestMapping(value = "/user")
public class UserController extends MyController {
@RequestMapping(value = "/index")
public String frame(Model model, HttpServletRequest request)throws Exception {
return "/user/index";
}
@RequestMapping(value = "/main")
public String main(Model model, HttpServletRequest request)throws Exception {
return "/user/main";
}
@RequestMapping(value = "/password")
public String password(Model model, HttpServletRequest request)throws Exception {
return "/user/password";
}
@RequestMapping(value = "/changePassword")
public ResponseEntity<String> loginSave(Model model,HttpServletRequest request,String oldPassword,String newPassword) throws Exception {
Map user = getUser(request);
if(oldPassword.equals(user.get("password").toString())){
String sql="update t_user set password=? where id=?";
db.update(sql, new Object[]{newPassword,user.get("id")});
return renderData(true,"1",null);
}else{
return renderData(false,"1",null);
}
}
@RequestMapping(value = "/mine")
public String mine(Model model, HttpServletRequest request)throws Exception {
Map user =getUser(request);Map map = db.queryForMap("select * from t_user where id=?",new Object[]{user.get("id")});model.addAttribute("map", map); return "/user/mine";
}
@RequestMapping(value = "/mineSave")
public ResponseEntity<String> mineSave(Model model,HttpServletRequest request,Long id
,String username,String password,String name,String gh,String mobile) throws Exception{
int result = 0;
String sql="update t_user set name=?,gh=?,mobile=? where id=?";
result = db.update(sql, new Object[]{name,gh,mobile,id});
if(result==1){
return renderData(true,"²Ù×÷³É¹¦",null);
}else{
return renderData(false,"²Ù×÷ʧ°Ü",null);
}
}
}

ͨÓùÜÀíÄ£¿é:
package com.sxl.controller;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import com.sxl.util.JacksonJsonUtil;
import com.sxl.util.StringUtil;
import com.sxl.util.SystemProperties;
public class BaseController {
public static final Long EXPIRES_IN = 1000 * 3600 * 24 * 1L;// 1Ìì
@Autowired
private SystemProperties systemProperties;
/**
* »ñµÃÅäÖÃÎļþÄÚÈÝ
*/
public String getConfig(String key) {
return systemProperties.getProperties(key);
}
/**
* ·µ»Ø·þÎñÆ÷µØÖ· like http://192.168.1.1:8441/UUBean/
*/
public String getHostUrl(HttpServletRequest request) {
String hostName = request.getServerName();
Integer hostPort = request.getServerPort();
String path = request.getContextPath();
if (hostPort == 80) {
return "http://" + hostName + path + "/";
} else {
return "http://" + hostName + ":" + hostPort + path + "/";
}
}
/***
* »ñÈ¡µ±Ç°µÄwebsite·¾¶ String
*/
public static String getWebSite(HttpServletRequest request) {
String returnUrl = request.getScheme() + "://"
+ request.getServerName();
if (request.getServerPort() != 80) {
returnUrl += ":" + request.getServerPort();
}
returnUrl += request.getContextPath();
return returnUrl;
}
/**
* ³õʼ»¯HTTPÍ·.
*
* @return HttpHeaders
*/
public HttpHeaders initHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
MediaType mediaType = new MediaType("text", "html",
Charset.forName("utf-8"));
headers.setContentType(mediaType);
return headers;
}
/**
* ·µ»Ø ÐÅÏ¢Êý¾Ý
*
* @param status
* @param msg
* @return
*/
public ResponseEntity<String> renderMsg(Boolean status, String msg) {
if (StringUtils.isEmpty(msg)) {
msg = "";
}
String str = "{\"status\":\"" + status + "\",\"msg\":\"" + msg + "\"}";
ResponseEntity<String> responseEntity = new ResponseEntity<String>(str,
initHttpHeaders(), HttpStatus.OK);
return responseEntity;
}
/**
* ·µ»ØobjÊý¾Ý
*
* @param status
* @param msg
* @param obj
* @return
*/
public ResponseEntity<String> renderData(Boolean status, String msg,
Object obj) {
if (StringUtils.isEmpty(msg)) {
msg = "";
}
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\"status\":\"" + status + "\",\"msg\":\"" + msg + "\",");
sb.append("\"data\":" + JacksonJsonUtil.toJson(obj) + "");
sb.append("}");
ResponseEntity<String> responseEntity = new ResponseEntity<String>(
sb.toString(), initHttpHeaders(), HttpStatus.OK);
return responseEntity;
}
/***
* »ñÈ¡IP£¨Èç¹ûÊǶ༶´úÀí£¬ÔòµÃµ½µÄÊÇÒ»´®IPÖµ£©
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip != null && ip.length() > 0) {
String[] ips = ip.split(",");
for (int i = 0; i < ips.length; i++) {
if (!"unknown".equalsIgnoreCase(ips[i])) {
ip = ips[i];
break;
}
}
}
return ip;
}
/**
* ¹ú¼Ê»¯»ñµÃÓïÑÔÄÚÈÝ
*
* @param key
* ÓïÑÔkey
* @param args
* @param argsSplit
* @param defaultMessage
* @param locale
* @return
*/
public static String getLanguage(String key, String args, String argsSplit,
String defaultMessage, String locale) {
String language = "zh";
String contry = "cn";
String returnValue = defaultMessage;
if (!StringUtil.isEmpty(locale)) {
try {
String[] localeArray = locale.split("_");
language = localeArray[0];
contry = localeArray[1];
} catch (Exception e) {
}
}
try {
ResourceBundle resource = ResourceBundle.getBundle("lang.resource",
new Locale(language, contry));
returnValue = resource.getString(key);
if (!StringUtil.isEmpty(args)) {
String[] argsArray = args.split(argsSplit);
for (int i = 0; i < argsArray.length; i++) {
returnValue = returnValue.replace("{" + i + "}",
argsArray[i]);
}
}
} catch (Exception e) {
}
return returnValue;
}
}












;










