VS2015中添加mysql数据源时返回错误

VS2015中添加mysql数据源时返回错误提示:You have a usable connection already,但在VS的服务器资源管理器中的数据连接是能正常显示mysql数据库中的表结构的,求解!

图片说明

1个回答

关闭其他的项目,再试试.

daiti
daiti 首次开机打开VS,没打开过其它项目,都会出现这种情况的
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于VS2010中,新建了一个连接数据库的类文件,然后在asp.net后台代码里调用问题

如题,本人目前有很个web窗体,并且都要连接数据库,后来发现如果要更改连接服务器 或更改连接数据库时,改起来就很麻烦,有这么多窗体,一个个进里面改 所以我新建了一个公共类文件,在里面写了个调用连接数据库的方法 ![图片说明](https://img-ask.csdn.net/upload/201806/12/1528767128_524160.jpg) 然后在asp.net后台调用 ![图片说明](https://img-ask.csdn.net/upload/201806/12/1528767159_446532.jpg) 然后经过浏览调试之后报了个这么错误 ![图片说明](https://img-ask.csdn.net/upload/201806/12/1528767198_633576.jpg) 我上百度了查了下,有人说是因为没有new一个DS对象案例,可是图2里我不是有new一个吗,请问这问题该怎么解决,急急急~!!!!大佬和大神们快来~!!!

已经测试可以连接数据库插入数据,但是还是提示空指针异常

public class JDBCUtils { private static DataSource druidDataSource; static { try { //FileInputStream fileInputStream = new FileInputStream(new File("../src/druid.properties")); InputStream inputStream = JDBCUtils.class.getClassLoader().getSystemResourceAsStream("druid.properties"); Properties properties = new Properties(); properties.load(inputStream); druidDataSource = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() throws Exception { return druidDataSource.getConnection(); } //获取连接池对象 public static DataSource getDataSource(){ return druidDataSource; } } java.lang.NullPointerException at java.util.Properties$LineReader.readLine(Properties.java:434) at java.util.Properties.load0(Properties.java:353) at java.util.Properties.load(Properties.java:341) at cn.itcast.util.JDBCUtils.<clinit>(JDBCUtils.java:26) at cn.itcast.dao.AdminDAO.<init>(AdminDAO.java:23) at cn.itcast.web.servlet.LoginServlet.doPost(LoginServlet.java:24) at cn.itcast.web.servlet.LoginServlet.doGet(LoginServlet.java:40)

第一次数据库查询成功,第二次查询去失败了?

我编写一个Android应用,A页面拥有一个选项菜单,点击菜单中的选项,跳转到B页面,B页面接收从A页面传递的数据后,进行数据库查询,在本页面中显示相关内容。 B页面中通过动态添加View的方法,添加了按钮,点击按钮,可进行数据库查询,获取相关值在页面显示。 不过我不想每次返回A页面,选择选项菜单的另一项再进入B页面,于是我在B页面同样放置了选项菜单,让我点击B页面上的选项菜单时,直接在B页面上显示,不过却出现“java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.rawQuery(java.lang.String, java.lang.String[])' on a null object reference”的错误。 请问,要怎样做呢? 相关数据库查询的函数 public ArrayList<JapInfo> query_stylecolumn(String style_column, String alp_style) { String sql = String.format("SELECT hiragana,katakana,sound_path FROM Jap_Info AS j " + "LEFT JOIN Alp_style AS a " + "ON j.alpha_style_id = a.id " + "WHERE j.style_column = '%s' and a.style_name = '%s';",style_column,alp_style); ArrayList<JapInfo> japIf = new ArrayList<JapInfo>(); Cursor cursor = mDB.rawQuery(sql,null); while (cursor.moveToNext()){ JapInfo japIfo = new JapInfo(); japIfo.hiragana = cursor.getString(0); japIfo.katakana = cursor.getString(1); japIfo.sound_path = cursor.getString(2); japIf.add(japIfo); } cursor.close(); return japIf; }

sql ODBC驱动程序不支持所需的属性

数据库查询语句SELECT di.[GUID],di.DeviceName,si.nYear, dg.GroupID,dg.GroupName,si.OperateTime,si.OperateMold FROM deviceinfo AS di INNER JOIN devicegroupunderusergroup AS dg ON di.DeviceID = dg.DeviceID INNER JOIN setupinfo AS si ON si.ID = di.DeviceID 在数据库管理工具中执行时没有错误,但是ado数据库编程查询sql server数据库时提示ODBC驱动程序不支持所需的属性

关于ODBC中SQLDriverConnect 和 SQLDriverConnectW连接问题

Hi,Guys 在采用unixODBC连接Mysql数据库,遇到以下问题: 使用SQLDriverConnect进行连接,正常 使用SQLDriverConnectW进行连接,出现下面的错误,说数据源找不到. ``` [unixODBC][Driver Manager]Data source name not found, and no default driver specified ``` --- 采用的都是同样的配置 环境: mysql-connector-odbc-5.3.4-linux-glibc2.5-x86-32bit unixODBC 2.3.2 --- 配置信息 **odbcinst.ini** ``` bash [MySQL] Driver = /usr/local/lib/libmyodbc5w.so ``` **odbc.ini** ``` bash [log4cxx] Driver = MySQL Server = localhost Port = 3306 Database= log User = root Password= 123456 Socket = /var/run/mysqld/mysqld.sock ``` **C代码 SQLDriverConnectW** ``` python int main() { SQLHENV env; SQLHDBC dbc; SQLRETURN ret; /* ODBC API return status */ SQLWCHAR outstr[1024]; SQLSMALLINT outstrlen; SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0); SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc); ret = SQLDriverConnectW(dbc, NULL, (SQLWCHAR *)"DSN=log4cxx;", SQL_NTS, outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_NOPROMPT); if(ret < 0) { printf("asdfasdfasdfsadfsadf\n"); } if (SQL_SUCCEEDED(ret)) { printf("Connected\n"); if (ret == SQL_SUCCESS_WITH_INFO) { printf("Driver reported the following diagnostics\n"); extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC); } SQLDisconnect(dbc);/* disconnect from driver */ } else { fprintf(stderr, "Failed to connect\n"); extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC); } /* free up allocated handles */ SQLFreeHandle(SQL_HANDLE_DBC, dbc); SQLFreeHandle(SQL_HANDLE_ENV, env); return 0; } ``` **C代码 SQLDriverConnect** ``` c int main() { SQLHENV env; SQLHDBC dbc; SQLRETURN ret; /* ODBC API return status */ SQLCHAR outstr[1024]; SQLSMALLINT outstrlen; SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0); SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc); ret = SQLDriverConnect(dbc, NULL, (SQLCHAR *)"DSN=log4cxx;", SQL_NTS, outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_NOPROMPT); if(ret < 0) { printf("asdfasdfasdfsadfsadf\n"); } if (SQL_SUCCEEDED(ret)) { printf("Connected\n"); if (ret == SQL_SUCCESS_WITH_INFO) { printf("Driver reported the following diagnostics\n"); extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC); } SQLDisconnect(dbc);/* disconnect from driver */ } else { fprintf(stderr, "Failed to connect\n"); extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC); } /* free up allocated handles */ SQLFreeHandle(SQL_HANDLE_DBC, dbc); SQLFreeHandle(SQL_HANDLE_ENV, env); return 0; } ```

weblogic的Servlet创建之后,报空指针异常

各位前辈,帮忙一下 weblogic的Servlet创建之后,报空指针异常 但是找不出原因 所有代码如下:【只有一个servlet,且数据源配置正常,实验过了的,web.xml也配置完成】 ``` package myservlet; import java.awt.Container; import java.io.IOException; import java.io.PrintWriter; import java.sql.ResultSet; import java.util.Hashtable; import java.util.Properties; import java.util.Vector; import javax.activation.DataSource; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.spi.DirStateFactory.Result; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.Statement; import com.mysql.jdbc.StatementImpl; import javax.naming.*; import javax.sql.*; import java.sql.*; import java.util.*; public class StudentServlet extends HttpServlet { public StudentServlet(){ super(); } public void destroy() { super.destroy(); } private static final String CONTENT_TYPE="text/html;charset=GBK"; //Do Get 方法 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); //打印网页 out.println("<HTML>"); out.println("<HEAD><TITLE>StudentServlet</TITLE></HEAD>"); out.println("<BODY bgcolor=\"#fffff\">"); if ((request.getParameter("sno"))==null ||(request.getParameter("sno")).equals("input number")){ out.println( "<form method='post' action='/lab05-2/src/myservlet/StudentServlet'>"); //"<form method='post' action='/lab05-2/StudentServlet'>"); out.println(""); out.println( "学号查询:<input type='text' name='sno' vaule='input number'/>"); out.println("<input type ='submit' vaule='查询'/><br>"); out.println("</form>"); } //另外一种情况 else if(!(request.getParameter("sno")).equals("input number")){ Vector vc =new Vector(); out.println("<Form method='post' action='/lab05-2/src/myservlet/StudentServlet'>"); out.println(""); out.println("学生学号:<input type='text' name='sno' />"); out.println("<input type ='submit' vaule='查询'/><br>"); out.println("</form>"); out.println("<hr>"); out.println("<table border='1'><tr>"); out.println("<th>学号</th><th>姓名</th><th>语文</th><th>数学</th></tr>"); try{ if((vc=accessDB(Integer.parseInt((String)request.getParameter("sno"))))!=null){ out.println("<tr>"); out.println("<td>"+vc.elementAt(0)+"</td>"); out.println("<td>"+vc.elementAt(1)+"</td>"); out.println("<td>"+vc.elementAt(2)+"</td>"); out.println("<td>"+vc.elementAt(3)+"</td>"); out.println("</tr>"); } }catch(Exception e) { out.println("<tr>"); out.println("<td>没有记录</td>"); out.println("</tr>"); out.println("<td>数据库里没有你要查询的记录</td>"); e.printStackTrace(); } out.println("</table>"); } out.println("</BODY>"); out.println("</HTML>"); out.flush(); out.close(); } //Do Post方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } //Init方法 public void init() throws ServletException { } //通过weblogic的JNDI服务来查询数据库数据 public Vector accessDB(int id){ Vector vc=new Vector(); Context ctx; javax.sql.DataSource ds = null; java.sql.Connection myConn = null ; final String JNDI_DATABASE_NAME="AA"; Properties ht =new Properties(); //Hashtable ht = new Hashtable(); ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); ht.put(Context.PROVIDER_URL, "t3://localhost:7001"); try{ ctx = new InitialContext(ht); ds = (javax.sql.DataSource)ctx.lookup(JNDI_DATABASE_NAME); }catch(Exception e){ e.printStackTrace(); } if(ds == null){ System.out.println("Eorror !!!"); } else{ System.out.println("Connection is OK !!!"); } java.sql.PreparedStatement myStatement = null; ResultSet mySet = null; try{ myConn=ds.getConnection(); myStatement=myConn.prepareStatement("select * from stdb where sno=?"); myStatement.setInt(1, id); mySet=myStatement.executeQuery(); while (mySet.next()){ vc.add(Integer.toString(mySet.getInt("sno"))); vc.add(mySet.getString("sname")); vc.add(Integer.toString(mySet.getInt("chinese"))); vc.add(Integer.toString(mySet.getInt("math"))); } //关闭 myStatement.close(); mySet.close(); myConn.close(); return vc;//返回vc }catch(Exception e) { e.printStackTrace(); } return vc; } public static void main(String[] args) { StudentServlet aa=new StudentServlet(); System.out.println(aa.accessDB(100).elementAt(1)); } } ``` ![图片说明](https://img-ask.csdn.net/upload/201910/20/1571542376_553297.png) 【aa和student只是测试着用,与StudentServlet无关】 报错为: ![图片说明](https://img-ask.csdn.net/upload/201910/20/1571542511_665195.png) 大概就是这些,请指教, 初学,找过百度等也没有解决

SpringMVC提交put,delete请求405

请求删除操作报:HTTP Status 405 - Request method 'POST' not supported 已经在web.xml配置,HiddenHttpMethodFilter过滤器 jsp页面: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>主页面</title> <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> </head> <body> <form action="" method="post"> <input type="hidden" value="DELETE" name="_method"/> </form> <table border="1"> <tr> <th>编号</th> <th>用户名</th> <th>密码</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach items="${requestScope.list}" var="list"> <tr> <td>${list.userId}</td> <td>${list.userName}</td> <td>${list.password}</td> <td>${list.email}</td> <td> <a href="update" class="update">修改</a> <a href="user/${list.userId}" class="delete">刪除</a> </td> </tr> </c:forEach> </table> <br> <br> </body> </html> <script> $(function(){ $(".delete").click(function(){ var href=$(this).attr("href"); $("form").attr("action",href).submit(); return false; }); }); </script> 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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd " default-autowire="byName"> <!-- 启用spring mvc 注解 --> <context:annotation-config /> <mvc:annotation-driven /> <!-- 处理静态资源 --> <mvc:default-servlet-handler/> <!--对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="suffix" value=".jsp"></property> </bean> <context:component-scan base-package="com.tang" /> <!-- 获取数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/springmvc"></property> <property name="username" value="root"></property> <property name="password" value="123"> </property> </bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean> <!-- 给jdbc模板注入数据源 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> </beans> controller代码: package com.tang.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.tang.dao.UserDao; import com.tang.pojo.User; @Controller public class LoginController { @Autowired private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } @ModelAttribute public void test(){ System.out.println("LoginController.test()"); } @RequestMapping("/login") public String doLogin(String username,String password,ModelMap map){ User user=userDao.doLogin(username, password); if(user!=null){ List<User> list=userDao.findAll(); map.put("list", list); return "index"; }else{ return "login"; } } @RequestMapping(value="/update",method=RequestMethod.PUT) public String doUpdate(User user,ModelMap map){ userDao.doUpdate(user); List<User> list=userDao.findAll(); map.put("list", list); return "index"; } @RequestMapping(value="/user/{id}",method=RequestMethod.DELETE) public String doDelete(@PathVariable("id")Integer id,ModelMap map){ userDao.doDelete(id); List<User> list=userDao.findAll(); map.put("list", list); return "index"; } }

有没有大神能指点一下哪里错了。。。。

package Frame; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; import javax.swing.*; import db.DButil; public class login extends JFrame implements ActionListener{ private JPanel jp=new JPanel(); //创建标签数组 private JLabel[] jlArray={new JLabel("用户名"), new JLabel("密 码"),new JLabel("")}; private JButton jb1; private JButton jb2; private JButton jb3; private JTextField jtf=new JTextField(); private JPasswordField jpf=new JPasswordField(); //布局构造实现方法 public login(){ Icon icon1=new ImageIcon("login.jpg"); Icon icon2=new ImageIcon("reset.jpg"); Icon icon3=new ImageIcon("zhuce.jpg"); JPanel jp=new JPanel(){ protected void paintComponent(Graphics g) { ImageIcon icon = new ImageIcon("bg.jpg"); Image img = icon.getImage(); g.drawImage(img, 0, 0, icon.getIconWidth(), icon.getIconHeight(), icon.getImageObserver()); }}; jp.setLayout(null); jb1=new JButton(icon1); jb2=new JButton(icon3); jb3=new JButton(icon2); jlArray[0].setBounds(70,120,90,32); jb1.setBounds(365,110,130,60); jb2.setBounds(365,170,130,60); jlArray[1].setBounds(70,170,90,32); //将标签与按钮添加到JPanel容器中 jp.add(jlArray[0]); jp.add(jlArray[1]); jp.add(jb1); jp.add(jb2); jb1.addActionListener(this); jb2.addActionListener(this);//为按钮注册动作事件监听器 //添加修改密码的按钮 jb3.setBounds(365,230,130,60); jp.add(jb3); jp.add(jtf); jtf.setBounds(140,120,180,30);//设置文本框位置 jp.add(jpf); jpf.setBounds(140,170,180,30);//设置密码框位置 jpf.setEchoChar('*'); //密码显示字符形式 jpf.addActionListener(this); //为密码框注册动作事件监听器 this.setVisible(true);//设置窗体的可见性 jpf.addActionListener(this); //为密码框注册动作事件监听器 //设置用于显示登陆状态的标签大小位置,并将其添加进JPanel容器 jlArray[2].setBounds(70,220,300,30); jp.add(jlArray[2]); this.setTitle("登陆");//设置窗体标题 this.setBounds(450,200,500,318);//设置窗体的大小 this.setResizable(false);//设置窗体不让用户调整大小 this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setVisible(true);//设置窗体的可见性 this.add(jp);//将窗体添加到面板中 jp.setBackground(Color.blue); } public static void main(String[] args) { new login();//创建登陆窗体 } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub //得到用户名与密码 String user=jtf.getText().trim(); String pwd=String.valueOf(jpf.getPassword());//返回密码的字符串表示方式 String sql=""; if(e.getSource()==jtf){//事件源为文本框,切换焦点到密码框 jpf.requestFocus(); } else if(e.getSource()==jb1||e.getSource()==jpf){ //判断用户名和密码是否匹配 查询数据库 if(DButil.check(user, pwd)){ //登陆成功 MainFrame mf=new MainFrame(jtf.getText());//主窗体 this.dispose(); } else{ //登陆失败 jlArray[2].setText("对不起,非法的用户名和密码"); this.clear(); } } else if(e.getSource()==jb2) {//事件源为注册按钮 if(user.equals("")||pwd.equals("")) {//如果注册的用户名为空或者密码为空 jlArray[2].setText("用户名和密码都不得为空!!!"); this.clear();//清空输入文本框 } else { sql="select uid from user where uid='"+user+"'"; if(DButil.isExist(sql)) {//用户名已经存在 jlArray[2].setText("对不起,用户名已存在!!!"); this.clear();//清空输入文本框 } else { sql="insert into user values('"+user+"','"+pwd+"')"; if(DButil.update(sql)>0) {//注册成功 jlArray[2].setText("恭喜您!!!注册成功,请登陆"); } } } } else if(e.getSource()==jb3)//修改密码的监听 { //判断是否已经输入用户名和密码 if(user.equals("")||pwd.equals("")) { jlArray[2].setText("修改密码先输入正确的用户名和密码!!!"); this.clear();//清空输入文本框 } //判断是否输入了正确的用户名和密码 else if(DButil.check(user,pwd)) { //正确的用户名和密码 String password=JOptionPane.showInputDialog(this,"修改密码:","请输入新密码", JOptionPane.PLAIN_MESSAGE); //得到新的密码为空 if(password==null||password.equals("")) { JOptionPane.showMessageDialog(this,"密码不得为空!!!","错误", JOptionPane.WARNING_MESSAGE); } else {//密码不为空 sql="update user set pwd='"+password+"' where uid='"+user+"'";//更新密码的SQL if(DButil.update(sql)>0) {//密码修改成功 this.clear();//清空输入文本框 jlArray[2].setText("恭喜您!!!密码修改成功,请用新密码登陆"); } } } else { JOptionPane.showMessageDialog(this,"用户名或者密码错误!!!","错误", JOptionPane.WARNING_MESSAGE); this.clear();//清空输入文本框 } } } package Frame; import javax.swing.*; import javax.swing.table.DefaultTableModel; import db.DButil; import java.awt.*; import java.awt.event.*; import java.sql.*; import java.io.*; import java.util.*; public class MainFrame extends JFrame implements ActionListener,ItemListener { private String uname=null;//当前用户的名字 private boolean isInsert=false;//是否为添加默认为否 private JPanel topjp=new JPanel();//界面上半部分的JPanel容器 private JButton jba=new JButton("模糊查询"); private JButton jbs=new JButton("查找"); private JTextField jtfs=new JTextField();//按给出信息查找联系人信息 private JRadioButton jrbxm=new JRadioButton("按姓名查找",true); private JRadioButton jrbbh=new JRadioButton("按学号查找",false); private ButtonGroup bg=new ButtonGroup();//单选按钮组 private JPanel jpbr=new JPanel();//单选按钮面板 private JPanel jpyInfo=new JPanel();//右侧显示个人信息的面板 private JTextArea jta=new JTextArea(); // 模糊查询得到的信息文本区 private JLabel[] jlInfo={new JLabel("学号:"),new JLabel("姓名:"), new JLabel("性别:"),new JLabel("出生日期:"), new JLabel("电话号码:"),new JLabel("QQ:"), new JLabel("Email:"),new JLabel("地址:"), new JLabel("添加相片")}; private JButton[] jbInfo={new JButton("编辑"),new JButton("保存"), new JButton("浏览"), new JButton("上传"),}; private JLabel jlPhoto=new JLabel();//显示图像的JLabel控件 private JTextField[] jtfInfo=new JTextField[10]; private JTextField jtfPhoto=new JTextField();//添加照片到相册的路径 private JFileChooser jfcPic=new JFileChooser();//上传图像的文件选择器 private DefaultTableModel tableModel; private JTable table; //性别部分 private JRadioButton jrbMale=new JRadioButton("男",true); private JRadioButton jrbFemale=new JRadioButton("女"); private ButtonGroup bgGender=new ButtonGroup(); private JPanel jpGender=new JPanel();//单选按钮面板 private JLabel jlDetail=new JLabel();//右侧显示一幅图片的标签 private JSplitPane jspOuter=//上下分割的JSplitPane new JSplitPane(JSplitPane.VERTICAL_SPLIT,true); //系统托盘部分 private PopupMenu popup=new PopupMenu(); private SystemTray tray;//定义SystemTray成员变量 private TrayIcon trayIcon;//定义TrayIcon成员变量 private MenuItem exit=new MenuItem("退出程序");//定义菜单 public void initJps() {//界面上半部分的初始化 topjp.setLayout(null);//设置topjp布局管理器为null //设置按钮大小并添加到JPanel面板里 jba.setBounds(5,10,120,26); jba.addActionListener(this);//为模糊查询按钮注册事件监听器 topjp.add(jba); jbs.setBounds(130,10,80,26); jbs.addActionListener(this);//为查找按钮注册事件监听器 topjp.add(jbs);//添加按钮到topjp面板里 //设置jtfs文本框大小并添加到jps面板里 jtfs.setBounds(215,10,120,26); jtfs.addActionListener(this);//为文本框注册事件监听器 topjp.add(jtfs); //设置单选按钮大小和位置并添加到jpbr面板里同时添加到bg单选按钮组里 jrbxm.setBounds(5,3,50,26); jrbxm.addItemListener(this);//为单选按钮注册ItemEvent事件监听器 bg.add(jrbxm); jpbr.add(jrbxm); jrbbh.setBounds(60,3,50,26); jrbbh.addItemListener(this); bg.add(jrbbh); jpbr.add(jrbbh); jpbr.setBounds(360,10,200,26); topjp.add(jpbr); } public void initInfo() {//初始化信息界面 jpyInfo.setLayout(null);//设置布局管理器为空 jpyInfo.setBounds(50,50,380,360);//设置信息面板的大小和位置 jlPhoto.setBounds(220,10,150,170);//设置联系人图像JLabel的大小和位置 jlPhoto.setBorder(BorderFactory.createLineBorder(Color.BLACK));//将JLbel的边框线显现出来 jpyInfo.add(jlPhoto);//将显示联系人照片的JLabel添加到信息面板 tableModel=new DefaultTableModel(); Vector vector1 = new Vector(); DButil db = new DButil(); vector1.add("学号"); vector1.add("姓名"); vector1.add("性别"); vector1.add("出生日期"); vector1.add("电话号码"); vector1.add("QQ"); vector1.add("Email"); vector1.add("地址"); vector1.add("照片路径"); tableModel.setDataVector(null, vector1); System.out.print(123); table=new JTable(tableModel); //table.addMouseListener((MouseListener) this); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); JScrollPane js=new JScrollPane(table); //添加相片部分的控件 jtfPhoto.setBounds(80,250,200,26);//设置得到照片路径的文本框的大小和位置 jpyInfo.add(jtfPhoto);//将得到照片路径的文本框添加到信息面板 jbInfo[2].setBounds(285,250,80,26); jbInfo[2].addActionListener(this);//为添加照片的浏览按钮注册事件监听器 jpyInfo.add(jbInfo[2]); //上传按钮 jbInfo[3].setBounds(380,250,80,26); jbInfo[3].addActionListener(this);//为添加照片的浏览按钮注册事件监听器 jpyInfo.add(jbInfo[3]); for(int i=0;i<9;i++)//添加JLabel,并设置大小和位置 { jlInfo[i].setBounds(20,10+i*30,60,26); jpyInfo.add(jlInfo[i]); } for(int i=0;i<10;i++) {//初始化一些文本框 jtfInfo[i]=new JTextField(); } //学号 jtfInfo[0].setBounds(80,10,135,26); jpyInfo.add(jtfInfo[0]); //姓名 jtfInfo[1].setBounds(80,40,135,26); jpyInfo.add(jtfInfo[1]); //出生日期 jtfInfo[3].setBounds(80,100,135,26); jpyInfo.add(jtfInfo[3]); //电话号码 jtfInfo[4].setBounds(80,130,135,26); jpyInfo.add(jtfInfo[4]); //QQ jtfInfo[5].setBounds(80,160,135,26); jpyInfo.add(jtfInfo[5]); //Email jtfInfo[6].setBounds(80,190,135,26); jpyInfo.add(jtfInfo[6]); //地址文本框的添加 jtfInfo[7].setBounds(80,220,285,26); jpyInfo.add(jtfInfo[7]); //模糊查询信息文本区的添加 js.setBounds(0,350,600,100); jpyInfo.add(js); //编辑、保存按钮 jbInfo[0].setBounds(160,300,80,26); jbInfo[0].addActionListener(this); jpyInfo.add(jbInfo[0]); jbInfo[1].setBounds(260,300,80,26); jbInfo[1].addActionListener(this); jpyInfo.add(jbInfo[1]); //性别部分 jrbMale.setBounds(5,3,50,26); jrbMale.addItemListener(this); //为单选按钮注册ItemEvent事件监听器 bgGender.add(jrbMale); jpGender.add(jrbMale); jrbFemale.setBounds(60,3,50,26); jrbFemale.addItemListener(this); //为单选按钮注册ItemEvent事件监听器 bgGender.add(jrbFemale); jpGender.add(jrbFemale); jpGender.setBounds(60,70,125,26); jpyInfo.add(jpGender); } public void clearInfo()//清空信息面板 { for(int i=0;i<10;i++) { jtfInfo[i].setText("");//清空文本框 } jlPhoto.setIcon(null);//清空图像 } public void setjtaArea(String information){ if(information.isEmpty()){ JOptionPane.showMessageDialog(this,"所查用户不存在!!!","错误", JOptionPane.WARNING_MESSAGE); } else { jta.setText(information); } } public void setInfo(Vector<String> pInfo)//将信息向量设置到信息面板中 {//将信息向量按规则填到信息面板里 this.clearInfo(); if(pInfo.size()==0) { JOptionPane.showMessageDialog(this,"所查用户不存在!!!","错误", JOptionPane.WARNING_MESSAGE); } else { for(int i=0;i<2;i++) {//显示联系人编号和姓名 jtfInfo[i].setText(pInfo.get(i)); } if(pInfo.get(2).equals("男")) {//显示性别 jrbMale.setSelected(true); } else {//显示性别 jrbFemale.setSelected(true); } for(int i=3;i<9;i++) {//显示出生日期、电话号码和QQ jtfInfo[i].setText(pInfo.get(i)); } } } public Vector<String> getInfo()//从信息面板得到用户输入的信息 { Vector<String> pInfo=new Vector<String>(); pInfo.add(jtfInfo[0].getText().trim());//添加pid pInfo.add(jtfInfo[1].getText().trim());//添加pname String gender=jrbMale.isSelected()?"男":"女"; pInfo.add(gender);//添加性别 pInfo.add(jtfInfo[3].getText().trim());//出生日期 pInfo.add(jtfInfo[4].getText().trim());//电话号码 pInfo.add(jtfInfo[5].getText().trim());//QQ pInfo.add(jtfInfo[6].getText().trim());//Email pInfo.add(jtfInfo[7].getText().trim());//地址 String photoPath=jtfPhoto.getText().trim();//得到照片路径 pInfo.add(photoPath);//照片路径 return pInfo; } public void monitorSaveButton() //监听保存按钮的方法 { String sql=""; String pid=jtfInfo[0].getText().trim();//得到联系人的编号 String pname=jtfInfo[1].getText().trim();//得到联系人的姓名 String gender=jrbMale.isSelected()?"男":"女"; String s1=jtfInfo[3].getText().trim(); String s2=jtfInfo[4].getText().trim(); String s3=jtfInfo[5].getText().trim(); String s4=jtfInfo[6].getText().trim(); String s5=jtfInfo[7].getText().trim(); String s6=jtfPhoto.getText().trim(); String sqla="select * from contacts where pid='"+pid+"'";//判断此编号是否存在的SQL String sqlb="select * from contacts where pname='"+pname+"'";//判断此姓名是否存在的SQL boolean isIdExist=DButil.isExist(sqla);//得到编号是否存在 boolean isNameExist=DButil.isExist(sqlb);//得到姓名是否存在 if(!(pid.equals(" ")||pname.equals(" "))) { if(isIdExist||isNameExist){ JOptionPane.showMessageDialog(this,"联系人已存在"+ " , 添加联系人失败","错误",JOptionPane.WARNING_MESSAGE); } else { sql="insert into contacts values (?,?,?,?,?,?,?,?,?,?)"; String[] paras={pid,pname,gender,s1,s2,s3,s4,s5,s6,null}; if(DButil.update(sql,paras)>0){ JOptionPane.showMessageDialog(this,"联系人保存成功","提示", JOptionPane.INFORMATION_MESSAGE); } } } } public void setEditable(boolean Editable)//设置信息窗口是否可编辑 { jrbFemale.setEnabled(Editable);//设置性别是否可编辑 jrbMale.setEnabled(Editable);//设置性别是否可编辑 for(int i=0;i<8;i++) { jtfInfo[i].setEditable(Editable);//设置文本框是否可编辑 } } public void monitorSearchButton()//监听查找按钮的方法 { String name=jtfs.getText().trim(); String sql="";//声明查找字符串 if(name.equals("")) { JOptionPane.showMessageDialog(this,"查找条件不能为空!!!", "错误", JOptionPane.WARNING_MESSAGE); } else { if(jrbxm.isSelected()==true) {//按姓名查找 sql="select pid,pname,pgender,pbirthday,pnumber,pQQ,pemail,padress,pphoto from contacts where pname='"+name+"'"; this.setInfo(DButil.getPerInfo(sql));//设置信息面板为该联系人的信息 } else {//按编号查找 sql="select pid,pname,pgender,pbirthday,pnumber,pQQ,pemail,padress,pphoto from contacts where pid='"+name+"'"; this.setInfo(DButil.getPerInfo(sql));//设置信息面板为该联系人的信息 } } this.setEditable(false);//设置面板不可编辑 } public void monitorRandomSearchButton(String information){ //监听模糊查询按钮 String adress=jba.getText().trim(); String sql="";//声明查找字符串 if(adress.equals("")) { JOptionPane.showMessageDialog(this,"查找条件不能为空!!!", "错误", JOptionPane.WARNING_MESSAGE); } else{ sql="select pid,pname,pgender,pbirthday,pnumber,pQQ,pemail,padress,pphoto from contacts where padress like '%天河区%'"; } } public MainFrame(String uname) { //主窗体构造器 this.uname=uname;//设置用户名 this.initJps();//界面上半部分的搭建 this.initInfo(); jspOuter.setDividerLocation(46);//设置分割窗体JSplitPane的位置 jspOuter.setTopComponent(topjp);//设置窗体上半部分的控件 jspOuter.setBottomComponent(jpyInfo);//设置下半部分的控件 //设置窗体关闭按钮执行的动作 this.add(jspOuter); this.addWindowListener( new WindowAdapter() { @SuppressWarnings("deprecation") public void WindowClosing(WindowEvent e) { //将窗体隐藏 MainFrame.this.hide(); } } ); //设置主窗体的图标、标题、大小以及可见性 this.setResizable(false);//设置窗体不让调整大小 this.setTitle(uname+"的通讯录"); this.setBounds(420,80,618,550); this.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource()==jbInfo[1]) {//保存按钮的监听 this.monitorSaveButton(); } else if(e.getSource()==jba) {//模糊查询按钮的监听 DButil db = new DButil(); Vector vector1 = new Vector(); vector1.add("学号"); vector1.add("姓名"); vector1.add("性别"); vector1.add("出生日期"); vector1.add("电话号码"); vector1.add("QQ"); vector1.add("Email"); vector1.add("地址"); vector1.add("照片路径"); String ad = jtfs.getText().trim(); tableModel.setDataVector(db.getData(ad),vector1); } else if(e.getSource()==jbInfo[2]) {//打开图像文件路径 jfcPic.showOpenDialog(this); if(jfcPic.getSelectedFile()!=null) { jtfPhoto.setText(""+jfcPic.getSelectedFile()); } } else if(e.getSource()==jbInfo[0]) {//编辑按钮的监听 this.setEditable(true);//设置信息面板可编辑 } else if(e.getSource()==jbs||e.getSource()==jtfs) {//查找,按按钮或者在文本框里敲回车 this.monitorSearchButton(); } } public void itemStateChanged(ItemEvent e) { } public static void main(String[] args){ } } package db; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.Vector; public class DButil { private static String jdbcName="org.gjt.mm.mysql.Driver";//声明驱动类字符串 //声明数据库连接字符串 private static String dbUrl="jdbc:mysql://127.0.0.1:3306/maillist"; private static String dbUserName="root"; private static String dbPassword="admin"; private static Connection con=null;//声明数据库连接对象引用 private static Statement stat=null;//声明语句对象引用 private static PreparedStatement pstmt=null; private static ResultSet rs=null;//声明结果集对象引用 private static PreparedStatement psInsert=null;//声明预编译语句对象引用 public static Connection getConnection()//得到数据库连接的方法 { System.out.println("连接中.."); try { Class.forName(jdbcName);//加载驱动类 con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);//得到连接 System.out.println("成功连接"); } catch(Exception e){e.printStackTrace();} return con;//返回连接 } public static boolean check(String user,String pwd)//登陆验证 { boolean flag=false; try { con=DButil.getConnection();//得到数据库连接 stat=con.createStatement();//创建语句对象 rs=stat.executeQuery("select pwd from user where uid='"+user+"'"); rs.next(); String spwd=rs.getString(1);//得到密码 if(spwd.equals(pwd)) { flag=true;//密码匹配,登陆成功 } } catch(Exception e) { flag=false;//有任何异常发生,登陆失败 } finally{DButil.closeCon();}//关闭数据库连接 return flag; } //某条记录是否存在 public static boolean isExist(String sql) { boolean flag=false;//设置返回值 try { con=DButil.getConnection();//得到数据库连接 stat=con.createStatement();//创建语句对象 rs=stat.executeQuery(sql);//执行查询 if(rs.next()) { flag=true;//存在,设置返回值为true } } catch(Exception e) { e.printStackTrace(); flag=false;//发生任何异常,置返回结果为false } finally{DButil.closeCon();}//关闭数据库连接 return flag;//返回结果 } public static int update(String sql,String[] paras)//更新数据库 { int count=0;//声明返回值 try { con=DButil.getConnection(); pstmt=con.prepareStatement(sql); for(int i=0; i<paras.length;i++){ pstmt.setString(i+1, paras[i]); } count=pstmt.executeUpdate(); } catch(Exception e) { e.printStackTrace(); count=-1;//更新失败返回值为-1 } finally{DButil.closeCon();}//关闭数据库连接 return count;//返回结果 } public static int update(String sql)//更新数据库 { int count=0;//声明返回值 try { con=DButil.getConnection(); stat=con.createStatement(); count=stat.executeUpdate(sql);//执行更新 } catch(Exception e) { e.printStackTrace(); count=-1;//更新失败返回值为-1 } finally{DButil.closeCon();}//关闭数据库连接 return count;//返回结果 } //====================添加联系人================================= public static String insertPerson(String uid,Vector<String> pInfo) { String isPathNull="isNotNull";//传过来的图像是不是合法,默认不为空 try{ con=getConnection();//得到数据库连接 if(pInfo.get(8).equals("")||pInfo.get(8)==null) {//照片路径为空,则不插入图像 psInsert=con.prepareStatement("insert into contacts(pid,pname,pgender,pbirthday,pnumber,"+ "pQQ,pemail,padress,uid)"+ "values(?,?,?,?,?,?,?,?,?)"); } else {//照片路径不为空,则插入图像 psInsert=con.prepareStatement("insert into contacts(pid,pname,pgender,pbirthday,pnumber,"+ "pQQ,pemail,padress,pphoto,uid)"+ "values(?,?,?,?,?,?,?,?,?,?,?)" ); File f=new File(pInfo.get(8));//获取选取的图片文件 byte[] b=new byte[(int)f.length()];//创建存储图片数据的数组 FileInputStream fin=new FileInputStream(f); fin.read(b);fin.close();//读取文件存于byte数组中并关闭输入流 psInsert.setBytes(11,b);//设置pphoto参数的数据 } for(int i=0;i<8;i++) {//设置公共信息 psInsert.setString(i+1,pInfo.get(i)); } psInsert.setString(10,uid);//所属用户 psInsert.execute();psInsert.close();//执行更新并关闭语句 } catch(FileNotFoundException fnfe){isPathNull="isNull";}//图片路径不对 catch(Exception e){e.printStackTrace();} finally{DButil.closeCon();}//关闭数据库连接 return isPathNull; } public static String updatePerson(String uid,Vector<String> pInfo){ String isPathNull="isNotNull";//传过来的path是不是合法 try{ con=getConnection(); if(pInfo.get(9).equals("")||pInfo.get(9)==null) {//更新时候,如果照片路径为空,则不更新图像 psInsert=con.prepareStatement("update contacts set pname=?,pgender=?,birthday=?,pnumber=?,"+ "pQQ=?,pemail=?,padress=?,pphoto=?,uid=? where pid='"+pInfo.get(0).trim()+"'"); } else {//如果照片路径不为空,则更新图像 psInsert=con.prepareStatement("update contacts set pname=?,pgender=?,page=?,pnumber=?,"+ "pemail=?,pgroup=?,ppostalcode=?,padress=?,uid=?,pphoto=? where pid='"+pInfo.get(0).trim()+"'"); File f=new File(pInfo.get(9));//获取选取的图片文件 byte[] b=new byte[(int)f.length()];//创建存储图片数据的数组 FileInputStream fin=new FileInputStream(f); fin.read(b);fin.close();//读取文件存于byte数组中并关闭输入流 psInsert.setBytes(10,b); } for(int i=1;i<8;i++){//设置公共的信息部分 psInsert.setString(i,pInfo.get(i)); } psInsert.setString(9,uid);//所属用户 psInsert.execute();psInsert.close();//执行更新并关闭语句 } catch(FileNotFoundException fnfe){isPathNull="isNull";}//路径不合法 catch(Exception e){e.printStackTrace();} finally{DButil.closeCon();}//关闭连接 return isPathNull; } public Vector getData(String ad){ Vector vector=new Vector(); try { //陈述对象 con=getConnection();//得到数据库连接 stat=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);//创建语句对象 rs=stat.executeQuery("select * from contacts where padress LIKE '%"+ad+"%'"); ResultSetMetaData rm=rs.getMetaData(); //循环打印出数据库表中数据 int n=rm.getColumnCount(); while(rs.next()){ Vector ve=new Vector(); for(int i=1;i<n+1;i++){ String s=rs.getString(i); ve.add(s); } vector.add(ve);//Vector对象接收表中数据 } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{if(rs!=null){ try { rs.close();//关闭结果集 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(stat!=null){ try { stat.close();//关闭陈述对象 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(con!=null){ try { con.close();//关闭连接 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return vector; } public static Vector<String> getPerInfo(String sql)//得到联系人信息 { Vector<String> pInfo=new Vector<String>(); try { con=getConnection();//得到数据库连接 stat=con.createStatement();//创建语句对象 rs=stat.executeQuery(sql);//执行查询 while(rs.next()) { for(int i=1;i<10;i++) { System.out.println(rs.getString(i)); pInfo.add(rs.getString(i));//将联系人信息添加到返回向量 } } } catch(Exception e) { e.printStackTrace(); } finally{DButil.closeCon();}//关闭数据库连接 return pInfo;//返回信息集合 } public static void closeCon()//关闭数据库连接的方法 { try { if(rs!=null){rs.close(); rs=null;}//如果结果集不为空关闭结果集并赋值null if(stat!=null){stat.close(); stat=null;}//如果语句对象不为空关闭语句对象并赋值null if(con!=null){con.close(); con=null;}//如果连接不为空关闭连接并赋值null } catch(Exception e){e.printStackTrace();} } public static void main(String[] args){ DButil DB=new DButil(); System.out.println(DB.getConnection()); } } }

基于springmvc+mybatis的登录表单提交后404

前端填写正确的用户名和密码后,提交登录,浏览器显示404,前端提交的地址是/userlogin,后端对接的/user/userlogin也是对的,浏览器f12里显示请求的确成功传给了后端,但是不知道为什么404。用的是tomcat8.5,java版本1.8,phpstudy最新版,mysql5.7.26。 ## 这是所用到的包: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567617_880785.jpg) ## 这是目录结构: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567511_223692.jpg) ## 这是web.xml: ```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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc_test</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/context-config.xml</param-value> </context-param> <!-- 配置前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- DispatcherServlet在初始化方法里面会读取该初始化参数的值来获得 spring配置文件的位置 ,然后启动spring容器。 --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/springmvc-config.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> <!-- 配置字符编码 --> <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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ``` ## 这是context-config.xml: ```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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描service包下的注解 --> <context:component-scan base-package="com.test.service"></context:component-scan> <!-- 配置数据库 --> <!-- 加载配置文件 --> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> --> <bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driver" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/Eday_Test"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> <!-- 配置Sqlsessionfactory并将数据源注入 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 引入数据源 --> <property name="dateSource" ref="dateSource"></property> <!-- 载入mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 载入配置mapper映射的xml --> <property name="mapperLocations" value="classpath:com/test/mapper/*.xml"></property> </bean> <!-- 配置扫描mapper接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackge" value="com.test.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dateSource" ref="dateSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> ``` ## 这是mybatis-config.xml: ```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> <typeAliases> <!-- 配置别名 --> <typeAlias alias="User" type="com.test.pojo.User"/> </typeAliases> </configuration> ``` ## 这是springmvc-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.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"> <!-- 扫描controller包下的注解 --> <context:component-scan base-package="com.test.controller"></context:component-scan> <!-- 开启注解 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 静态资源访问 --> <mvc:default-servlet-handler/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置试图解析的默认路径,即配置页面的根路径 --> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ``` ## 这是UserController.java: ```java package com.test.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.test.pojo.User; import com.test.service.UserService; //声明控制器 @Controller //设置bean的scope属性为多例(prototype) @Scope("prototype") //设置请求映射,当客户端请求/user时,转到该控制器处理 @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value="/userlogin") public ModelAndView login(String user_Name,String user_pwd,ModelAndView mv,HttpSession session){ //调用userService中的login方法处理user实体类对象 User user = userService.login(user_Name,user_pwd); //登录的逻辑判断,判断条件是返回结果不为空 if(user!=null){ //登陆成功,将user对象设置到HttpSession作用范围域中,相当于服务端的cookie,有效时间默认30分钟 //在程序运行期间,在任意页面都可以提取它的值。 session.setAttribute("user",user); //转发到main请求 //登录成功,跳转页面 mv.setViewName("login/login-success"); }else{ //登录失败,向前端传递失败信息 mv.addObject("message","用户名或密码错误,请重新输入!"); //登录失败,跳转到登录页面 mv.setViewName("login"); } return mv; } //跳转到用户注册界面 @RequestMapping(value="/userregister"/*,method=RequestMethod.POST*/) public String register(User user){ String user_Name = user.getUser_Name(); //如果数据库中没有该用户,可以注册,否则跳转页面 if(userService.findByUserName(user_Name)==null){ //添加用户 userService.register(user); //注册成功,跳转到主页面 return "index"; }else{ //注册失败,跳转到错误页面 return "error"; } } } ``` ## 这是UserMapper.java: ```java package com.test.mapper; import org.apache.ibatis.annotations.Param; import com.test.pojo.User; public interface UserMapper { //根据用户名和密码查找,mybatis中有多个参数时,需要使用@Param注解 User findByUserNameAndPassword(@Param("user_Name")String user_Name,@Param("user_Pwd")String user_Pwd); //增加用户 void addUser(User user); //根据用户名查询 User findByUserName(String user_Name); } ``` ## 这是UserMapper.xml: ```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.tes.mapper.UserMapper"> <!-- 根据用户名和密码查询 --> <select id="findByUserNameAndPasssword" resultType="User"> select * from user where user_Name=#{user_Name} and user_Pwd=#{user_Pwd} </select> <!-- 增加用户 --> <insert id="addUser" parameterType="User"> insert into user (user_Name,user_Pwd,user_Email,user_NickName,user_Birth,user_Phone,user_InvitationCode) values(#{user_Name},#{user_Pwd},#{user_Email},#{user_NickName},#{user_Birth},#{user_Phone},#{user_InvitationCode}) </insert> <!-- 根据用户名查询 --> <select id="findByUserName" resultType="User"> select * from user where user_Name=#{user_Name} </select> </mapper> ``` ## 这是User.java: ```java package com.test.pojo; import java.sql.Timestamp; public class User { private int user_Id; private String user_Name; private int user_Pwd; private String user_Email; private String user_NickName; private Timestamp user_Time; private String user_Birth; private int user_Fans; private int user_Follow; private int user_Score; private String user_HeadImgAddr; private int user_Phone; private String user_InvitationCode; public int getUser_Id() { return user_Id; } public void setUser_Id(int user_Id) { this.user_Id = user_Id; } public String getUser_Name() { return user_Name; } public void setUser_Name(String user_Name) { this.user_Name = user_Name; } public int getUser_Pwd() { return user_Pwd; } public void setUser_Pwd(int user_Pwd) { this.user_Pwd = user_Pwd; } public String getUser_Email() { return user_Email; } public void setUser_Email(String user_Email) { this.user_Email = user_Email; } public String getUser_NickName() { return user_NickName; } public void setUser_NickName(String user_NickName) { this.user_NickName = user_NickName; } public Timestamp getUser_Time() { return user_Time; } public void setUser_Time(Timestamp user_Time) { this.user_Time = user_Time; } public String getUser_Birth() { return user_Birth; } public void setUser_Birth(String user_Birth) { this.user_Birth = user_Birth; } public int getUser_Fans() { return user_Fans; } public void setUser_Fans(int user_Fans) { this.user_Fans = user_Fans; } public int getUser_Follow() { return user_Follow; } public void setUser_Follow(int user_Follow) { this.user_Follow = user_Follow; } public int getUser_Score() { return user_Score; } public void setUser_Score(int user_Score) { this.user_Score = user_Score; } public String getUser_HeadImgAddr() { return user_HeadImgAddr; } public void setUser_HeadImgAddr(String user_HeadImgAddr) { this.user_HeadImgAddr = user_HeadImgAddr; } public int getUser_Phone() { return user_Phone; } public void setUser_Phone(int user_Phone) { this.user_Phone = user_Phone; } public String getUser_InvitationCode() { return user_InvitationCode; } public void setUser_InvitationCode(String user_InvitationCode) { this.user_InvitationCode = user_InvitationCode; } @Override public String toString() { return "User [user_Id=" + user_Id + ", user_Name=" + user_Name + ", user_Pwd=" + user_Pwd + ", user_Email=" + user_Email + ", user_NickName=" + user_NickName + ", user_Time=" + user_Time + ", user_Birth=" + user_Birth + ", user_Fans=" + user_Fans + ", user_Follow=" + user_Follow + ", user_Score=" + user_Score + ", user_HeadImgAddr=" + user_HeadImgAddr + ", user_Phone=" + user_Phone + ", user_InvitationCode=" + user_InvitationCode + "]"; } } ``` ## 这是UserService.java: ```java package com.test.service; import com.test.pojo.User; public interface UserService { //通过用户名及密码核查用户登录 User login(String user_Name,String user_Pwd); //增加用户 void register(User user); //根据用户名查询 User findByUserName(String user); } ``` ## 这是UserServiceImpl.java: ```java package com.test.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.test.mapper.UserMapper; import com.test.pojo.User; import com.test.service.UserService; @Service @Transactional public class UserServiceImpl implements UserService { //注入UserMapper接口 @Autowired private UserMapper userMapper; //登录,根据用户名和密码进行查询 @Override public User login(String user_Name,String user_Pwd){ return userMapper.findByUserNameAndPassword(user_Name,user_Pwd); } //注册,增加用户 @Override public void register(User user){ userMapper.addUser(user); } //根据用户名查询 @Override public User findByUserName(String user_Name){ return userMapper.findByUserName(user_Name); } } ``` ##这是login.jsp ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/login.css" /> <title>登录</title> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <!--登录板块--> <header class="header"> <p class="logintitle"> <b>登录</b> </p> <form action="${pageContext.request.contextPath }/user/userlogin" method="post" class=login-form> <p class= login-username-p> <label for="username" class="login-username-text">用户名:</label> <input type=text name="user_Name" class="login-username-input"> <br><a href="register.jsp" class=login-register>注册</a> </p> <p class="login-psw-p"> <label for="psw" class="login-psw-text">密码:</label> <input type=password name="user_Pwd" class="login-psw-input"> <br><a href="#" class=login-forget>忘记密码</a> </p> <div class=login-button-div> <label for=button></label> <button type=sublim class=login-button>登录</button> </div> </form> </header> </body> </html> ``` ## 这是login-success.jsp: ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录成功,请等待跳转...</title> <script type="text/javascript"> onload=function(){ setInterval(go, 1000); }; var x=3; //利用了全局变量来执行 function go(){ x--; if(x>0){ document.getElementById("sp").innerHTML=x; //每次设置的x的值都不一样了。 }else{ location.href='../index.jsp'; } } </script> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <header> <div> <p>登录成功!页面将在3秒后自动跳转,请稍等...</p> </div> </header> </body> </html> ``` ## 这是数据库: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580568589_694404.jpg)

spring security cas单点登录拒绝访问

[b]cas服务端和cas客户端都已经配合,访问cas服务端可以登录,访问客户端应用资源的时候出现拒绝访问问题,但是[color=red]能成功跳转到cas服务端的login页面,输入账号密码后控制台打印显示出服务端登录成功,但是关于客户端的打印出现拒绝访问异常,而且httpSession不为null但是里面没值[/color][/b]。 初次使用spring security和cas望多多指教. 异常信息: [color=red][b]首次登录直接出现拒绝访问,但是却能跳转到cas 登录页面,[/b][/color] [quote] 信息: Server startup in 21955 ms 2012-6-6 11:51:31 org.apache.catalina.core.ApplicationContext log 信息: HTMLManager: init: Associated with Deployer 'Catalina:type=Deployer,host=localhost' 2012-6-6 11:51:31 org.apache.catalina.core.ApplicationContext log 信息: HTMLManager: init: Global resources are available 2012-6-6 11:51:31 org.apache.catalina.core.ApplicationContext log 信息: HTMLManager: list: Listing contexts for virtual host 'localhost' 2012-06-06 11:51:32,593 INFO [org.jasig.cas.ticket.registry.support.DefaultTicketRegistryCleaner] - <Beginning ticket cleanup.> 2012-06-06 11:51:32,593 INFO [org.jasig.cas.ticket.registry.support.DefaultTicketRegistryCleaner] - <0 tickets found to be removed.> 2012-06-06 11:51:32,593 INFO [org.jasig.cas.ticket.registry.support.DefaultTicketRegistryCleaner] - <Finished ticket cleanup.> 11:51:33,906 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 11:51:33,921 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository:127 - No HttpSession currently exists 11:51:33,921 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository:85 - No SecurityContext was available from the HttpSession: null. A new one will be created. 11:51:33,921 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 2 of 12 in additional filter chain; firing Filter: 'LogoutFilter' 11:51:33,921 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 3 of 12 in additional filter chain; firing Filter: 'CasAuthenticationFilter' 11:51:33,937 DEBUG org.springframework.security.cas.web.CasAuthenticationFilter:311 - serviceTicketRequest = false 11:51:33,937 DEBUG org.springframework.security.cas.web.CasAuthenticationFilter:362 - proxyReceptorConfigured = false 11:51:33,937 DEBUG org.springframework.security.cas.web.CasAuthenticationFilter:349 - proxyReceptorRequest = false 11:51:33,937 DEBUG org.springframework.security.cas.web.CasAuthenticationFilter:327 - proxyTicketRequest = false 11:51:33,937 DEBUG org.springframework.security.cas.web.CasAuthenticationFilter:262 - requiresAuthentication = false 11:51:33,937 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 4 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' 11:51:33,937 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 5 of 12 in additional filter chain; firing Filter: 'DefaultLoginPageGeneratingFilter' 11:51:33,937 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 6 of 12 in additional filter chain; firing Filter: 'BasicAuthenticationFilter' 11:51:33,937 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' 11:51:33,937 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' 11:51:33,937 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' 11:51:33,937 DEBUG org.springframework.security.web.authentication.AnonymousAuthenticationFilter:102 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS' 11:51:33,937 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter' 11:51:33,937 DEBUG org.springframework.security.web.session.SessionManagementFilter:91 - Requested session IDFED78FFF2BDBC0647461CBFA29AB9B23 is invalid. 11:51:33,937 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' 11:51:33,937 DEBUG org.springframework.security.web.FilterChainProxy:318 - /index.jsp at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' 11:51:33,937 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor:193 - Secure object: FilterInvocation: URL: /index.jsp; Attributes: [ROLE_USER] 11:51:33,937 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor:298 - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS 11:51:33,937 DEBUG org.springframework.security.access.vote.AffirmativeBased:65 - Voter: org.springframework.security.access.vote.RoleVoter@13e02ed, returned: -1 11:51:33,953 DEBUG org.springframework.security.access.vote.AffirmativeBased:65 - Voter: org.springframework.security.access.vote.AuthenticatedVoter@322394, returned: 0 11:51:33,968 DEBUG org.springframework.security.web.access.ExceptionTranslationFilter:165 - Access is denied (user is anonymous); redirecting to authentication entry point org.springframework.security.access.AccessDeniedException: Access is denied at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83) at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:205) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:114) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:91) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) 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:293) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:877) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:594) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1675) at java.lang.Thread.run(Thread.java:662) 11:51:33,984 DEBUG org.springframework.security.web.savedrequest.HttpSessionRequestCache:41 - DefaultSavedRequest added to Session: DefaultSavedRequest[http://localhost:8080/Cas_Client/] 11:51:33,984 DEBUG org.springframework.security.web.access.ExceptionTranslationFilter:185 - Calling Authentication entry point. 11:51:33,984 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository:269 - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 11:51:34,015 DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter:97 - SecurityContextHolder now cleared, as request processing completed 2012-06-06 11:51:34,921 INFO [org.jasig.cas.web.flow.InitialFlowSetupAction] - <Setting path for cookies to: /casServer/> [/quote] [color=red][b]跳转到登录页面后输入账号密码出现cas服务端的信息正常,但是关于cas客户端的和上面的异常一样:[/b][/color] 打印信息: [quote] 2012-06-06 12:03:21,625 INFO [org.jasig.cas.services.DefaultServicesManagerImpl] - <Reloading registered services.> 2012-06-06 12:03:21,625 INFO [org.jasig.cas.services.DefaultServicesManagerImpl] - <Loaded 0 services.> start[1338955402531] time[603] tag[QueryDatabaseAuthenticationHandler] 2012-06-06 12:03:23,125 INFO [org.jasig.cas.authentication.AuthenticationManagerImpl] - <AuthenticationHandler: org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler successfully authenticated the user which provided the following credentials: [username: wucht]> 2012-06-06 12:03:23,234 INFO [org.jasig.cas.authentication.AuthenticationManagerImpl] - <Resolved principal wucht> 2012-06-06 12:03:23,234 INFO [org.jasig.cas.authentication.AuthenticationManagerImpl] - <Principal found: wucht> 2012-06-06 12:03:23,250 INFO [com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager] - <Audit trail record BEGIN ============================================================= WHO: [username: wucht] WHAT: supplied credentials: [username: wucht] ACTION: AUTHENTICATION_SUCCESS APPLICATION: CAS WHEN: Wed Jun 06 12:03:23 CST 2012 CLIENT IP ADDRESS: 127.0.0.1 SERVER IP ADDRESS: 127.0.0.1 ============================================================= > 2012-06-06 12:03:23,250 INFO [com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager] - <Audit trail record BEGIN ============================================================= WHO: [username: wucht] WHAT: TGT-1-0WNh4MDLT57myMG77eF54B9ix5oQP0OItPnVBGDZBYac9Bj42E-casServer ACTION: TICKET_GRANTING_TICKET_CREATED APPLICATION: CAS WHEN: Wed Jun 06 12:03:23 CST 2012 CLIENT IP ADDRESS: 127.0.0.1 SERVER IP ADDRESS: 127.0.0.1 ============================================================= > 2012-06-06 12:03:23,265 INFO [org.jasig.cas.CentralAuthenticationServiceImpl] - <Granted service ticket [ST-1-eOK4CG7zd7cApkahlva9-casServer] for service [http://localhost:8080/Cas_Client/j_acegi_cas_security_check] for user [wucht]> 2012-06-06 12:03:23,265 INFO [com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager] - <Audit trail record BEGIN ============================================================= WHO: wucht WHAT: ST-1-eOK4CG7zd7cApkahlva9-casServer for http://localhost:8080/Cas_Client/j_acegi_cas_security_check ACTION: SERVICE_TICKET_CREATED APPLICATION: CAS WHEN: Wed Jun 06 12:03:23 CST 2012 CLIENT IP ADDRESS: 127.0.0.1 SERVER IP ADDRESS: 127.0.0.1 ============================================================= > 12:03:23,296 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 12:03:23,296 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository:139 - HttpSession returned null object for SPRING_SECURITY_CONTEXT 12:03:23,296 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository:85 - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@1ef3d12. A new one will be created. 12:03:23,296 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 2 of 12 in additional filter chain; firing Filter: 'LogoutFilter' 12:03:23,296 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 3 of 12 in additional filter chain; firing Filter: 'CasAuthenticationFilter' 12:03:23,296 DEBUG org.springframework.security.cas.web.CasAuthenticationFilter:311 - serviceTicketRequest = false 12:03:23,296 DEBUG org.springframework.security.cas.web.CasAuthenticationFilter:362 - proxyReceptorConfigured = false 12:03:23,296 DEBUG org.springframework.security.cas.web.CasAuthenticationFilter:349 - proxyReceptorRequest = false 12:03:23,296 DEBUG org.springframework.security.cas.web.CasAuthenticationFilter:327 - proxyTicketRequest = false 12:03:23,296 DEBUG org.springframework.security.cas.web.CasAuthenticationFilter:262 - requiresAuthentication = false 12:03:23,296 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 4 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' 12:03:23,296 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 5 of 12 in additional filter chain; firing Filter: 'DefaultLoginPageGeneratingFilter' 12:03:23,296 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 6 of 12 in additional filter chain; firing Filter: 'BasicAuthenticationFilter' 12:03:23,296 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' 12:03:23,296 DEBUG org.springframework.security.web.savedrequest.DefaultSavedRequest:309 - pathInfo: both null (property equals) 12:03:23,296 DEBUG org.springframework.security.web.savedrequest.DefaultSavedRequest:317 - queryString: arg1=null; arg2=ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer (property not equals) 12:03:23,296 DEBUG org.springframework.security.web.savedrequest.HttpSessionRequestCache:75 - saved request doesn't match 12:03:23,296 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' 12:03:23,296 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' 12:03:23,296 DEBUG org.springframework.security.web.authentication.AnonymousAuthenticationFilter:102 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@6fa86552: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffd148a: RemoteIpAddress: 127.0.0.1; SessionId: 659060E504E41E2F28CF873803A07F81; Granted Authorities: ROLE_ANONYMOUS' 12:03:23,312 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter' 12:03:23,312 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' 12:03:23,312 DEBUG org.springframework.security.web.FilterChainProxy:318 - /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' 12:03:23,312 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor:193 - Secure object: FilterInvocation: URL: /j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer; Attributes: [ROLE_USER] 12:03:23,312 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor:298 - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@6fa86552: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffd148a: RemoteIpAddress: 127.0.0.1; SessionId: 659060E504E41E2F28CF873803A07F81; Granted Authorities: ROLE_ANONYMOUS 12:03:23,312 DEBUG org.springframework.security.access.vote.AffirmativeBased:65 - Voter: org.springframework.security.access.vote.RoleVoter@13e02ed, returned: -1 12:03:23,312 DEBUG org.springframework.security.access.vote.AffirmativeBased:65 - Voter: org.springframework.security.access.vote.AuthenticatedVoter@322394, returned: 0 12:03:23,312 DEBUG org.springframework.security.web.access.ExceptionTranslationFilter:165 - Access is denied (user is anonymous); redirecting to authentication entry point org.springframework.security.access.AccessDeniedException: Access is denied at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83) at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:205) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:114) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:91) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) 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:293) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:877) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:594) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1675) at java.lang.Thread.run(Thread.java:662) 12:03:23,312 DEBUG org.springframework.security.web.savedrequest.HttpSessionRequestCache:41 - DefaultSavedRequest added to Session: DefaultSavedRequest[http://localhost:8080/Cas_Client/j_acegi_cas_security_check?ticket=ST-1-eOK4CG7zd7cApkahlva9-casServer] 12:03:23,312 DEBUG org.springframework.security.web.access.ExceptionTranslationFilter:185 - Calling Authentication entry point. 12:03:23,312 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository:269 - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 12:03:23,343 DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter:97 - SecurityContextHolder now cleared, as request processing completed [/quote] [b]cas服务端配置:[/b] cas.properties [quote] #server.prefix=http://localhost:8080/cas #server.prefix=http://cas.wucht.com:8080/casServer server.prefix=http://localhost:8080/casServer cas.securityContext.serviceProperties.service=${server.prefix}/j_acegi_cas_security_check # Names of roles allowed to access the CAS service manager cas.securityContext.serviceProperties.adminRoles=ROLE_ADMIN cas.securityContext.casProcessingFilterEntryPoint.loginUrl=${server.prefix}/login cas.securityContext.ticketValidator.casServerUrlPrefix=${server.prefix} cas.themeResolver.defaultThemeName=cas-theme-default #cas.themeResolver.defaultThemeName=default cas.viewResolver.basename=default_views #host.name=cas host.name=casServer #database.hibernate.dialect=org.hibernate.dialect.OracleDialect database.hibernate.dialect=org.hibernate.dialect.MySQLDialect #database.hibernate.dialect=org.hibernate.dialect.HSQLDialect [/quote] deployerConfigContext.xml [quote] <?xml version="1.0" encoding="UTF-8"?> <!-- | deployerConfigContext.xml centralizes into one file some of the declarative configuration that | all CAS deployers will need to modify. | | This file declares some of the Spring-managed JavaBeans that make up a CAS deployment. | The beans declared in this file are instantiated at context initialization time by the Spring | ContextLoaderListener declared in web.xml. It finds this file because this | file is among those declared in the context parameter "contextConfigLocation". | | By far the most common change you will need to make in this file is to change the last bean | declaration to replace the default SimpleTestUsernamePasswordAuthenticationHandler with | one implementing your approach for authenticating usernames and passwords. +--> <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:sec="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> <!-- | This bean declares our AuthenticationManager. The CentralAuthenticationService service bean | declared in applicationContext.xml picks up this AuthenticationManager by reference to its id, | "authenticationManager". Most deployers will be able to use the default AuthenticationManager | implementation and so do not need to change the class of this bean. We include the whole | AuthenticationManager here in the userConfigContext.xml so that you can see the things you will | need to change in context. +--> <bean id="authenticationManager" class="org.jasig.cas.authentication.AuthenticationManagerImpl"> <!-- | This is the List of CredentialToPrincipalResolvers that identify what Principal is trying to authenticate. | The AuthenticationManagerImpl considers them in order, finding a CredentialToPrincipalResolver which | supports the presented credentials. | | AuthenticationManagerImpl uses these resolvers for two purposes. First, it uses them to identify the Principal | attempting to authenticate to CAS /login . In the default configuration, it is the DefaultCredentialsToPrincipalResolver | that fills this role. If you are using some other kind of credentials than UsernamePasswordCredentials, you will need to replace | DefaultCredentialsToPrincipalResolver with a CredentialsToPrincipalResolver that supports the credentials you are | using. | | Second, AuthenticationManagerImpl uses these resolvers to identify a service requesting a proxy granting ticket. | In the default configuration, it is the HttpBasedServiceCredentialsToPrincipalResolver that serves this purpose. | You will need to change this list if you are identifying services by something more or other than their callback URL. +--> <property name="credentialsToPrincipalResolvers"> <list> <!-- | UsernamePasswordCredentialsToPrincipalResolver supports the UsernamePasswordCredentials that we use for /login | by default and produces SimplePrincipal instances conveying the username from the credentials. | | If you've changed your LoginFormAction to use credentials other than UsernamePasswordCredentials then you will also | need to change this bean declaration (or add additional declarations) to declare a CredentialsToPrincipalResolver that supports the | Credentials you are using. +--> <bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver"> <!--增加此属性,为认证过的用户的Principal添加属性--> <property name="attributeRepository" ref="attributeRepository"></property> </bean> <!-- | HttpBasedServiceCredentialsToPrincipalResolver supports HttpBasedCredentials. It supports the CAS 2.0 approach of | authenticating services by SSL callback, extracting the callback URL from the Credentials and representing it as a | SimpleService identified by that callback URL. | | If you are representing services by something more or other than an HTTPS URL whereat they are able to | receive a proxy callback, you will need to change this bean declaration (or add additional declarations). +--> <bean class="org.jasig.cas.authentication.principal.HttpBasedServiceCredentialsToPrincipalResolver" /> </list> </property> <!-- | Whereas CredentialsToPrincipalResolvers identify who it is some Credentials might authenticate, | AuthenticationHandlers actually authenticate credentials. Here we declare the AuthenticationHandlers that | authenticate the Principals that the CredentialsToPrincipalResolvers identified. CAS will try these handlers in turn | until it finds one that both supports the Credentials presented and succeeds in authenticating. +--> <property name="authenticationHandlers"> <list> <!-- | This is the authentication handler that authenticates services by means of callback via SSL, thereby validating | a server side SSL certificate. +--> <bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler" p:httpClient-ref="httpClient" /> <!-- | This is the authentication handler declaration that every CAS deployer will need to change before deploying CAS | into production. The default SimpleTestUsernamePasswordAuthenticationHandler authenticates UsernamePasswordCredentials | where the username equals the password. You will need to replace this with an AuthenticationHandler that implements your | local authentication strategy. You might accomplish this by coding a new such handler and declaring | edu.someschool.its.cas.MySpecialHandler here, or you might use one of the handlers provided in the adaptors modules. +--> <!-- <bean class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" /> --> <!-- 数据库认证.wucht--> <bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler"> <property name="dataSource" ref="dataSource" /> <property name="sql" value="select password from users where name=?" /> </bean> </list> </property> </bean> <!-- DATABASE 增加数据源配置 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property> <property name="url"><value>jdbc:mysql://localhost:3306/mysql?useUnicode=true&amp;characterEncoding=utf-8</value></property> <property name="username"><value>root</value></property> <property name="password"><value>root</value></property> </bean> <!-- This bean defines the security roles for the Services Management application. Simple deployments can use the in-memory version. More robust deployments will want to use another option, such as the Jdbc version. The name of this should remain "userDetailsService" in order for Spring Security to find it. --> <!-- <sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused" authorities="ROLE_ADMIN" />--> <sec:user-service id="userDetailsService"> <sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused" authorities="ROLE_ADMIN" /> </sec:user-service> <!-- Bean that defines the attributes that a service may return. This example uses the Stub/Mock version. A real implementation may go against a database or LDAP server. The id should remain "attributeRepository" though. --> <!-- <bean id="attributeRepository" class="org.jasig.services.persondir.support.StubPersonAttributeDao"> <property name="backingMap"> <map> <entry key="uid" value="uid" /> <entry key="eduPersonAffiliation" value="eduPersonAffiliation" /> <entry key="groupMembership" value="groupMembership" /> </map> </property> </bean> --> <!-- 使用SingleRowJdbcPersonAttributeDao 获取更多用户的信息 --> <bean id="attributeRepository" class="org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao"> <constructor-arg index="0" ref="dataSource"/> <constructor-arg index="1" value="select role_name from role where login_name = ?"/> <!--这里的key需写username,value对应数据库用户名字段 --> <property name="queryAttributeMapping"> <map> <entry key="username" value="login_name"/> </map> </property> <!--key对应数据库字段,value对应客户端获取参数 --> <!-- 返回数据认证后的数据 --> <property name="resultAttributeMapping"> <map> <!--这个从数据库中获取的角色,用于在应用中security的权限验证--> <entry key="role_name" value="authorities"/> </map> </property> </bean> <!-- Sample, in-memory data store for the ServiceRegistry. A real implementation would probably want to replace this with the JPA-backed ServiceRegistry DAO The name of this bean should remain "serviceRegistryDao". --> <bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl"> <!-- <property name="registeredServices"> <list> <bean class="org.jasig.cas.services.RegisteredServiceImpl"> <property name="id" value="0" /> <property name="name" value="HTTP" /> <property name="description" value="Only Allows HTTP Urls" /> <property name="serviceId" value="http://**" /> <property name="evaluationOrder" value="10000001" /> </bean> <bean class="org.jasig.cas.services.RegisteredServiceImpl"> <property name="id" value="1" /> <property name="name" value="HTTPS" /> <property name="description" value="Only Allows HTTPS Urls" /> <property name="serviceId" value="https://**" /> <property name="evaluationOrder" value="10000002" /> </bean> <bean class="org.jasig.cas.services.RegisteredServiceImpl"> <property name="id" value="2" /> <property name="name" value="IMAPS" /> <property name="description" value="Only Allows HTTPS Urls" /> <property name="serviceId" value="imaps://**" /> <property name="evaluationOrder" value="10000003" /> </bean> <bean class="org.jasig.cas.services.RegisteredServiceImpl"> <property name="id" value="3" /> <property name="name" value="IMAP" /> <property name="description" value="Only Allows IMAP Urls" /> <property name="serviceId" value="imap://**" /> <property name="evaluationOrder" value="10000004" /> </bean> </list> </property> --> </bean> <bean id="auditTrailManager" class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" /> </beans> [/quote] [b]spring的配置代码如下:[/b][code="ruby"] <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:beans="http://www.springframework.org/schema/beans" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd" default-lazy-init="true"> <!-- entry-point-ref="casEntryPoint"作用是认证的入口,是一个实现AuthenticationEntryPoint接口的类 ,为ExceptionTranslationFilter类提供认证依据, <custom-filter position="FORM_LOGIN_FILTER" ref="casFilter"/> 使用自定义的Filter,放置在过滤器链的FORM_LOGIN_FILTER的位置 casEntryPoint只是提供认证入口的作用,当没有权限,将跳转到该地址。 casFilter是处理CAS service ticket的,当无权访问时,会使用casEntryPoint提供认证入口 --> <http auto-config="true" entry-point-ref="casEntryPoint" access-denied-page="/403.jsp"> <intercept-url pattern="/**" access="ROLE_USER" /> <!-- ROLE_ADMIN--> <!-- logout-success-url="/login.html" --> <!-- 注销时需要先注销应用程序,再注销cas中心认证服务 --> <logout logout-url="/logout.html" success-handler-ref="casLogoutSuccessHandler" /> <custom-filter position="CAS_FILTER" ref="casFilter" /> </http> <authentication-manager alias="authenticationManager"> <authentication-provider ref="casAuthenticationProvider" /> </authentication-manager> <!-- cas中心认证服务入口 --> <beans:bean id="casEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint"> <beans:property name="loginUrl" value="http://localhost:8080/casServer/login" /> <beans:property name="serviceProperties" ref="serviceProperties" /> </beans:bean> <!-- cas中心认证服务配置 --> <beans:bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties"> <beans:property name="service" value="http://localhost:8080/Cas_Client/j_acegi_cas_security_check" /> <beans:property name="sendRenew" value="false" /> </beans:bean> <!-- CAS service ticket(中心认证服务凭据)验证 --> <beans:bean id="casFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter"> <beans:property name="authenticationManager" ref="authenticationManager" /> <!-- <beans:property name="authenticationFailureHandler">--> <!-- <beans:bean--> <!-- class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">--> <!-- <beans:property name="defaultFailureUrl"--> <!-- value="/logout.html" />--> <!-- </beans:bean>--> <!-- </beans:property>--> <!-- 登录成功后的页面,如果是固定的。否则 ref="authenticationSuccessHandler" --> <!-- <beans:property name="authenticationSuccessHandler">--> <!-- <beans:bean--> <!-- class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">--> <!-- <beans:property name="defaultTargetUrl"--> <!-- value="/index.jsp" />--> <!-- </beans:bean>--> <!-- </beans:property>--> </beans:bean> <!-- 从Cas Server得到用户信息 --> <beans:bean id="authenticationUserDetailsService" class="org.springframework.security.cas.userdetails.GrantedAuthorityFromAssertionAttributesUserDetailsService"> <beans:constructor-arg> <beans:array> <beans:value>authorities</beans:value> </beans:array> </beans:constructor-arg> </beans:bean> <beans:bean id="userDetailsService" class="com.reportstart.security.service.impl.BocUserDetaislServiceImpl"> <!-- <beans:property name="userDao">--> <!-- <beans:ref bean="userDao" />--> <!-- </beans:property>--> </beans:bean> <!-- <beans:bean id="authenticationUserDetailsService"--> <!-- class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">--> <!-- <beans:property name="userDetailsService">--> <!-- <beans:ref local="userDetailsService" />--> <!-- </beans:property>--> <!-- </beans:bean>--> <beans:bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider"> <!-- 使用自定义service获取用户信息 --> <!-- <beans:property name="authenticationUserDetailsService"--> <!-- ref="casAuthenticationUserDetailsService" />--> <!-- 通过Cas Server获取用户信息 --> <beans:property name="authenticationUserDetailsService" ref="authenticationUserDetailsService" /> <beans:property name="serviceProperties" ref="serviceProperties" /> <beans:property name="ticketValidator"> <beans:bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator"> <beans:constructor-arg index="0" value="http://localhost:8080/casServer" /> </beans:bean> </beans:property> <!-- 自定义cas客户端应用标示.wucht.2012-6-4(每个cas客户端都需要一个key标示用于区分不同cas客户端) --> <beans:property name="key" value="Cas_Client" /> </beans:bean> <!-- 注销 --> <beans:bean id="casLogoutSuccessHandler" class="com.wucht.test.CasLogoutSuccessHandler"> </beans:bean> </beans:beans>[/code]

一开始自己配置的activiti的运行web时报错以为是环境的问题,后面到网上借鉴改了一些还是没用。

ssm框架整合activiti流程,在控制器中使用注入有关activities的一些Service如:RepositoryService、ProcessEngine、TaskService、RuntimeService、HistoryService,运行web项目后报错,后面网上借鉴了一些activitie的一些配置还是没用,o依.springframework.beans.factory.BeanCreationException: Error creating bean with name 'processEngineConfiguration' defined in file [F:\宏图软件学院办公软件项目\SchoolSystem\target\SSMTest\WEB-INF\classes\spring-activiti.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1469) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748) ``` 这个是activiti.cfg.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:jee="http://www.springframework.org/schema/jee" 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/context http://www.springframework.org/schema/context/spring-context-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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置数据源 --> <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration"> <property name="jdbcDriver" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/schoolsystem?characterEncoding=utf8"></property> <property name="jdbcUsername" value="root"></property> <property name="jdbcPassword" value="1234"></property> <property name="databaseSchemaUpdate" value="true"></property> </bean> <!-- 配置流程引擎工厂 --> <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean"> <property name="processEngineConfiguration" ref="processEngineConfiguration"></property> </bean> </beans> ``` 这个是spring-activiti.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:jee="http://www.springframework.org/schema/jee" 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/context http://www.springframework.org/schema/context/spring-context-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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 用于创建流程引擎的对象 --> <bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration"> <property name="transactionManager" ref="transactionManager"></property> <property name="dataSource" ref="druidDataSource"></property> <property name="databaseSchemaUpdate" value="true"></property> </bean> <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean"> <property name="processEngineConfiguration" ref="processEngineConfiguration"></property> </bean> </beans> ``` 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" 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"> <!-- 配置整合mybatis过程 --> <!-- 1.配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 2.数据库连接池 --> <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc_driverClassName}" /> <property name="url" value="${jdbc_url}"/> <property name="username" value="${jdbc_username}"/> <property name="password" value="${jdbc_password}"/> <!-- 初始化连接大小 --> <property name="initialSize" value="5"/> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="50"/> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20"/> <!-- 连接池最小空闲 --> <property name="minIdle" value="5"/> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000"/> <property name="validationQuery" value="${validationQuery}"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000"/> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true"/> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800"/> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true"/> <!-- 监控数据库 --> <property name="filters" value="mergeStat"/> </bean> <!-- 3.配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="druidDataSource" /> <!-- 配置MyBaties全局配置文件:mybatis-config.xml --> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 扫描vo包 使用别名 --> <property name="typeAliasesPackage" value="Vo" /> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:Mapper/*.xml" /> </bean> <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="Mapper"/> </bean> </beans> ``` 这个是spring-service.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" 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"> <!-- 扫描service包下所有使用注解的类型 --> <context:component-scan base-package="Service" /> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="druidDataSource" /> </bean> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> ``` 这个是spring-web.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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--配置spring mvc--> <!--1,开启springmvc注解模式 a.自动注册 DefaultAnnotationHandlerMapping, AnnotationMethodHandlerAdapter b.默认提供一系列的功能:数据绑定,数字和日期的format@NumberFormat,@DateTimeFormat c:xml,json的默认读写支持--> <mvc:annotation-driven conversion-service="dateUtil"></mvc:annotation-driven> <!--2.静态资源默认servlet配置--> <!-- 1).加入对静态资源处理:排除后缀 js,gif,png, 等静态资源的请求不会进入控制器 2).允许使用 "/" 做整体映射 --> <mvc:default-servlet-handler/> <!--3:配置JSP 显示ViewResolver--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--4:扫描web所有的 controller--> <context:component-scan base-package="Control"/> <!-- FastJson注入 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!-- 避免IE执行AJAX时,返回JSON出现下载文件 --> <!-- FastJson --> <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 --> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <property name="features"> <array value-type="com.alibaba.fastjson.serializer.SerializerFeature"> <!-- 避免循环引用 --> <value>DisableCircularReferenceDetect</value> <!-- 是否输出值为null的字段 --> <value>WriteMapNullValue</value> <!-- 数值字段如果为null,输出为0,而非null --> <value>WriteNullNumberAsZero</value> <!-- 字符类型字段如果为null,输出为"",而非null --> <value>WriteNullStringAsEmpty</value> <!-- List字段如果为null,输出为[],而非null --> <value>WriteNullListAsEmpty</value> <!-- Boolean字段如果为null,输出为false,而非null --> <value>WriteNullBooleanAsFalse</value> </array> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 拦截器配置 --> <mvc:interceptors> <mvc:interceptor> <!-- 拦截URL,拦截 admin 开头的所有请求 --> <mvc:mapping path="/**" /> <!-- 添加不会被拦截的url --> <mvc:exclude-mapping path="/login/**" /> <!-- 拦截请求交给,哪个拦截器 --> <bean class="Interceptor.MyInterceptor"/> </mvc:interceptor> <!-- 国际化拦截器 --> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="lang"/> </bean> </mvc:interceptors> <bean id="dateUtil" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" > <property name="converters" > <list> <bean class="Base.DateUtil"></bean> </list> </property> </bean> <!-- 文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 配置文件上传最大大小(字节)这里是1M --> <property name="maxUploadSize" value="1048576"/> </bean> <!-- 国际化资源文件 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <!-- 表示多语言配置文件在根路径下,以i18n开头的文件--> <property name="basename" value="i18n"/> <property name="useCodeAsDefaultMessage" value="true"/> </bean> <!-- 配置SessionLocaleResolver用于将Locale对象存储于Session中供后续使用 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> </beans> ``` ```

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)

正确选择比瞎努力更重要!

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

字节跳动面试官竟然问了我JDBC?

轻松等回家通知

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

阿里面试官让我用Zk(Zookeeper)实现分布式锁

他可能没想到,我当场手写出来了

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

2020春招面试了10多家大厂,我把问烂了的数据库事务知识点总结了一下

2020年截止目前,我面试了阿里巴巴、腾讯、美团、拼多多、京东、快手等互联网大厂。我发现数据库事务在面试中出现的次数非常多。

爬虫(101)爬点重口味的

小弟最近在学校无聊的很哪,浏览网页突然看到一张图片,都快流鼻血。。。然后小弟冥思苦想,得干一点有趣的事情python 爬虫库安装https://s.taobao.com/api?_ks...

在拼多多上班,是一种什么样的体验?我心态崩了呀!

之前有很多读者咨询我:武哥,在拼多多上班是一种什么样的体验?由于一直很忙,没抽出时间来和大家分享。上周末特地花点时间来写了一篇文章,跟大家分享一下拼多多的日常。 1. 倒时差的作息 可能很多小伙伴都听说了,拼多多加班很严重。这怎么说呢?作息上确实和其他公司有点区别,大家知道 996,那么自然也就能理解拼多多的“11 11 6”了。 所以当很多小伙伴早上出门时,他们是这样的: 我们是这样的: 当...

应聘3万的职位,有必要这么刁难我么。。。沙雕。。。

又一次被面试官带到坑里面了。面试官:springmvc用过么?我:用过啊,经常用呢面试官:springmvc中为什么需要用父子容器?我:嗯。。。没听明白你说的什么。面试官:就是contr...

太狠了,疫情期间面试,一个问题砍了我5000!

疫情期间找工作确实有点难度,想拿到满意的薪资,确实要点实力啊!面试官:Spring中的@Value用过么,介绍一下我:@Value可以标注在字段上面,可以将外部配置文件中的数据,比如可以...

自学编程的 6 个致命误区

嗨,小伙伴们大家好,我是沉默王二。本篇文章来和大家聊聊自学编程中的一些误区——这是我在 B 站上看了羊哥的一期视频后有感而发的文章。因为确实有很多读者也曾私信问过我这些方面的问题,很有代表性,所以我就结合自己的亲身体会来谈一谈,希望对小伙伴们有所启发。 01、追求时髦 所谓基础不牢,地动山摇啊。可很多小伙伴压根就没注意过这个问题,市面上出什么新鲜的技术就想去尝试,结果把自己学的乱七八糟,心灰意冷...

漫画:什么是 “眼镜蛇效应” ?

世界是复杂的。每当你做出一个决定的时候,你的出发点通常是好的,但结果一定会好吗?在印度的某个地区,当地野生的眼镜蛇非常泛滥。众所周知,眼镜蛇有剧毒,又具有很强的攻击性,给当地居民的生命安...

大海啊,夏天啊,全是腿啊,python带你爬取长腿妹子图

知乎还是很友好的 总体来说没啥难度 简单说下思路 1.评论是动态加载的 直接找json接口 2.分析接口参数,我测试的时候一次最多能拿20条数据(不过我还是一条一条拿的) 3.循环发送请求,其实可以先把评论数抓下来再for range 我只是比较懒(。・ω・。) 4.有的评论没图片,简单try一下或者if处理 首先需要引入爬虫库 import requests from bs4 import Be...

立即提问
相关内容推荐